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 },
368 for (const auto &LC : LibraryCalls) {
369 setLibcallName(LC.Op, LC.Name);
370 setLibcallCallingConv(LC.Op, LC.CC);
374 // Use divmod compiler-rt calls for iOS 5.0 and later.
375 if (Subtarget->getTargetTriple().isiOS() &&
376 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
377 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
378 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
381 // The half <-> float conversion functions are always soft-float, but are
382 // needed for some targets which use a hard-float calling convention by
384 if (Subtarget->isAAPCS_ABI()) {
385 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
386 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
390 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
391 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
394 if (Subtarget->isThumb1Only())
395 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
397 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
398 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
399 !Subtarget->isThumb1Only()) {
400 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
401 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
404 for (MVT VT : MVT::vector_valuetypes()) {
405 for (MVT InnerVT : MVT::vector_valuetypes()) {
406 setTruncStoreAction(VT, InnerVT, Expand);
407 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
408 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
409 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
412 setOperationAction(ISD::MULHS, VT, Expand);
413 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
414 setOperationAction(ISD::MULHU, VT, Expand);
415 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
417 setOperationAction(ISD::BSWAP, VT, Expand);
420 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
424 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
426 if (Subtarget->hasNEON()) {
427 addDRTypeForNEON(MVT::v2f32);
428 addDRTypeForNEON(MVT::v8i8);
429 addDRTypeForNEON(MVT::v4i16);
430 addDRTypeForNEON(MVT::v2i32);
431 addDRTypeForNEON(MVT::v1i64);
433 addQRTypeForNEON(MVT::v4f32);
434 addQRTypeForNEON(MVT::v2f64);
435 addQRTypeForNEON(MVT::v16i8);
436 addQRTypeForNEON(MVT::v8i16);
437 addQRTypeForNEON(MVT::v4i32);
438 addQRTypeForNEON(MVT::v2i64);
440 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441 // neither Neon nor VFP support any arithmetic operations on it.
442 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443 // supported for v4f32.
444 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447 // FIXME: Code duplication: FDIV and FREM are expanded always, see
448 // ARMTargetLowering::addTypeForNEON method for details.
449 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451 // FIXME: Create unittest.
452 // In another words, find a way when "copysign" appears in DAG with vector
454 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455 // FIXME: Code duplication: SETCC has custom operation action, see
456 // ARMTargetLowering::addTypeForNEON method for details.
457 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458 // FIXME: Create unittest for FNEG and for FABS.
459 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495 // Mark v2f32 intrinsics.
496 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512 // Neon does not support some operations on v1i64 and v2i64 types.
513 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514 // Custom handling for some quad-vector types to detect VMULL.
515 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518 // Custom handling for some vector types to avoid expensive expansions
519 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526 // a destination type that is wider than the source, and nor does
527 // it have a FP_TO_[SU]INT instruction with a narrower destination than
529 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
535 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
537 // NEON does not have single instruction CTPOP for vectors with element
538 // types wider than 8-bits. However, custom lowering can leverage the
539 // v8i8/v16i8 vcnt instruction.
540 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
541 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
542 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
543 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
545 // NEON does not have single instruction CTTZ for vectors.
546 setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
547 setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
548 setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
549 setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
551 setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
552 setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
553 setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
554 setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
556 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
557 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
558 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
559 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
561 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
562 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
563 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
564 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
566 // NEON only has FMA instructions as of VFP4.
567 if (!Subtarget->hasVFP4()) {
568 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
569 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
572 setTargetDAGCombine(ISD::INTRINSIC_VOID);
573 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
574 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
575 setTargetDAGCombine(ISD::SHL);
576 setTargetDAGCombine(ISD::SRL);
577 setTargetDAGCombine(ISD::SRA);
578 setTargetDAGCombine(ISD::SIGN_EXTEND);
579 setTargetDAGCombine(ISD::ZERO_EXTEND);
580 setTargetDAGCombine(ISD::ANY_EXTEND);
581 setTargetDAGCombine(ISD::SELECT_CC);
582 setTargetDAGCombine(ISD::BUILD_VECTOR);
583 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
584 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
585 setTargetDAGCombine(ISD::STORE);
586 setTargetDAGCombine(ISD::FP_TO_SINT);
587 setTargetDAGCombine(ISD::FP_TO_UINT);
588 setTargetDAGCombine(ISD::FDIV);
589 setTargetDAGCombine(ISD::LOAD);
591 // It is legal to extload from v4i8 to v4i16 or v4i32.
592 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
594 for (MVT VT : MVT::integer_vector_valuetypes()) {
595 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
596 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
597 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
602 // ARM and Thumb2 support UMLAL/SMLAL.
603 if (!Subtarget->isThumb1Only())
604 setTargetDAGCombine(ISD::ADDC);
606 if (Subtarget->isFPOnlySP()) {
607 // When targetting a floating-point unit with only single-precision
608 // operations, f64 is legal for the few double-precision instructions which
609 // are present However, no double-precision operations other than moves,
610 // loads and stores are provided by the hardware.
611 setOperationAction(ISD::FADD, MVT::f64, Expand);
612 setOperationAction(ISD::FSUB, MVT::f64, Expand);
613 setOperationAction(ISD::FMUL, MVT::f64, Expand);
614 setOperationAction(ISD::FMA, MVT::f64, Expand);
615 setOperationAction(ISD::FDIV, MVT::f64, Expand);
616 setOperationAction(ISD::FREM, MVT::f64, Expand);
617 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
618 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
619 setOperationAction(ISD::FNEG, MVT::f64, Expand);
620 setOperationAction(ISD::FABS, MVT::f64, Expand);
621 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
622 setOperationAction(ISD::FSIN, MVT::f64, Expand);
623 setOperationAction(ISD::FCOS, MVT::f64, Expand);
624 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
625 setOperationAction(ISD::FPOW, MVT::f64, Expand);
626 setOperationAction(ISD::FLOG, MVT::f64, Expand);
627 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
628 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
629 setOperationAction(ISD::FEXP, MVT::f64, Expand);
630 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
631 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
632 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
633 setOperationAction(ISD::FRINT, MVT::f64, Expand);
634 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
635 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
636 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
637 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
638 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
639 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
640 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
641 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
642 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
643 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
646 computeRegisterProperties(Subtarget->getRegisterInfo());
648 // ARM does not have floating-point extending loads.
649 for (MVT VT : MVT::fp_valuetypes()) {
650 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
651 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
654 // ... or truncating stores
655 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
656 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
657 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
659 // ARM does not have i1 sign extending load.
660 for (MVT VT : MVT::integer_valuetypes())
661 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
663 // ARM supports all 4 flavors of integer indexed load / store.
664 if (!Subtarget->isThumb1Only()) {
665 for (unsigned im = (unsigned)ISD::PRE_INC;
666 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
667 setIndexedLoadAction(im, MVT::i1, Legal);
668 setIndexedLoadAction(im, MVT::i8, Legal);
669 setIndexedLoadAction(im, MVT::i16, Legal);
670 setIndexedLoadAction(im, MVT::i32, Legal);
671 setIndexedStoreAction(im, MVT::i1, Legal);
672 setIndexedStoreAction(im, MVT::i8, Legal);
673 setIndexedStoreAction(im, MVT::i16, Legal);
674 setIndexedStoreAction(im, MVT::i32, Legal);
678 setOperationAction(ISD::SADDO, MVT::i32, Custom);
679 setOperationAction(ISD::UADDO, MVT::i32, Custom);
680 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
681 setOperationAction(ISD::USUBO, MVT::i32, Custom);
683 // i64 operation support.
684 setOperationAction(ISD::MUL, MVT::i64, Expand);
685 setOperationAction(ISD::MULHU, MVT::i32, Expand);
686 if (Subtarget->isThumb1Only()) {
687 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
688 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
690 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
691 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
692 setOperationAction(ISD::MULHS, MVT::i32, Expand);
694 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
695 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
696 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
697 setOperationAction(ISD::SRL, MVT::i64, Custom);
698 setOperationAction(ISD::SRA, MVT::i64, Custom);
700 if (!Subtarget->isThumb1Only()) {
701 // FIXME: We should do this for Thumb1 as well.
702 setOperationAction(ISD::ADDC, MVT::i32, Custom);
703 setOperationAction(ISD::ADDE, MVT::i32, Custom);
704 setOperationAction(ISD::SUBC, MVT::i32, Custom);
705 setOperationAction(ISD::SUBE, MVT::i32, Custom);
708 // ARM does not have ROTL.
709 setOperationAction(ISD::ROTL, MVT::i32, Expand);
710 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
711 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
712 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
713 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
715 // These just redirect to CTTZ and CTLZ on ARM.
716 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
717 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
719 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
721 // Only ARMv6 has BSWAP.
722 if (!Subtarget->hasV6Ops())
723 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
725 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
726 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
727 // These are expanded into libcalls if the cpu doesn't have HW divider.
728 setOperationAction(ISD::SDIV, MVT::i32, Expand);
729 setOperationAction(ISD::UDIV, MVT::i32, Expand);
732 // FIXME: Also set divmod for SREM on EABI/androideabi
733 setOperationAction(ISD::SREM, MVT::i32, Expand);
734 setOperationAction(ISD::UREM, MVT::i32, Expand);
735 // Register based DivRem for AEABI (RTABI 4.2)
736 if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
737 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
738 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
739 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
740 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
741 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
742 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
743 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
744 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
746 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
747 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
748 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
749 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
750 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
751 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
752 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
753 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
755 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
756 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
758 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
759 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
762 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
763 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
764 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
765 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
766 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
768 setOperationAction(ISD::TRAP, MVT::Other, Legal);
770 // Use the default implementation.
771 setOperationAction(ISD::VASTART, MVT::Other, Custom);
772 setOperationAction(ISD::VAARG, MVT::Other, Expand);
773 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
774 setOperationAction(ISD::VAEND, MVT::Other, Expand);
775 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
776 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
778 if (!Subtarget->isTargetMachO()) {
779 // Non-MachO platforms may return values in these registers via the
780 // personality function.
781 setExceptionPointerRegister(ARM::R0);
782 setExceptionSelectorRegister(ARM::R1);
785 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
786 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
788 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
790 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
791 // the default expansion. If we are targeting a single threaded system,
792 // then set them all for expand so we can lower them later into their
794 if (TM.Options.ThreadModel == ThreadModel::Single)
795 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
796 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
797 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
798 // to ldrex/strex loops already.
799 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
801 // On v8, we have particularly efficient implementations of atomic fences
802 // if they can be combined with nearby atomic loads and stores.
803 if (!Subtarget->hasV8Ops()) {
804 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
805 setInsertFencesForAtomic(true);
808 // If there's anything we can use as a barrier, go through custom lowering
810 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
811 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
813 // Set them all for expansion, which will force libcalls.
814 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
815 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
816 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
817 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
818 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
819 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
820 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
821 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
822 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
823 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
824 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
825 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
826 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
827 // Unordered/Monotonic case.
828 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
829 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
832 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
834 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
835 if (!Subtarget->hasV6Ops()) {
836 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
837 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
839 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
841 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
842 !Subtarget->isThumb1Only()) {
843 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
844 // iff target supports vfp2.
845 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
846 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
849 // We want to custom lower some of our intrinsics.
850 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
851 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
852 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
853 setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
854 if (Subtarget->isTargetDarwin())
855 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
857 setOperationAction(ISD::SETCC, MVT::i32, Expand);
858 setOperationAction(ISD::SETCC, MVT::f32, Expand);
859 setOperationAction(ISD::SETCC, MVT::f64, Expand);
860 setOperationAction(ISD::SELECT, MVT::i32, Custom);
861 setOperationAction(ISD::SELECT, MVT::f32, Custom);
862 setOperationAction(ISD::SELECT, MVT::f64, Custom);
863 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
864 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
865 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
867 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
868 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
869 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
870 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
871 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
873 // We don't support sin/cos/fmod/copysign/pow
874 setOperationAction(ISD::FSIN, MVT::f64, Expand);
875 setOperationAction(ISD::FSIN, MVT::f32, Expand);
876 setOperationAction(ISD::FCOS, MVT::f32, Expand);
877 setOperationAction(ISD::FCOS, MVT::f64, Expand);
878 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
879 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
880 setOperationAction(ISD::FREM, MVT::f64, Expand);
881 setOperationAction(ISD::FREM, MVT::f32, Expand);
882 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
883 !Subtarget->isThumb1Only()) {
884 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
885 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
887 setOperationAction(ISD::FPOW, MVT::f64, Expand);
888 setOperationAction(ISD::FPOW, MVT::f32, Expand);
890 if (!Subtarget->hasVFP4()) {
891 setOperationAction(ISD::FMA, MVT::f64, Expand);
892 setOperationAction(ISD::FMA, MVT::f32, Expand);
895 // Various VFP goodness
896 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
897 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
898 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
899 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
900 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
903 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
904 if (!Subtarget->hasFP16()) {
905 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
906 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
910 // Combine sin / cos into one node or libcall if possible.
911 if (Subtarget->hasSinCos()) {
912 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
913 setLibcallName(RTLIB::SINCOS_F64, "sincos");
914 if (Subtarget->getTargetTriple().isiOS()) {
915 // For iOS, we don't want to the normal expansion of a libcall to
916 // sincos. We want to issue a libcall to __sincos_stret.
917 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
918 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
922 // FP-ARMv8 implements a lot of rounding-like FP operations.
923 if (Subtarget->hasFPARMv8()) {
924 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
925 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
926 setOperationAction(ISD::FROUND, MVT::f32, Legal);
927 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
928 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
929 setOperationAction(ISD::FRINT, MVT::f32, Legal);
930 if (!Subtarget->isFPOnlySP()) {
931 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
932 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
933 setOperationAction(ISD::FROUND, MVT::f64, Legal);
934 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
935 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
936 setOperationAction(ISD::FRINT, MVT::f64, Legal);
939 // We have target-specific dag combine patterns for the following nodes:
940 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
941 setTargetDAGCombine(ISD::ADD);
942 setTargetDAGCombine(ISD::SUB);
943 setTargetDAGCombine(ISD::MUL);
944 setTargetDAGCombine(ISD::AND);
945 setTargetDAGCombine(ISD::OR);
946 setTargetDAGCombine(ISD::XOR);
948 if (Subtarget->hasV6Ops())
949 setTargetDAGCombine(ISD::SRL);
951 setStackPointerRegisterToSaveRestore(ARM::SP);
953 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
954 !Subtarget->hasVFP2())
955 setSchedulingPreference(Sched::RegPressure);
957 setSchedulingPreference(Sched::Hybrid);
959 //// temporary - rewrite interface to use type
960 MaxStoresPerMemset = 8;
961 MaxStoresPerMemsetOptSize = 4;
962 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
963 MaxStoresPerMemcpyOptSize = 2;
964 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
965 MaxStoresPerMemmoveOptSize = 2;
967 // On ARM arguments smaller than 4 bytes are extended, so all arguments
968 // are at least 4 bytes aligned.
969 setMinStackArgumentAlignment(4);
971 // Prefer likely predicted branches to selects on out-of-order cores.
972 PredictableSelectIsExpensive = Subtarget->isLikeA9();
974 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
977 bool ARMTargetLowering::useSoftFloat() const {
978 return Subtarget->useSoftFloat();
981 // FIXME: It might make sense to define the representative register class as the
982 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
983 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
984 // SPR's representative would be DPR_VFP2. This should work well if register
985 // pressure tracking were modified such that a register use would increment the
986 // pressure of the register class's representative and all of it's super
987 // classes' representatives transitively. We have not implemented this because
988 // of the difficulty prior to coalescing of modeling operand register classes
989 // due to the common occurrence of cross class copies and subregister insertions
991 std::pair<const TargetRegisterClass *, uint8_t>
992 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
994 const TargetRegisterClass *RRC = nullptr;
996 switch (VT.SimpleTy) {
998 return TargetLowering::findRepresentativeClass(TRI, VT);
999 // Use DPR as representative register class for all floating point
1000 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1001 // the cost is 1 for both f32 and f64.
1002 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1003 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1004 RRC = &ARM::DPRRegClass;
1005 // When NEON is used for SP, only half of the register file is available
1006 // because operations that define both SP and DP results will be constrained
1007 // to the VFP2 class (D0-D15). We currently model this constraint prior to
1008 // coalescing by double-counting the SP regs. See the FIXME above.
1009 if (Subtarget->useNEONForSinglePrecisionFP())
1012 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1013 case MVT::v4f32: case MVT::v2f64:
1014 RRC = &ARM::DPRRegClass;
1018 RRC = &ARM::DPRRegClass;
1022 RRC = &ARM::DPRRegClass;
1026 return std::make_pair(RRC, Cost);
1029 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1030 switch ((ARMISD::NodeType)Opcode) {
1031 case ARMISD::FIRST_NUMBER: break;
1032 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1033 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1034 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1035 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1036 case ARMISD::CALL: return "ARMISD::CALL";
1037 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1038 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1039 case ARMISD::tCALL: return "ARMISD::tCALL";
1040 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1041 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1042 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1043 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1044 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1045 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1046 case ARMISD::CMP: return "ARMISD::CMP";
1047 case ARMISD::CMN: return "ARMISD::CMN";
1048 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1049 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1050 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1051 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1052 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1054 case ARMISD::CMOV: return "ARMISD::CMOV";
1056 case ARMISD::RBIT: return "ARMISD::RBIT";
1058 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1059 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1060 case ARMISD::RRX: return "ARMISD::RRX";
1062 case ARMISD::ADDC: return "ARMISD::ADDC";
1063 case ARMISD::ADDE: return "ARMISD::ADDE";
1064 case ARMISD::SUBC: return "ARMISD::SUBC";
1065 case ARMISD::SUBE: return "ARMISD::SUBE";
1067 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1068 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1070 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1071 case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1072 case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1074 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1076 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1078 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1080 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1082 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1084 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1086 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1087 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1088 case ARMISD::VCGE: return "ARMISD::VCGE";
1089 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1090 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1091 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1092 case ARMISD::VCGT: return "ARMISD::VCGT";
1093 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1094 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1095 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1096 case ARMISD::VTST: return "ARMISD::VTST";
1098 case ARMISD::VSHL: return "ARMISD::VSHL";
1099 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1100 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1101 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1102 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1103 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1104 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1105 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1106 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1107 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1108 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1109 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1110 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1111 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1112 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1113 case ARMISD::VSLI: return "ARMISD::VSLI";
1114 case ARMISD::VSRI: return "ARMISD::VSRI";
1115 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1116 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1117 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1118 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1119 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1120 case ARMISD::VDUP: return "ARMISD::VDUP";
1121 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1122 case ARMISD::VEXT: return "ARMISD::VEXT";
1123 case ARMISD::VREV64: return "ARMISD::VREV64";
1124 case ARMISD::VREV32: return "ARMISD::VREV32";
1125 case ARMISD::VREV16: return "ARMISD::VREV16";
1126 case ARMISD::VZIP: return "ARMISD::VZIP";
1127 case ARMISD::VUZP: return "ARMISD::VUZP";
1128 case ARMISD::VTRN: return "ARMISD::VTRN";
1129 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1130 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1131 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1132 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1133 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1134 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1135 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1136 case ARMISD::FMAX: return "ARMISD::FMAX";
1137 case ARMISD::FMIN: return "ARMISD::FMIN";
1138 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1139 case ARMISD::VMINNM: return "ARMISD::VMIN";
1140 case ARMISD::BFI: return "ARMISD::BFI";
1141 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1142 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1143 case ARMISD::VBSL: return "ARMISD::VBSL";
1144 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1145 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1146 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1147 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1148 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1149 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1150 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1151 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1152 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1153 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1154 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1155 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1156 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1157 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1158 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1159 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1160 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1161 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1162 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1163 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1168 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1171 return getPointerTy(DL);
1172 return VT.changeVectorElementTypeToInteger();
1175 /// getRegClassFor - Return the register class that should be used for the
1176 /// specified value type.
1177 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1178 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1179 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1180 // load / store 4 to 8 consecutive D registers.
1181 if (Subtarget->hasNEON()) {
1182 if (VT == MVT::v4i64)
1183 return &ARM::QQPRRegClass;
1184 if (VT == MVT::v8i64)
1185 return &ARM::QQQQPRRegClass;
1187 return TargetLowering::getRegClassFor(VT);
1190 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1191 // source/dest is aligned and the copy size is large enough. We therefore want
1192 // to align such objects passed to memory intrinsics.
1193 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1194 unsigned &PrefAlign) const {
1195 if (!isa<MemIntrinsic>(CI))
1198 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1199 // cycle faster than 4-byte aligned LDM.
1200 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1204 // Create a fast isel object.
1206 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1207 const TargetLibraryInfo *libInfo) const {
1208 return ARM::createFastISel(funcInfo, libInfo);
1211 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1212 unsigned NumVals = N->getNumValues();
1214 return Sched::RegPressure;
1216 for (unsigned i = 0; i != NumVals; ++i) {
1217 EVT VT = N->getValueType(i);
1218 if (VT == MVT::Glue || VT == MVT::Other)
1220 if (VT.isFloatingPoint() || VT.isVector())
1224 if (!N->isMachineOpcode())
1225 return Sched::RegPressure;
1227 // Load are scheduled for latency even if there instruction itinerary
1228 // is not available.
1229 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1230 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1232 if (MCID.getNumDefs() == 0)
1233 return Sched::RegPressure;
1234 if (!Itins->isEmpty() &&
1235 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1238 return Sched::RegPressure;
1241 //===----------------------------------------------------------------------===//
1243 //===----------------------------------------------------------------------===//
1245 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1246 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1248 default: llvm_unreachable("Unknown condition code!");
1249 case ISD::SETNE: return ARMCC::NE;
1250 case ISD::SETEQ: return ARMCC::EQ;
1251 case ISD::SETGT: return ARMCC::GT;
1252 case ISD::SETGE: return ARMCC::GE;
1253 case ISD::SETLT: return ARMCC::LT;
1254 case ISD::SETLE: return ARMCC::LE;
1255 case ISD::SETUGT: return ARMCC::HI;
1256 case ISD::SETUGE: return ARMCC::HS;
1257 case ISD::SETULT: return ARMCC::LO;
1258 case ISD::SETULE: return ARMCC::LS;
1262 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1263 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1264 ARMCC::CondCodes &CondCode2) {
1265 CondCode2 = ARMCC::AL;
1267 default: llvm_unreachable("Unknown FP condition!");
1269 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1271 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1273 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1274 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1275 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1276 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1277 case ISD::SETO: CondCode = ARMCC::VC; break;
1278 case ISD::SETUO: CondCode = ARMCC::VS; break;
1279 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1280 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1281 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1283 case ISD::SETULT: CondCode = ARMCC::LT; break;
1285 case ISD::SETULE: CondCode = ARMCC::LE; break;
1287 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1291 //===----------------------------------------------------------------------===//
1292 // Calling Convention Implementation
1293 //===----------------------------------------------------------------------===//
1295 #include "ARMGenCallingConv.inc"
1297 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1298 /// account presence of floating point hardware and calling convention
1299 /// limitations, such as support for variadic functions.
1301 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1302 bool isVarArg) const {
1305 llvm_unreachable("Unsupported calling convention");
1306 case CallingConv::ARM_AAPCS:
1307 case CallingConv::ARM_APCS:
1308 case CallingConv::GHC:
1310 case CallingConv::ARM_AAPCS_VFP:
1311 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1312 case CallingConv::C:
1313 if (!Subtarget->isAAPCS_ABI())
1314 return CallingConv::ARM_APCS;
1315 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1316 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1318 return CallingConv::ARM_AAPCS_VFP;
1320 return CallingConv::ARM_AAPCS;
1321 case CallingConv::Fast:
1322 if (!Subtarget->isAAPCS_ABI()) {
1323 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1324 return CallingConv::Fast;
1325 return CallingConv::ARM_APCS;
1326 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1327 return CallingConv::ARM_AAPCS_VFP;
1329 return CallingConv::ARM_AAPCS;
1333 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1334 /// CallingConvention.
1335 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1337 bool isVarArg) const {
1338 switch (getEffectiveCallingConv(CC, isVarArg)) {
1340 llvm_unreachable("Unsupported calling convention");
1341 case CallingConv::ARM_APCS:
1342 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1343 case CallingConv::ARM_AAPCS:
1344 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1345 case CallingConv::ARM_AAPCS_VFP:
1346 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1347 case CallingConv::Fast:
1348 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1349 case CallingConv::GHC:
1350 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1354 /// LowerCallResult - Lower the result values of a call into the
1355 /// appropriate copies out of appropriate physical registers.
1357 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1358 CallingConv::ID CallConv, bool isVarArg,
1359 const SmallVectorImpl<ISD::InputArg> &Ins,
1360 SDLoc dl, SelectionDAG &DAG,
1361 SmallVectorImpl<SDValue> &InVals,
1362 bool isThisReturn, SDValue ThisVal) const {
1364 // Assign locations to each value returned by this call.
1365 SmallVector<CCValAssign, 16> RVLocs;
1366 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1367 *DAG.getContext(), Call);
1368 CCInfo.AnalyzeCallResult(Ins,
1369 CCAssignFnForNode(CallConv, /* Return*/ true,
1372 // Copy all of the result registers out of their specified physreg.
1373 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1374 CCValAssign VA = RVLocs[i];
1376 // Pass 'this' value directly from the argument to return value, to avoid
1377 // reg unit interference
1378 if (i == 0 && isThisReturn) {
1379 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1380 "unexpected return calling convention register assignment");
1381 InVals.push_back(ThisVal);
1386 if (VA.needsCustom()) {
1387 // Handle f64 or half of a v2f64.
1388 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1390 Chain = Lo.getValue(1);
1391 InFlag = Lo.getValue(2);
1392 VA = RVLocs[++i]; // skip ahead to next loc
1393 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1395 Chain = Hi.getValue(1);
1396 InFlag = Hi.getValue(2);
1397 if (!Subtarget->isLittle())
1399 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1401 if (VA.getLocVT() == MVT::v2f64) {
1402 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1403 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1404 DAG.getConstant(0, dl, MVT::i32));
1406 VA = RVLocs[++i]; // skip ahead to next loc
1407 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1408 Chain = Lo.getValue(1);
1409 InFlag = Lo.getValue(2);
1410 VA = RVLocs[++i]; // skip ahead to next loc
1411 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1412 Chain = Hi.getValue(1);
1413 InFlag = Hi.getValue(2);
1414 if (!Subtarget->isLittle())
1416 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1417 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1418 DAG.getConstant(1, dl, MVT::i32));
1421 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1423 Chain = Val.getValue(1);
1424 InFlag = Val.getValue(2);
1427 switch (VA.getLocInfo()) {
1428 default: llvm_unreachable("Unknown loc info!");
1429 case CCValAssign::Full: break;
1430 case CCValAssign::BCvt:
1431 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1435 InVals.push_back(Val);
1441 /// LowerMemOpCallTo - Store the argument to the stack.
1443 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1444 SDValue StackPtr, SDValue Arg,
1445 SDLoc dl, SelectionDAG &DAG,
1446 const CCValAssign &VA,
1447 ISD::ArgFlagsTy Flags) const {
1448 unsigned LocMemOffset = VA.getLocMemOffset();
1449 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1450 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1452 return DAG.getStore(Chain, dl, Arg, PtrOff,
1453 MachinePointerInfo::getStack(LocMemOffset),
1457 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1458 SDValue Chain, SDValue &Arg,
1459 RegsToPassVector &RegsToPass,
1460 CCValAssign &VA, CCValAssign &NextVA,
1462 SmallVectorImpl<SDValue> &MemOpChains,
1463 ISD::ArgFlagsTy Flags) const {
1465 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1466 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1467 unsigned id = Subtarget->isLittle() ? 0 : 1;
1468 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1470 if (NextVA.isRegLoc())
1471 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1473 assert(NextVA.isMemLoc());
1474 if (!StackPtr.getNode())
1475 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1476 getPointerTy(DAG.getDataLayout()));
1478 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1484 /// LowerCall - Lowering a call into a callseq_start <-
1485 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1488 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1489 SmallVectorImpl<SDValue> &InVals) const {
1490 SelectionDAG &DAG = CLI.DAG;
1492 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1493 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1494 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1495 SDValue Chain = CLI.Chain;
1496 SDValue Callee = CLI.Callee;
1497 bool &isTailCall = CLI.IsTailCall;
1498 CallingConv::ID CallConv = CLI.CallConv;
1499 bool doesNotRet = CLI.DoesNotReturn;
1500 bool isVarArg = CLI.IsVarArg;
1502 MachineFunction &MF = DAG.getMachineFunction();
1503 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1504 bool isThisReturn = false;
1505 bool isSibCall = false;
1506 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1508 // Disable tail calls if they're not supported.
1509 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1513 // Check if it's really possible to do a tail call.
1514 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1515 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1516 Outs, OutVals, Ins, DAG);
1517 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1518 report_fatal_error("failed to perform tail call elimination on a call "
1519 "site marked musttail");
1520 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1521 // detected sibcalls.
1528 // Analyze operands of the call, assigning locations to each operand.
1529 SmallVector<CCValAssign, 16> ArgLocs;
1530 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1531 *DAG.getContext(), Call);
1532 CCInfo.AnalyzeCallOperands(Outs,
1533 CCAssignFnForNode(CallConv, /* Return*/ false,
1536 // Get a count of how many bytes are to be pushed on the stack.
1537 unsigned NumBytes = CCInfo.getNextStackOffset();
1539 // For tail calls, memory operands are available in our caller's stack.
1543 // Adjust the stack pointer for the new arguments...
1544 // These operations are automatically eliminated by the prolog/epilog pass
1546 Chain = DAG.getCALLSEQ_START(Chain,
1547 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1550 DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1552 RegsToPassVector RegsToPass;
1553 SmallVector<SDValue, 8> MemOpChains;
1555 // Walk the register/memloc assignments, inserting copies/loads. In the case
1556 // of tail call optimization, arguments are handled later.
1557 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1559 ++i, ++realArgIdx) {
1560 CCValAssign &VA = ArgLocs[i];
1561 SDValue Arg = OutVals[realArgIdx];
1562 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1563 bool isByVal = Flags.isByVal();
1565 // Promote the value if needed.
1566 switch (VA.getLocInfo()) {
1567 default: llvm_unreachable("Unknown loc info!");
1568 case CCValAssign::Full: break;
1569 case CCValAssign::SExt:
1570 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1572 case CCValAssign::ZExt:
1573 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1575 case CCValAssign::AExt:
1576 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1578 case CCValAssign::BCvt:
1579 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1583 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1584 if (VA.needsCustom()) {
1585 if (VA.getLocVT() == MVT::v2f64) {
1586 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1587 DAG.getConstant(0, dl, MVT::i32));
1588 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1589 DAG.getConstant(1, dl, MVT::i32));
1591 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1592 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1594 VA = ArgLocs[++i]; // skip ahead to next loc
1595 if (VA.isRegLoc()) {
1596 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1597 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1599 assert(VA.isMemLoc());
1601 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1602 dl, DAG, VA, Flags));
1605 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1606 StackPtr, MemOpChains, Flags);
1608 } else if (VA.isRegLoc()) {
1609 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1610 assert(VA.getLocVT() == MVT::i32 &&
1611 "unexpected calling convention register assignment");
1612 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1613 "unexpected use of 'returned'");
1614 isThisReturn = true;
1616 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1617 } else if (isByVal) {
1618 assert(VA.isMemLoc());
1619 unsigned offset = 0;
1621 // True if this byval aggregate will be split between registers
1623 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1624 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1626 if (CurByValIdx < ByValArgsCount) {
1628 unsigned RegBegin, RegEnd;
1629 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1632 DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1634 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1635 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1636 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1637 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1638 MachinePointerInfo(),
1639 false, false, false,
1640 DAG.InferPtrAlignment(AddArg));
1641 MemOpChains.push_back(Load.getValue(1));
1642 RegsToPass.push_back(std::make_pair(j, Load));
1645 // If parameter size outsides register area, "offset" value
1646 // helps us to calculate stack slot for remained part properly.
1647 offset = RegEnd - RegBegin;
1649 CCInfo.nextInRegsParam();
1652 if (Flags.getByValSize() > 4*offset) {
1653 auto PtrVT = getPointerTy(DAG.getDataLayout());
1654 unsigned LocMemOffset = VA.getLocMemOffset();
1655 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1656 SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1657 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1658 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1659 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1661 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1664 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1665 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1666 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1669 } else if (!isSibCall) {
1670 assert(VA.isMemLoc());
1672 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1673 dl, DAG, VA, Flags));
1677 if (!MemOpChains.empty())
1678 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1680 // Build a sequence of copy-to-reg nodes chained together with token chain
1681 // and flag operands which copy the outgoing args into the appropriate regs.
1683 // Tail call byval lowering might overwrite argument registers so in case of
1684 // tail call optimization the copies to registers are lowered later.
1686 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1687 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1688 RegsToPass[i].second, InFlag);
1689 InFlag = Chain.getValue(1);
1692 // For tail calls lower the arguments to the 'real' stack slot.
1694 // Force all the incoming stack arguments to be loaded from the stack
1695 // before any new outgoing arguments are stored to the stack, because the
1696 // outgoing stack slots may alias the incoming argument stack slots, and
1697 // the alias isn't otherwise explicit. This is slightly more conservative
1698 // than necessary, because it means that each store effectively depends
1699 // on every argument instead of just those arguments it would clobber.
1701 // Do not flag preceding copytoreg stuff together with the following stuff.
1703 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1704 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1705 RegsToPass[i].second, InFlag);
1706 InFlag = Chain.getValue(1);
1711 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1712 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1713 // node so that legalize doesn't hack it.
1714 bool isDirect = false;
1715 bool isARMFunc = false;
1716 bool isLocalARMFunc = false;
1717 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1718 auto PtrVt = getPointerTy(DAG.getDataLayout());
1720 if (Subtarget->genLongCalls()) {
1721 assert((Subtarget->isTargetWindows() ||
1722 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1723 "long-calls with non-static relocation model!");
1724 // Handle a global address or an external symbol. If it's not one of
1725 // those, the target's already in a register, so we don't need to do
1727 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1728 const GlobalValue *GV = G->getGlobal();
1729 // Create a constant pool entry for the callee address
1730 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1731 ARMConstantPoolValue *CPV =
1732 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1734 // Get the address of the callee into a register
1735 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1736 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1737 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1738 MachinePointerInfo::getConstantPool(), false, false,
1740 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1741 const char *Sym = S->getSymbol();
1743 // Create a constant pool entry for the callee address
1744 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1745 ARMConstantPoolValue *CPV =
1746 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1747 ARMPCLabelIndex, 0);
1748 // Get the address of the callee into a register
1749 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1750 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1751 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1752 MachinePointerInfo::getConstantPool(), false, false,
1755 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1756 const GlobalValue *GV = G->getGlobal();
1758 bool isDef = GV->isStrongDefinitionForLinker();
1759 bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1760 getTargetMachine().getRelocationModel() != Reloc::Static;
1761 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1762 // ARM call to a local ARM function is predicable.
1763 isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1764 // tBX takes a register source operand.
1765 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1766 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1767 Callee = DAG.getNode(
1768 ARMISD::WrapperPIC, dl, PtrVt,
1769 DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1770 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1771 MachinePointerInfo::getGOT(), false, false, true, 0);
1772 } else if (Subtarget->isTargetCOFF()) {
1773 assert(Subtarget->isTargetWindows() &&
1774 "Windows is the only supported COFF target");
1775 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1776 ? ARMII::MO_DLLIMPORT
1777 : ARMII::MO_NO_FLAG;
1779 DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1780 if (GV->hasDLLImportStorageClass())
1782 DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1783 DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1784 MachinePointerInfo::getGOT(), false, false, false, 0);
1786 // On ELF targets for PIC code, direct calls should go through the PLT
1787 unsigned OpFlags = 0;
1788 if (Subtarget->isTargetELF() &&
1789 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1790 OpFlags = ARMII::MO_PLT;
1791 Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1793 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1795 bool isStub = Subtarget->isTargetMachO() &&
1796 getTargetMachine().getRelocationModel() != Reloc::Static;
1797 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1798 // tBX takes a register source operand.
1799 const char *Sym = S->getSymbol();
1800 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1801 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1802 ARMConstantPoolValue *CPV =
1803 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1804 ARMPCLabelIndex, 4);
1805 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1806 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1807 Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1808 MachinePointerInfo::getConstantPool(), false, false,
1810 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1811 Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1813 unsigned OpFlags = 0;
1814 // On ELF targets for PIC code, direct calls should go through the PLT
1815 if (Subtarget->isTargetELF() &&
1816 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1817 OpFlags = ARMII::MO_PLT;
1818 Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1822 // FIXME: handle tail calls differently.
1824 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1825 if (Subtarget->isThumb()) {
1826 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1827 CallOpc = ARMISD::CALL_NOLINK;
1829 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1831 if (!isDirect && !Subtarget->hasV5TOps())
1832 CallOpc = ARMISD::CALL_NOLINK;
1833 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1834 // Emit regular call when code size is the priority
1836 // "mov lr, pc; b _foo" to avoid confusing the RSP
1837 CallOpc = ARMISD::CALL_NOLINK;
1839 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1842 std::vector<SDValue> Ops;
1843 Ops.push_back(Chain);
1844 Ops.push_back(Callee);
1846 // Add argument registers to the end of the list so that they are known live
1848 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1849 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1850 RegsToPass[i].second.getValueType()));
1852 // Add a register mask operand representing the call-preserved registers.
1854 const uint32_t *Mask;
1855 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1857 // For 'this' returns, use the R0-preserving mask if applicable
1858 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1860 // Set isThisReturn to false if the calling convention is not one that
1861 // allows 'returned' to be modeled in this way, so LowerCallResult does
1862 // not try to pass 'this' straight through
1863 isThisReturn = false;
1864 Mask = ARI->getCallPreservedMask(MF, CallConv);
1867 Mask = ARI->getCallPreservedMask(MF, CallConv);
1869 assert(Mask && "Missing call preserved mask for calling convention");
1870 Ops.push_back(DAG.getRegisterMask(Mask));
1873 if (InFlag.getNode())
1874 Ops.push_back(InFlag);
1876 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1878 MF.getFrameInfo()->setHasTailCall();
1879 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1882 // Returns a chain and a flag for retval copy to use.
1883 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1884 InFlag = Chain.getValue(1);
1886 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1887 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1889 InFlag = Chain.getValue(1);
1891 // Handle result values, copying them out of physregs into vregs that we
1893 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1894 InVals, isThisReturn,
1895 isThisReturn ? OutVals[0] : SDValue());
1898 /// HandleByVal - Every parameter *after* a byval parameter is passed
1899 /// on the stack. Remember the next parameter register to allocate,
1900 /// and then confiscate the rest of the parameter registers to insure
1902 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1903 unsigned Align) const {
1904 assert((State->getCallOrPrologue() == Prologue ||
1905 State->getCallOrPrologue() == Call) &&
1906 "unhandled ParmContext");
1908 // Byval (as with any stack) slots are always at least 4 byte aligned.
1909 Align = std::max(Align, 4U);
1911 unsigned Reg = State->AllocateReg(GPRArgRegs);
1915 unsigned AlignInRegs = Align / 4;
1916 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1917 for (unsigned i = 0; i < Waste; ++i)
1918 Reg = State->AllocateReg(GPRArgRegs);
1923 unsigned Excess = 4 * (ARM::R4 - Reg);
1925 // Special case when NSAA != SP and parameter size greater than size of
1926 // all remained GPR regs. In that case we can't split parameter, we must
1927 // send it to stack. We also must set NCRN to R4, so waste all
1928 // remained registers.
1929 const unsigned NSAAOffset = State->getNextStackOffset();
1930 if (NSAAOffset != 0 && Size > Excess) {
1931 while (State->AllocateReg(GPRArgRegs))
1936 // First register for byval parameter is the first register that wasn't
1937 // allocated before this method call, so it would be "reg".
1938 // If parameter is small enough to be saved in range [reg, r4), then
1939 // the end (first after last) register would be reg + param-size-in-regs,
1940 // else parameter would be splitted between registers and stack,
1941 // end register would be r4 in this case.
1942 unsigned ByValRegBegin = Reg;
1943 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1944 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1945 // Note, first register is allocated in the beginning of function already,
1946 // allocate remained amount of registers we need.
1947 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1948 State->AllocateReg(GPRArgRegs);
1949 // A byval parameter that is split between registers and memory needs its
1950 // size truncated here.
1951 // In the case where the entire structure fits in registers, we set the
1952 // size in memory to zero.
1953 Size = std::max<int>(Size - Excess, 0);
1956 /// MatchingStackOffset - Return true if the given stack call argument is
1957 /// already available in the same position (relatively) of the caller's
1958 /// incoming argument stack.
1960 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1961 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1962 const TargetInstrInfo *TII) {
1963 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1965 if (Arg.getOpcode() == ISD::CopyFromReg) {
1966 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1967 if (!TargetRegisterInfo::isVirtualRegister(VR))
1969 MachineInstr *Def = MRI->getVRegDef(VR);
1972 if (!Flags.isByVal()) {
1973 if (!TII->isLoadFromStackSlot(Def, FI))
1978 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1979 if (Flags.isByVal())
1980 // ByVal argument is passed in as a pointer but it's now being
1981 // dereferenced. e.g.
1982 // define @foo(%struct.X* %A) {
1983 // tail call @bar(%struct.X* byval %A)
1986 SDValue Ptr = Ld->getBasePtr();
1987 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1990 FI = FINode->getIndex();
1994 assert(FI != INT_MAX);
1995 if (!MFI->isFixedObjectIndex(FI))
1997 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2000 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2001 /// for tail call optimization. Targets which want to do tail call
2002 /// optimization should implement this function.
2004 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2005 CallingConv::ID CalleeCC,
2007 bool isCalleeStructRet,
2008 bool isCallerStructRet,
2009 const SmallVectorImpl<ISD::OutputArg> &Outs,
2010 const SmallVectorImpl<SDValue> &OutVals,
2011 const SmallVectorImpl<ISD::InputArg> &Ins,
2012 SelectionDAG& DAG) const {
2013 const Function *CallerF = DAG.getMachineFunction().getFunction();
2014 CallingConv::ID CallerCC = CallerF->getCallingConv();
2015 bool CCMatch = CallerCC == CalleeCC;
2017 // Look for obvious safe cases to perform tail call optimization that do not
2018 // require ABI changes. This is what gcc calls sibcall.
2020 // Do not sibcall optimize vararg calls unless the call site is not passing
2022 if (isVarArg && !Outs.empty())
2025 // Exception-handling functions need a special set of instructions to indicate
2026 // a return to the hardware. Tail-calling another function would probably
2028 if (CallerF->hasFnAttribute("interrupt"))
2031 // Also avoid sibcall optimization if either caller or callee uses struct
2032 // return semantics.
2033 if (isCalleeStructRet || isCallerStructRet)
2036 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2037 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2038 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2039 // support in the assembler and linker to be used. This would need to be
2040 // fixed to fully support tail calls in Thumb1.
2042 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2043 // LR. This means if we need to reload LR, it takes an extra instructions,
2044 // which outweighs the value of the tail call; but here we don't know yet
2045 // whether LR is going to be used. Probably the right approach is to
2046 // generate the tail call here and turn it back into CALL/RET in
2047 // emitEpilogue if LR is used.
2049 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2050 // but we need to make sure there are enough registers; the only valid
2051 // registers are the 4 used for parameters. We don't currently do this
2053 if (Subtarget->isThumb1Only())
2056 // Externally-defined functions with weak linkage should not be
2057 // tail-called on ARM when the OS does not support dynamic
2058 // pre-emption of symbols, as the AAELF spec requires normal calls
2059 // to undefined weak functions to be replaced with a NOP or jump to the
2060 // next instruction. The behaviour of branch instructions in this
2061 // situation (as used for tail calls) is implementation-defined, so we
2062 // cannot rely on the linker replacing the tail call with a return.
2063 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2064 const GlobalValue *GV = G->getGlobal();
2065 const Triple &TT = getTargetMachine().getTargetTriple();
2066 if (GV->hasExternalWeakLinkage() &&
2067 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2071 // If the calling conventions do not match, then we'd better make sure the
2072 // results are returned in the same way as what the caller expects.
2074 SmallVector<CCValAssign, 16> RVLocs1;
2075 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2076 *DAG.getContext(), Call);
2077 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2079 SmallVector<CCValAssign, 16> RVLocs2;
2080 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2081 *DAG.getContext(), Call);
2082 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2084 if (RVLocs1.size() != RVLocs2.size())
2086 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2087 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2089 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2091 if (RVLocs1[i].isRegLoc()) {
2092 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2095 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2101 // If Caller's vararg or byval argument has been split between registers and
2102 // stack, do not perform tail call, since part of the argument is in caller's
2104 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2105 getInfo<ARMFunctionInfo>();
2106 if (AFI_Caller->getArgRegsSaveSize())
2109 // If the callee takes no arguments then go on to check the results of the
2111 if (!Outs.empty()) {
2112 // Check if stack adjustment is needed. For now, do not do this if any
2113 // argument is passed on the stack.
2114 SmallVector<CCValAssign, 16> ArgLocs;
2115 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2116 *DAG.getContext(), Call);
2117 CCInfo.AnalyzeCallOperands(Outs,
2118 CCAssignFnForNode(CalleeCC, false, isVarArg));
2119 if (CCInfo.getNextStackOffset()) {
2120 MachineFunction &MF = DAG.getMachineFunction();
2122 // Check if the arguments are already laid out in the right way as
2123 // the caller's fixed stack objects.
2124 MachineFrameInfo *MFI = MF.getFrameInfo();
2125 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2126 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2127 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2129 ++i, ++realArgIdx) {
2130 CCValAssign &VA = ArgLocs[i];
2131 EVT RegVT = VA.getLocVT();
2132 SDValue Arg = OutVals[realArgIdx];
2133 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2134 if (VA.getLocInfo() == CCValAssign::Indirect)
2136 if (VA.needsCustom()) {
2137 // f64 and vector types are split into multiple registers or
2138 // register/stack-slot combinations. The types will not match
2139 // the registers; give up on memory f64 refs until we figure
2140 // out what to do about this.
2143 if (!ArgLocs[++i].isRegLoc())
2145 if (RegVT == MVT::v2f64) {
2146 if (!ArgLocs[++i].isRegLoc())
2148 if (!ArgLocs[++i].isRegLoc())
2151 } else if (!VA.isRegLoc()) {
2152 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2164 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2165 MachineFunction &MF, bool isVarArg,
2166 const SmallVectorImpl<ISD::OutputArg> &Outs,
2167 LLVMContext &Context) const {
2168 SmallVector<CCValAssign, 16> RVLocs;
2169 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2170 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2174 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2175 SDLoc DL, SelectionDAG &DAG) {
2176 const MachineFunction &MF = DAG.getMachineFunction();
2177 const Function *F = MF.getFunction();
2179 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2181 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2182 // version of the "preferred return address". These offsets affect the return
2183 // instruction if this is a return from PL1 without hypervisor extensions.
2184 // IRQ/FIQ: +4 "subs pc, lr, #4"
2185 // SWI: 0 "subs pc, lr, #0"
2186 // ABORT: +4 "subs pc, lr, #4"
2187 // UNDEF: +4/+2 "subs pc, lr, #0"
2188 // UNDEF varies depending on where the exception came from ARM or Thumb
2189 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2192 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2195 else if (IntKind == "SWI" || IntKind == "UNDEF")
2198 report_fatal_error("Unsupported interrupt attribute. If present, value "
2199 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2201 RetOps.insert(RetOps.begin() + 1,
2202 DAG.getConstant(LROffset, DL, MVT::i32, false));
2204 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2208 ARMTargetLowering::LowerReturn(SDValue Chain,
2209 CallingConv::ID CallConv, bool isVarArg,
2210 const SmallVectorImpl<ISD::OutputArg> &Outs,
2211 const SmallVectorImpl<SDValue> &OutVals,
2212 SDLoc dl, SelectionDAG &DAG) const {
2214 // CCValAssign - represent the assignment of the return value to a location.
2215 SmallVector<CCValAssign, 16> RVLocs;
2217 // CCState - Info about the registers and stack slots.
2218 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2219 *DAG.getContext(), Call);
2221 // Analyze outgoing return values.
2222 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2226 SmallVector<SDValue, 4> RetOps;
2227 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2228 bool isLittleEndian = Subtarget->isLittle();
2230 MachineFunction &MF = DAG.getMachineFunction();
2231 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2232 AFI->setReturnRegsCount(RVLocs.size());
2234 // Copy the result values into the output registers.
2235 for (unsigned i = 0, realRVLocIdx = 0;
2237 ++i, ++realRVLocIdx) {
2238 CCValAssign &VA = RVLocs[i];
2239 assert(VA.isRegLoc() && "Can only return in registers!");
2241 SDValue Arg = OutVals[realRVLocIdx];
2243 switch (VA.getLocInfo()) {
2244 default: llvm_unreachable("Unknown loc info!");
2245 case CCValAssign::Full: break;
2246 case CCValAssign::BCvt:
2247 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2251 if (VA.needsCustom()) {
2252 if (VA.getLocVT() == MVT::v2f64) {
2253 // Extract the first half and return it in two registers.
2254 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2255 DAG.getConstant(0, dl, MVT::i32));
2256 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2257 DAG.getVTList(MVT::i32, MVT::i32), Half);
2259 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2260 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2262 Flag = Chain.getValue(1);
2263 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264 VA = RVLocs[++i]; // skip ahead to next loc
2265 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2266 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2268 Flag = Chain.getValue(1);
2269 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2270 VA = RVLocs[++i]; // skip ahead to next loc
2272 // Extract the 2nd half and fall through to handle it as an f64 value.
2273 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2274 DAG.getConstant(1, dl, MVT::i32));
2276 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2278 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2279 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2280 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2281 fmrrd.getValue(isLittleEndian ? 0 : 1),
2283 Flag = Chain.getValue(1);
2284 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2285 VA = RVLocs[++i]; // skip ahead to next loc
2286 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2287 fmrrd.getValue(isLittleEndian ? 1 : 0),
2290 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2292 // Guarantee that all emitted copies are
2293 // stuck together, avoiding something bad.
2294 Flag = Chain.getValue(1);
2295 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2298 // Update chain and glue.
2301 RetOps.push_back(Flag);
2303 // CPUs which aren't M-class use a special sequence to return from
2304 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2305 // though we use "subs pc, lr, #N").
2307 // M-class CPUs actually use a normal return sequence with a special
2308 // (hardware-provided) value in LR, so the normal code path works.
2309 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2310 !Subtarget->isMClass()) {
2311 if (Subtarget->isThumb1Only())
2312 report_fatal_error("interrupt attribute is not supported in Thumb1");
2313 return LowerInterruptReturn(RetOps, dl, DAG);
2316 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2319 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2320 if (N->getNumValues() != 1)
2322 if (!N->hasNUsesOfValue(1, 0))
2325 SDValue TCChain = Chain;
2326 SDNode *Copy = *N->use_begin();
2327 if (Copy->getOpcode() == ISD::CopyToReg) {
2328 // If the copy has a glue operand, we conservatively assume it isn't safe to
2329 // perform a tail call.
2330 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2332 TCChain = Copy->getOperand(0);
2333 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2334 SDNode *VMov = Copy;
2335 // f64 returned in a pair of GPRs.
2336 SmallPtrSet<SDNode*, 2> Copies;
2337 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2339 if (UI->getOpcode() != ISD::CopyToReg)
2343 if (Copies.size() > 2)
2346 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2348 SDValue UseChain = UI->getOperand(0);
2349 if (Copies.count(UseChain.getNode()))
2353 // We are at the top of this chain.
2354 // If the copy has a glue operand, we conservatively assume it
2355 // isn't safe to perform a tail call.
2356 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2362 } else if (Copy->getOpcode() == ISD::BITCAST) {
2363 // f32 returned in a single GPR.
2364 if (!Copy->hasOneUse())
2366 Copy = *Copy->use_begin();
2367 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2369 // If the copy has a glue operand, we conservatively assume it isn't safe to
2370 // perform a tail call.
2371 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2373 TCChain = Copy->getOperand(0);
2378 bool HasRet = false;
2379 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2381 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2382 UI->getOpcode() != ARMISD::INTRET_FLAG)
2394 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2395 if (!Subtarget->supportsTailCall())
2399 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2400 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2403 return !Subtarget->isThumb1Only();
2406 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2407 // and pass the lower and high parts through.
2408 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2410 SDValue WriteValue = Op->getOperand(2);
2412 // This function is only supposed to be called for i64 type argument.
2413 assert(WriteValue.getValueType() == MVT::i64
2414 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2416 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2417 DAG.getConstant(0, DL, MVT::i32));
2418 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2419 DAG.getConstant(1, DL, MVT::i32));
2420 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2421 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2424 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2425 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2426 // one of the above mentioned nodes. It has to be wrapped because otherwise
2427 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2428 // be used to form addressing mode. These wrapped nodes will be selected
2430 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2431 EVT PtrVT = Op.getValueType();
2432 // FIXME there is no actual debug info here
2434 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2436 if (CP->isMachineConstantPoolEntry())
2437 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2438 CP->getAlignment());
2440 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2441 CP->getAlignment());
2442 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2445 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2446 return MachineJumpTableInfo::EK_Inline;
2449 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2450 SelectionDAG &DAG) const {
2451 MachineFunction &MF = DAG.getMachineFunction();
2452 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2453 unsigned ARMPCLabelIndex = 0;
2455 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2456 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2457 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2459 if (RelocM == Reloc::Static) {
2460 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2462 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2463 ARMPCLabelIndex = AFI->createPICLabelUId();
2464 ARMConstantPoolValue *CPV =
2465 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2466 ARMCP::CPBlockAddress, PCAdj);
2467 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2469 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2470 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2471 MachinePointerInfo::getConstantPool(),
2472 false, false, false, 0);
2473 if (RelocM == Reloc::Static)
2475 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2476 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2479 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2481 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2482 SelectionDAG &DAG) const {
2484 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2485 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486 MachineFunction &MF = DAG.getMachineFunction();
2487 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2488 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2489 ARMConstantPoolValue *CPV =
2490 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2491 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2492 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2494 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2495 MachinePointerInfo::getConstantPool(),
2496 false, false, false, 0);
2497 SDValue Chain = Argument.getValue(1);
2499 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2500 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2502 // call __tls_get_addr.
2505 Entry.Node = Argument;
2506 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2507 Args.push_back(Entry);
2509 // FIXME: is there useful debug info available here?
2510 TargetLowering::CallLoweringInfo CLI(DAG);
2511 CLI.setDebugLoc(dl).setChain(Chain)
2512 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2513 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2516 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2517 return CallResult.first;
2520 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2521 // "local exec" model.
2523 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2525 TLSModel::Model model) const {
2526 const GlobalValue *GV = GA->getGlobal();
2529 SDValue Chain = DAG.getEntryNode();
2530 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2531 // Get the Thread Pointer
2532 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2534 if (model == TLSModel::InitialExec) {
2535 MachineFunction &MF = DAG.getMachineFunction();
2536 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2537 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2538 // Initial exec model.
2539 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2540 ARMConstantPoolValue *CPV =
2541 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2542 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2544 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2545 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2546 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2547 MachinePointerInfo::getConstantPool(),
2548 false, false, false, 0);
2549 Chain = Offset.getValue(1);
2551 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2552 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2554 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2555 MachinePointerInfo::getConstantPool(),
2556 false, false, false, 0);
2559 assert(model == TLSModel::LocalExec);
2560 ARMConstantPoolValue *CPV =
2561 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2562 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2563 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2564 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2565 MachinePointerInfo::getConstantPool(),
2566 false, false, false, 0);
2569 // The address of the thread local variable is the add of the thread
2570 // pointer with the offset of the variable.
2571 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2575 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2576 // TODO: implement the "local dynamic" model
2577 assert(Subtarget->isTargetELF() &&
2578 "TLS not implemented for non-ELF targets");
2579 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2580 if (DAG.getTarget().Options.EmulatedTLS)
2581 return LowerToTLSEmulatedModel(GA, DAG);
2583 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2586 case TLSModel::GeneralDynamic:
2587 case TLSModel::LocalDynamic:
2588 return LowerToTLSGeneralDynamicModel(GA, DAG);
2589 case TLSModel::InitialExec:
2590 case TLSModel::LocalExec:
2591 return LowerToTLSExecModels(GA, DAG, model);
2593 llvm_unreachable("bogus TLS model");
2596 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2597 SelectionDAG &DAG) const {
2598 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2600 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2601 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2602 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2603 ARMConstantPoolValue *CPV =
2604 ARMConstantPoolConstant::Create(GV,
2605 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2606 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2607 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2608 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2610 MachinePointerInfo::getConstantPool(),
2611 false, false, false, 0);
2612 SDValue Chain = Result.getValue(1);
2613 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2614 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2616 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2617 MachinePointerInfo::getGOT(),
2618 false, false, false, 0);
2622 // If we have T2 ops, we can materialize the address directly via movt/movw
2623 // pair. This is always cheaper.
2624 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2626 // FIXME: Once remat is capable of dealing with instructions with register
2627 // operands, expand this into two nodes.
2628 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2629 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2631 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2632 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2633 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2634 MachinePointerInfo::getConstantPool(),
2635 false, false, false, 0);
2639 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2640 SelectionDAG &DAG) const {
2641 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2643 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2644 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2646 if (Subtarget->useMovt(DAG.getMachineFunction()))
2649 // FIXME: Once remat is capable of dealing with instructions with register
2650 // operands, expand this into multiple nodes
2652 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2654 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2655 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2657 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2658 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2659 MachinePointerInfo::getGOT(), false, false, false, 0);
2663 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2664 SelectionDAG &DAG) const {
2665 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2666 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2667 "Windows on ARM expects to use movw/movt");
2669 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2670 const ARMII::TOF TargetFlags =
2671 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2672 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2678 // FIXME: Once remat is capable of dealing with instructions with register
2679 // operands, expand this into two nodes.
2680 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2681 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2683 if (GV->hasDLLImportStorageClass())
2684 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2685 MachinePointerInfo::getGOT(), false, false, false, 0);
2689 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2690 SelectionDAG &DAG) const {
2691 assert(Subtarget->isTargetELF() &&
2692 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2693 MachineFunction &MF = DAG.getMachineFunction();
2694 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2695 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2696 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2698 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2699 ARMConstantPoolValue *CPV =
2700 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2701 ARMPCLabelIndex, PCAdj);
2702 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2703 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2704 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2705 MachinePointerInfo::getConstantPool(),
2706 false, false, false, 0);
2707 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2708 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2712 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2714 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2715 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2716 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2717 Op.getOperand(1), Val);
2721 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2723 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2724 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2727 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2728 SelectionDAG &DAG) const {
2730 return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2735 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2736 const ARMSubtarget *Subtarget) const {
2737 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2740 default: return SDValue(); // Don't custom lower most intrinsics.
2741 case Intrinsic::arm_rbit: {
2742 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2743 "RBIT intrinsic must have i32 type!");
2744 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2746 case Intrinsic::arm_thread_pointer: {
2747 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2748 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2750 case Intrinsic::eh_sjlj_lsda: {
2751 MachineFunction &MF = DAG.getMachineFunction();
2752 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2753 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2754 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2755 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2757 unsigned PCAdj = (RelocM != Reloc::PIC_)
2758 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2759 ARMConstantPoolValue *CPV =
2760 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2761 ARMCP::CPLSDA, PCAdj);
2762 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2763 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2765 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2766 MachinePointerInfo::getConstantPool(),
2767 false, false, false, 0);
2769 if (RelocM == Reloc::PIC_) {
2770 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2771 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2775 case Intrinsic::arm_neon_vmulls:
2776 case Intrinsic::arm_neon_vmullu: {
2777 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2778 ? ARMISD::VMULLs : ARMISD::VMULLu;
2779 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2780 Op.getOperand(1), Op.getOperand(2));
2785 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2786 const ARMSubtarget *Subtarget) {
2787 // FIXME: handle "fence singlethread" more efficiently.
2789 if (!Subtarget->hasDataBarrier()) {
2790 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2791 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2793 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2794 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2795 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2796 DAG.getConstant(0, dl, MVT::i32));
2799 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2800 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2801 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2802 if (Subtarget->isMClass()) {
2803 // Only a full system barrier exists in the M-class architectures.
2804 Domain = ARM_MB::SY;
2805 } else if (Subtarget->isSwift() && Ord == Release) {
2806 // Swift happens to implement ISHST barriers in a way that's compatible with
2807 // Release semantics but weaker than ISH so we'd be fools not to use
2808 // it. Beware: other processors probably don't!
2809 Domain = ARM_MB::ISHST;
2812 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2813 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2814 DAG.getConstant(Domain, dl, MVT::i32));
2817 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2818 const ARMSubtarget *Subtarget) {
2819 // ARM pre v5TE and Thumb1 does not have preload instructions.
2820 if (!(Subtarget->isThumb2() ||
2821 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2822 // Just preserve the chain.
2823 return Op.getOperand(0);
2826 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2828 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2829 // ARMv7 with MP extension has PLDW.
2830 return Op.getOperand(0);
2832 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2833 if (Subtarget->isThumb()) {
2835 isRead = ~isRead & 1;
2836 isData = ~isData & 1;
2839 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2840 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2841 DAG.getConstant(isData, dl, MVT::i32));
2844 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2845 MachineFunction &MF = DAG.getMachineFunction();
2846 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2848 // vastart just stores the address of the VarArgsFrameIndex slot into the
2849 // memory location argument.
2851 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2852 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2853 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2854 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2855 MachinePointerInfo(SV), false, false, 0);
2859 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2860 SDValue &Root, SelectionDAG &DAG,
2862 MachineFunction &MF = DAG.getMachineFunction();
2863 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2865 const TargetRegisterClass *RC;
2866 if (AFI->isThumb1OnlyFunction())
2867 RC = &ARM::tGPRRegClass;
2869 RC = &ARM::GPRRegClass;
2871 // Transform the arguments stored in physical registers into virtual ones.
2872 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2873 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2876 if (NextVA.isMemLoc()) {
2877 MachineFrameInfo *MFI = MF.getFrameInfo();
2878 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2880 // Create load node to retrieve arguments from the stack.
2881 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2882 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2883 MachinePointerInfo::getFixedStack(FI),
2884 false, false, false, 0);
2886 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2887 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2889 if (!Subtarget->isLittle())
2890 std::swap (ArgValue, ArgValue2);
2891 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2894 // The remaining GPRs hold either the beginning of variable-argument
2895 // data, or the beginning of an aggregate passed by value (usually
2896 // byval). Either way, we allocate stack slots adjacent to the data
2897 // provided by our caller, and store the unallocated registers there.
2898 // If this is a variadic function, the va_list pointer will begin with
2899 // these values; otherwise, this reassembles a (byval) structure that
2900 // was split between registers and memory.
2901 // Return: The frame index registers were stored into.
2903 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2904 SDLoc dl, SDValue &Chain,
2905 const Value *OrigArg,
2906 unsigned InRegsParamRecordIdx,
2908 unsigned ArgSize) const {
2909 // Currently, two use-cases possible:
2910 // Case #1. Non-var-args function, and we meet first byval parameter.
2911 // Setup first unallocated register as first byval register;
2912 // eat all remained registers
2913 // (these two actions are performed by HandleByVal method).
2914 // Then, here, we initialize stack frame with
2915 // "store-reg" instructions.
2916 // Case #2. Var-args function, that doesn't contain byval parameters.
2917 // The same: eat all remained unallocated registers,
2918 // initialize stack frame.
2920 MachineFunction &MF = DAG.getMachineFunction();
2921 MachineFrameInfo *MFI = MF.getFrameInfo();
2922 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2923 unsigned RBegin, REnd;
2924 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2925 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2927 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2928 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2933 ArgOffset = -4 * (ARM::R4 - RBegin);
2935 auto PtrVT = getPointerTy(DAG.getDataLayout());
2936 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2937 SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2939 SmallVector<SDValue, 4> MemOps;
2940 const TargetRegisterClass *RC =
2941 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2943 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2944 unsigned VReg = MF.addLiveIn(Reg, RC);
2945 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2947 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2948 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2949 MemOps.push_back(Store);
2950 FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2953 if (!MemOps.empty())
2954 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2958 // Setup stack frame, the va_list pointer will start from.
2960 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2961 SDLoc dl, SDValue &Chain,
2963 unsigned TotalArgRegsSaveSize,
2964 bool ForceMutable) const {
2965 MachineFunction &MF = DAG.getMachineFunction();
2966 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2968 // Try to store any remaining integer argument regs
2969 // to their spots on the stack so that they may be loaded by deferencing
2970 // the result of va_next.
2971 // If there is no regs to be stored, just point address after last
2972 // argument passed via stack.
2973 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2974 CCInfo.getInRegsParamsCount(),
2975 CCInfo.getNextStackOffset(), 4);
2976 AFI->setVarArgsFrameIndex(FrameIndex);
2980 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2981 CallingConv::ID CallConv, bool isVarArg,
2982 const SmallVectorImpl<ISD::InputArg>
2984 SDLoc dl, SelectionDAG &DAG,
2985 SmallVectorImpl<SDValue> &InVals)
2987 MachineFunction &MF = DAG.getMachineFunction();
2988 MachineFrameInfo *MFI = MF.getFrameInfo();
2990 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2992 // Assign locations to all of the incoming arguments.
2993 SmallVector<CCValAssign, 16> ArgLocs;
2994 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2995 *DAG.getContext(), Prologue);
2996 CCInfo.AnalyzeFormalArguments(Ins,
2997 CCAssignFnForNode(CallConv, /* Return*/ false,
3000 SmallVector<SDValue, 16> ArgValues;
3002 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3003 unsigned CurArgIdx = 0;
3005 // Initially ArgRegsSaveSize is zero.
3006 // Then we increase this value each time we meet byval parameter.
3007 // We also increase this value in case of varargs function.
3008 AFI->setArgRegsSaveSize(0);
3010 // Calculate the amount of stack space that we need to allocate to store
3011 // byval and variadic arguments that are passed in registers.
3012 // We need to know this before we allocate the first byval or variadic
3013 // argument, as they will be allocated a stack slot below the CFA (Canonical
3014 // Frame Address, the stack pointer at entry to the function).
3015 unsigned ArgRegBegin = ARM::R4;
3016 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3017 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3020 CCValAssign &VA = ArgLocs[i];
3021 unsigned Index = VA.getValNo();
3022 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3023 if (!Flags.isByVal())
3026 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3027 unsigned RBegin, REnd;
3028 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3029 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3031 CCInfo.nextInRegsParam();
3033 CCInfo.rewindByValRegsInfo();
3035 int lastInsIndex = -1;
3036 if (isVarArg && MFI->hasVAStart()) {
3037 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3038 if (RegIdx != array_lengthof(GPRArgRegs))
3039 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3042 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3043 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3044 auto PtrVT = getPointerTy(DAG.getDataLayout());
3046 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3047 CCValAssign &VA = ArgLocs[i];
3048 if (Ins[VA.getValNo()].isOrigArg()) {
3049 std::advance(CurOrigArg,
3050 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3051 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3053 // Arguments stored in registers.
3054 if (VA.isRegLoc()) {
3055 EVT RegVT = VA.getLocVT();
3057 if (VA.needsCustom()) {
3058 // f64 and vector types are split up into multiple registers or
3059 // combinations of registers and stack slots.
3060 if (VA.getLocVT() == MVT::v2f64) {
3061 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3063 VA = ArgLocs[++i]; // skip ahead to next loc
3065 if (VA.isMemLoc()) {
3066 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3067 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3068 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3069 MachinePointerInfo::getFixedStack(FI),
3070 false, false, false, 0);
3072 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3075 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3076 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3077 ArgValue, ArgValue1,
3078 DAG.getIntPtrConstant(0, dl));
3079 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3080 ArgValue, ArgValue2,
3081 DAG.getIntPtrConstant(1, dl));
3083 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3086 const TargetRegisterClass *RC;
3088 if (RegVT == MVT::f32)
3089 RC = &ARM::SPRRegClass;
3090 else if (RegVT == MVT::f64)
3091 RC = &ARM::DPRRegClass;
3092 else if (RegVT == MVT::v2f64)
3093 RC = &ARM::QPRRegClass;
3094 else if (RegVT == MVT::i32)
3095 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3096 : &ARM::GPRRegClass;
3098 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3100 // Transform the arguments in physical registers into virtual ones.
3101 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3102 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3105 // If this is an 8 or 16-bit value, it is really passed promoted
3106 // to 32 bits. Insert an assert[sz]ext to capture this, then
3107 // truncate to the right size.
3108 switch (VA.getLocInfo()) {
3109 default: llvm_unreachable("Unknown loc info!");
3110 case CCValAssign::Full: break;
3111 case CCValAssign::BCvt:
3112 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3114 case CCValAssign::SExt:
3115 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3116 DAG.getValueType(VA.getValVT()));
3117 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3119 case CCValAssign::ZExt:
3120 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3121 DAG.getValueType(VA.getValVT()));
3122 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3126 InVals.push_back(ArgValue);
3128 } else { // VA.isRegLoc()
3131 assert(VA.isMemLoc());
3132 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3134 int index = VA.getValNo();
3136 // Some Ins[] entries become multiple ArgLoc[] entries.
3137 // Process them only once.
3138 if (index != lastInsIndex)
3140 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3141 // FIXME: For now, all byval parameter objects are marked mutable.
3142 // This can be changed with more analysis.
3143 // In case of tail call optimization mark all arguments mutable.
3144 // Since they could be overwritten by lowering of arguments in case of
3146 if (Flags.isByVal()) {
3147 assert(Ins[index].isOrigArg() &&
3148 "Byval arguments cannot be implicit");
3149 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3151 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3152 CurByValIndex, VA.getLocMemOffset(),
3153 Flags.getByValSize());
3154 InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3155 CCInfo.nextInRegsParam();
3157 unsigned FIOffset = VA.getLocMemOffset();
3158 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3161 // Create load nodes to retrieve arguments from the stack.
3162 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3163 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3164 MachinePointerInfo::getFixedStack(FI),
3165 false, false, false, 0));
3167 lastInsIndex = index;
3173 if (isVarArg && MFI->hasVAStart())
3174 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3175 CCInfo.getNextStackOffset(),
3176 TotalArgRegsSaveSize);
3178 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3183 /// isFloatingPointZero - Return true if this is +0.0.
3184 static bool isFloatingPointZero(SDValue Op) {
3185 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3186 return CFP->getValueAPF().isPosZero();
3187 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3188 // Maybe this has already been legalized into the constant pool?
3189 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3190 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3191 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3192 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3193 return CFP->getValueAPF().isPosZero();
3195 } else if (Op->getOpcode() == ISD::BITCAST &&
3196 Op->getValueType(0) == MVT::f64) {
3197 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3198 // created by LowerConstantFP().
3199 SDValue BitcastOp = Op->getOperand(0);
3200 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3201 SDValue MoveOp = BitcastOp->getOperand(0);
3202 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3203 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3211 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3212 /// the given operands.
3214 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3215 SDValue &ARMcc, SelectionDAG &DAG,
3217 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3218 unsigned C = RHSC->getZExtValue();
3219 if (!isLegalICmpImmediate(C)) {
3220 // Constant does not fit, try adjusting it by one?
3225 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3226 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3227 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3232 if (C != 0 && isLegalICmpImmediate(C-1)) {
3233 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3234 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3239 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3240 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3241 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3246 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3247 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3248 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3255 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3256 ARMISD::NodeType CompareType;
3259 CompareType = ARMISD::CMP;
3264 CompareType = ARMISD::CMPZ;
3267 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3268 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3271 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3273 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3275 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3277 if (!isFloatingPointZero(RHS))
3278 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3280 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3281 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3284 /// duplicateCmp - Glue values can have only one use, so this function
3285 /// duplicates a comparison node.
3287 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3288 unsigned Opc = Cmp.getOpcode();
3290 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3291 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3293 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3294 Cmp = Cmp.getOperand(0);
3295 Opc = Cmp.getOpcode();
3296 if (Opc == ARMISD::CMPFP)
3297 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3299 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3300 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3302 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3305 std::pair<SDValue, SDValue>
3306 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3307 SDValue &ARMcc) const {
3308 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3310 SDValue Value, OverflowCmp;
3311 SDValue LHS = Op.getOperand(0);
3312 SDValue RHS = Op.getOperand(1);
3315 // FIXME: We are currently always generating CMPs because we don't support
3316 // generating CMN through the backend. This is not as good as the natural
3317 // CMP case because it causes a register dependency and cannot be folded
3320 switch (Op.getOpcode()) {
3322 llvm_unreachable("Unknown overflow instruction!");
3324 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3325 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3326 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3329 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3330 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3331 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3334 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3335 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3336 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3339 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3340 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3341 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3345 return std::make_pair(Value, OverflowCmp);
3350 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3351 // Let legalize expand this if it isn't a legal type yet.
3352 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3355 SDValue Value, OverflowCmp;
3357 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3358 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3360 // We use 0 and 1 as false and true values.
3361 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3362 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3363 EVT VT = Op.getValueType();
3365 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3366 ARMcc, CCR, OverflowCmp);
3368 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3369 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3373 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3374 SDValue Cond = Op.getOperand(0);
3375 SDValue SelectTrue = Op.getOperand(1);
3376 SDValue SelectFalse = Op.getOperand(2);
3378 unsigned Opc = Cond.getOpcode();
3380 if (Cond.getResNo() == 1 &&
3381 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3382 Opc == ISD::USUBO)) {
3383 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3386 SDValue Value, OverflowCmp;
3388 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3389 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3390 EVT VT = Op.getValueType();
3392 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3398 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3399 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3401 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3402 const ConstantSDNode *CMOVTrue =
3403 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3404 const ConstantSDNode *CMOVFalse =
3405 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3407 if (CMOVTrue && CMOVFalse) {
3408 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3409 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3413 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3415 False = SelectFalse;
3416 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3421 if (True.getNode() && False.getNode()) {
3422 EVT VT = Op.getValueType();
3423 SDValue ARMcc = Cond.getOperand(2);
3424 SDValue CCR = Cond.getOperand(3);
3425 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3426 assert(True.getValueType() == VT);
3427 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3432 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3433 // undefined bits before doing a full-word comparison with zero.
3434 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3435 DAG.getConstant(1, dl, Cond.getValueType()));
3437 return DAG.getSelectCC(dl, Cond,
3438 DAG.getConstant(0, dl, Cond.getValueType()),
3439 SelectTrue, SelectFalse, ISD::SETNE);
3442 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3443 bool &swpCmpOps, bool &swpVselOps) {
3444 // Start by selecting the GE condition code for opcodes that return true for
3446 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3448 CondCode = ARMCC::GE;
3450 // and GT for opcodes that return false for 'equality'.
3451 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3453 CondCode = ARMCC::GT;
3455 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3456 // to swap the compare operands.
3457 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3461 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3462 // If we have an unordered opcode, we need to swap the operands to the VSEL
3463 // instruction (effectively negating the condition).
3465 // This also has the effect of swapping which one of 'less' or 'greater'
3466 // returns true, so we also swap the compare operands. It also switches
3467 // whether we return true for 'equality', so we compensate by picking the
3468 // opposite condition code to our original choice.
3469 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3470 CC == ISD::SETUGT) {
3471 swpCmpOps = !swpCmpOps;
3472 swpVselOps = !swpVselOps;
3473 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3476 // 'ordered' is 'anything but unordered', so use the VS condition code and
3477 // swap the VSEL operands.
3478 if (CC == ISD::SETO) {
3479 CondCode = ARMCC::VS;
3483 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3484 // code and swap the VSEL operands.
3485 if (CC == ISD::SETUNE) {
3486 CondCode = ARMCC::EQ;
3491 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3492 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3493 SDValue Cmp, SelectionDAG &DAG) const {
3494 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3495 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3496 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3497 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3498 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3500 SDValue TrueLow = TrueVal.getValue(0);
3501 SDValue TrueHigh = TrueVal.getValue(1);
3502 SDValue FalseLow = FalseVal.getValue(0);
3503 SDValue FalseHigh = FalseVal.getValue(1);
3505 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3507 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3508 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3510 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3512 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3517 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3518 EVT VT = Op.getValueType();
3519 SDValue LHS = Op.getOperand(0);
3520 SDValue RHS = Op.getOperand(1);
3521 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3522 SDValue TrueVal = Op.getOperand(2);
3523 SDValue FalseVal = Op.getOperand(3);
3526 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3527 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3530 // If softenSetCCOperands only returned one value, we should compare it to
3532 if (!RHS.getNode()) {
3533 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3538 if (LHS.getValueType() == MVT::i32) {
3539 // Try to generate VSEL on ARMv8.
3540 // The VSEL instruction can't use all the usual ARM condition
3541 // codes: it only has two bits to select the condition code, so it's
3542 // constrained to use only GE, GT, VS and EQ.
3544 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3545 // swap the operands of the previous compare instruction (effectively
3546 // inverting the compare condition, swapping 'less' and 'greater') and
3547 // sometimes need to swap the operands to the VSEL (which inverts the
3548 // condition in the sense of firing whenever the previous condition didn't)
3549 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3550 TrueVal.getValueType() == MVT::f64)) {
3551 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3552 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3553 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3554 CC = ISD::getSetCCInverse(CC, true);
3555 std::swap(TrueVal, FalseVal);
3560 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3561 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3562 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3565 ARMCC::CondCodes CondCode, CondCode2;
3566 FPCCToARMCC(CC, CondCode, CondCode2);
3568 // Try to generate VMAXNM/VMINNM on ARMv8.
3569 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3570 TrueVal.getValueType() == MVT::f64)) {
3571 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3572 // same operands, as follows:
3573 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3575 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3576 bool swapSides = false;
3577 if (!getTargetMachine().Options.NoNaNsFPMath) {
3578 // transformability may depend on which way around we compare
3586 // the non-NaN should be RHS
3587 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3593 // the non-NaN should be LHS
3594 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3598 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3600 CC = ISD::getSetCCSwappedOperands(CC);
3601 std::swap(LHS, RHS);
3603 if (LHS == TrueVal && RHS == FalseVal) {
3604 bool canTransform = true;
3605 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3606 if (!getTargetMachine().Options.UnsafeFPMath &&
3607 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3608 const ConstantFPSDNode *Zero;
3615 // RHS must not be -0
3616 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3617 !Zero->isNegative();
3622 // LHS must not be -0
3623 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3624 !Zero->isNegative();
3629 // RHS must not be +0
3630 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3636 // LHS must not be +0
3637 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3643 // Note: If one of the elements in a pair is a number and the other
3644 // element is NaN, the corresponding result element is the number.
3645 // This is consistent with the IEEE 754-2008 standard.
3646 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3652 if (!DAG.isKnownNeverNaN(RHS))
3654 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3657 if (!DAG.isKnownNeverNaN(LHS))
3661 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3664 if (!DAG.isKnownNeverNaN(RHS))
3666 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3669 if (!DAG.isKnownNeverNaN(LHS))
3673 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3678 bool swpCmpOps = false;
3679 bool swpVselOps = false;
3680 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3682 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3683 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3685 std::swap(LHS, RHS);
3687 std::swap(TrueVal, FalseVal);
3691 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3692 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3693 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3694 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3695 if (CondCode2 != ARMCC::AL) {
3696 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3697 // FIXME: Needs another CMP because flag can have but one use.
3698 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3699 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3704 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3705 /// to morph to an integer compare sequence.
3706 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3707 const ARMSubtarget *Subtarget) {
3708 SDNode *N = Op.getNode();
3709 if (!N->hasOneUse())
3710 // Otherwise it requires moving the value from fp to integer registers.
3712 if (!N->getNumValues())
3714 EVT VT = Op.getValueType();
3715 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3716 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3717 // vmrs are very slow, e.g. cortex-a8.
3720 if (isFloatingPointZero(Op)) {
3724 return ISD::isNormalLoad(N);
3727 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3728 if (isFloatingPointZero(Op))
3729 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3731 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3732 return DAG.getLoad(MVT::i32, SDLoc(Op),
3733 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3734 Ld->isVolatile(), Ld->isNonTemporal(),
3735 Ld->isInvariant(), Ld->getAlignment());
3737 llvm_unreachable("Unknown VFP cmp argument!");
3740 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3741 SDValue &RetVal1, SDValue &RetVal2) {
3744 if (isFloatingPointZero(Op)) {
3745 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3746 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3750 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3751 SDValue Ptr = Ld->getBasePtr();
3752 RetVal1 = DAG.getLoad(MVT::i32, dl,
3753 Ld->getChain(), Ptr,
3754 Ld->getPointerInfo(),
3755 Ld->isVolatile(), Ld->isNonTemporal(),
3756 Ld->isInvariant(), Ld->getAlignment());
3758 EVT PtrType = Ptr.getValueType();
3759 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3760 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3761 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3762 RetVal2 = DAG.getLoad(MVT::i32, dl,
3763 Ld->getChain(), NewPtr,
3764 Ld->getPointerInfo().getWithOffset(4),
3765 Ld->isVolatile(), Ld->isNonTemporal(),
3766 Ld->isInvariant(), NewAlign);
3770 llvm_unreachable("Unknown VFP cmp argument!");
3773 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3774 /// f32 and even f64 comparisons to integer ones.
3776 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3777 SDValue Chain = Op.getOperand(0);
3778 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3779 SDValue LHS = Op.getOperand(2);
3780 SDValue RHS = Op.getOperand(3);
3781 SDValue Dest = Op.getOperand(4);
3784 bool LHSSeenZero = false;
3785 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3786 bool RHSSeenZero = false;
3787 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3788 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3789 // If unsafe fp math optimization is enabled and there are no other uses of
3790 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3791 // to an integer comparison.
3792 if (CC == ISD::SETOEQ)
3794 else if (CC == ISD::SETUNE)
3797 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3799 if (LHS.getValueType() == MVT::f32) {
3800 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3801 bitcastf32Toi32(LHS, DAG), Mask);
3802 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3803 bitcastf32Toi32(RHS, DAG), Mask);
3804 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3805 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3807 Chain, Dest, ARMcc, CCR, Cmp);
3812 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3813 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3814 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3815 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3816 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3817 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3818 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3819 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3820 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3826 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3827 SDValue Chain = Op.getOperand(0);
3828 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3829 SDValue LHS = Op.getOperand(2);
3830 SDValue RHS = Op.getOperand(3);
3831 SDValue Dest = Op.getOperand(4);
3834 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3835 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3838 // If softenSetCCOperands only returned one value, we should compare it to
3840 if (!RHS.getNode()) {
3841 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3846 if (LHS.getValueType() == MVT::i32) {
3848 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3849 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3850 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3851 Chain, Dest, ARMcc, CCR, Cmp);
3854 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3856 if (getTargetMachine().Options.UnsafeFPMath &&
3857 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3858 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3859 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3860 if (Result.getNode())
3864 ARMCC::CondCodes CondCode, CondCode2;
3865 FPCCToARMCC(CC, CondCode, CondCode2);
3867 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3868 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3869 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3870 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3871 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3872 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3873 if (CondCode2 != ARMCC::AL) {
3874 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3875 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3876 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3881 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3882 SDValue Chain = Op.getOperand(0);
3883 SDValue Table = Op.getOperand(1);
3884 SDValue Index = Op.getOperand(2);
3887 EVT PTy = getPointerTy(DAG.getDataLayout());
3888 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3889 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3890 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3891 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3892 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3893 if (Subtarget->isThumb2()) {
3894 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3895 // which does another jump to the destination. This also makes it easier
3896 // to translate it to TBB / TBH later.
3897 // FIXME: This might not work if the function is extremely large.
3898 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3899 Addr, Op.getOperand(2), JTI);
3901 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3902 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3903 MachinePointerInfo::getJumpTable(),
3904 false, false, false, 0);
3905 Chain = Addr.getValue(1);
3906 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3907 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3909 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3910 MachinePointerInfo::getJumpTable(),
3911 false, false, false, 0);
3912 Chain = Addr.getValue(1);
3913 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3917 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3918 EVT VT = Op.getValueType();
3921 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3922 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3924 return DAG.UnrollVectorOp(Op.getNode());
3927 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3928 "Invalid type for custom lowering!");
3929 if (VT != MVT::v4i16)
3930 return DAG.UnrollVectorOp(Op.getNode());
3932 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3933 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3936 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3937 EVT VT = Op.getValueType();
3939 return LowerVectorFP_TO_INT(Op, DAG);
3940 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3942 if (Op.getOpcode() == ISD::FP_TO_SINT)
3943 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3946 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3948 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3949 /*isSigned*/ false, SDLoc(Op)).first;
3955 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3956 EVT VT = Op.getValueType();
3959 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3960 if (VT.getVectorElementType() == MVT::f32)
3962 return DAG.UnrollVectorOp(Op.getNode());
3965 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3966 "Invalid type for custom lowering!");
3967 if (VT != MVT::v4f32)
3968 return DAG.UnrollVectorOp(Op.getNode());
3972 switch (Op.getOpcode()) {
3973 default: llvm_unreachable("Invalid opcode!");
3974 case ISD::SINT_TO_FP:
3975 CastOpc = ISD::SIGN_EXTEND;
3976 Opc = ISD::SINT_TO_FP;
3978 case ISD::UINT_TO_FP:
3979 CastOpc = ISD::ZERO_EXTEND;
3980 Opc = ISD::UINT_TO_FP;
3984 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3985 return DAG.getNode(Opc, dl, VT, Op);
3988 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3989 EVT VT = Op.getValueType();
3991 return LowerVectorINT_TO_FP(Op, DAG);
3992 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3994 if (Op.getOpcode() == ISD::SINT_TO_FP)
3995 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3998 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4000 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4001 /*isSigned*/ false, SDLoc(Op)).first;
4007 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4008 // Implement fcopysign with a fabs and a conditional fneg.
4009 SDValue Tmp0 = Op.getOperand(0);
4010 SDValue Tmp1 = Op.getOperand(1);
4012 EVT VT = Op.getValueType();
4013 EVT SrcVT = Tmp1.getValueType();
4014 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4015 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4016 bool UseNEON = !InGPR && Subtarget->hasNEON();
4019 // Use VBSL to copy the sign bit.
4020 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4021 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4022 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4023 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4025 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4026 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4027 DAG.getConstant(32, dl, MVT::i32));
4028 else /*if (VT == MVT::f32)*/
4029 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4030 if (SrcVT == MVT::f32) {
4031 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4033 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4034 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4035 DAG.getConstant(32, dl, MVT::i32));
4036 } else if (VT == MVT::f32)
4037 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4038 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4039 DAG.getConstant(32, dl, MVT::i32));
4040 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4041 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4043 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4045 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4046 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4047 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4049 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4050 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4051 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4052 if (VT == MVT::f32) {
4053 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4054 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4055 DAG.getConstant(0, dl, MVT::i32));
4057 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4063 // Bitcast operand 1 to i32.
4064 if (SrcVT == MVT::f64)
4065 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4067 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4069 // Or in the signbit with integer operations.
4070 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4071 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4072 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4073 if (VT == MVT::f32) {
4074 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4075 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4076 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4077 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4080 // f64: Or the high part with signbit and then combine two parts.
4081 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4083 SDValue Lo = Tmp0.getValue(0);
4084 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4085 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4086 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4089 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4090 MachineFunction &MF = DAG.getMachineFunction();
4091 MachineFrameInfo *MFI = MF.getFrameInfo();
4092 MFI->setReturnAddressIsTaken(true);
4094 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4097 EVT VT = Op.getValueType();
4099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4101 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4102 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4103 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4104 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4105 MachinePointerInfo(), false, false, false, 0);
4108 // Return LR, which contains the return address. Mark it an implicit live-in.
4109 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4110 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4113 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4114 const ARMBaseRegisterInfo &ARI =
4115 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4116 MachineFunction &MF = DAG.getMachineFunction();
4117 MachineFrameInfo *MFI = MF.getFrameInfo();
4118 MFI->setFrameAddressIsTaken(true);
4120 EVT VT = Op.getValueType();
4121 SDLoc dl(Op); // FIXME probably not meaningful
4122 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4123 unsigned FrameReg = ARI.getFrameRegister(MF);
4124 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4126 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4127 MachinePointerInfo(),
4128 false, false, false, 0);
4132 // FIXME? Maybe this could be a TableGen attribute on some registers and
4133 // this table could be generated automatically from RegInfo.
4134 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4135 SelectionDAG &DAG) const {
4136 unsigned Reg = StringSwitch<unsigned>(RegName)
4137 .Case("sp", ARM::SP)
4141 report_fatal_error(Twine("Invalid register name \""
4142 + StringRef(RegName) + "\"."));
4145 // Result is 64 bit value so split into two 32 bit values and return as a
4147 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4148 SelectionDAG &DAG) {
4151 // This function is only supposed to be called for i64 type destination.
4152 assert(N->getValueType(0) == MVT::i64
4153 && "ExpandREAD_REGISTER called for non-i64 type result.");
4155 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4156 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4160 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4162 Results.push_back(Read.getOperand(0));
4165 /// ExpandBITCAST - If the target supports VFP, this function is called to
4166 /// expand a bit convert where either the source or destination type is i64 to
4167 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4168 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4169 /// vectors), since the legalizer won't know what to do with that.
4170 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4171 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4173 SDValue Op = N->getOperand(0);
4175 // This function is only supposed to be called for i64 types, either as the
4176 // source or destination of the bit convert.
4177 EVT SrcVT = Op.getValueType();
4178 EVT DstVT = N->getValueType(0);
4179 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4180 "ExpandBITCAST called for non-i64 type");
4182 // Turn i64->f64 into VMOVDRR.
4183 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4184 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4185 DAG.getConstant(0, dl, MVT::i32));
4186 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4187 DAG.getConstant(1, dl, MVT::i32));
4188 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4189 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4192 // Turn f64->i64 into VMOVRRD.
4193 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4195 if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4196 SrcVT.getVectorNumElements() > 1)
4197 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4198 DAG.getVTList(MVT::i32, MVT::i32),
4199 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4201 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4202 DAG.getVTList(MVT::i32, MVT::i32), Op);
4203 // Merge the pieces into a single i64 value.
4204 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4210 /// getZeroVector - Returns a vector of specified type with all zero elements.
4211 /// Zero vectors are used to represent vector negation and in those cases
4212 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4213 /// not support i64 elements, so sometimes the zero vectors will need to be
4214 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4216 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4217 assert(VT.isVector() && "Expected a vector type");
4218 // The canonical modified immediate encoding of a zero vector is....0!
4219 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4220 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4221 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4222 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4225 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4226 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4227 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4228 SelectionDAG &DAG) const {
4229 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4230 EVT VT = Op.getValueType();
4231 unsigned VTBits = VT.getSizeInBits();
4233 SDValue ShOpLo = Op.getOperand(0);
4234 SDValue ShOpHi = Op.getOperand(1);
4235 SDValue ShAmt = Op.getOperand(2);
4237 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4239 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4241 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4242 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4243 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4244 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4245 DAG.getConstant(VTBits, dl, MVT::i32));
4246 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4247 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4248 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4250 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4251 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4252 ISD::SETGE, ARMcc, DAG, dl);
4253 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4254 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4257 SDValue Ops[2] = { Lo, Hi };
4258 return DAG.getMergeValues(Ops, dl);
4261 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4262 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4263 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4264 SelectionDAG &DAG) const {
4265 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4266 EVT VT = Op.getValueType();
4267 unsigned VTBits = VT.getSizeInBits();
4269 SDValue ShOpLo = Op.getOperand(0);
4270 SDValue ShOpHi = Op.getOperand(1);
4271 SDValue ShAmt = Op.getOperand(2);
4274 assert(Op.getOpcode() == ISD::SHL_PARTS);
4275 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4276 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4277 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4278 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4279 DAG.getConstant(VTBits, dl, MVT::i32));
4280 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4281 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4283 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4284 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4285 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4286 ISD::SETGE, ARMcc, DAG, dl);
4287 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4288 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4291 SDValue Ops[2] = { Lo, Hi };
4292 return DAG.getMergeValues(Ops, dl);
4295 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4296 SelectionDAG &DAG) const {
4297 // The rounding mode is in bits 23:22 of the FPSCR.
4298 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4299 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4300 // so that the shift + and get folded into a bitfield extract.
4302 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4303 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4305 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4306 DAG.getConstant(1U << 22, dl, MVT::i32));
4307 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4308 DAG.getConstant(22, dl, MVT::i32));
4309 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4310 DAG.getConstant(3, dl, MVT::i32));
4313 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4314 const ARMSubtarget *ST) {
4316 EVT VT = N->getValueType(0);
4317 if (VT.isVector()) {
4318 assert(ST->hasNEON());
4320 // Compute the least significant set bit: LSB = X & -X
4321 SDValue X = N->getOperand(0);
4322 SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4323 SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4325 EVT ElemTy = VT.getVectorElementType();
4327 if (ElemTy == MVT::i8) {
4328 // Compute with: cttz(x) = ctpop(lsb - 1)
4329 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4330 DAG.getTargetConstant(1, dl, ElemTy));
4331 SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4332 return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4335 if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4336 (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4337 // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4338 unsigned NumBits = ElemTy.getSizeInBits();
4339 SDValue WidthMinus1 =
4340 DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4341 DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4342 SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4343 return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4346 // Compute with: cttz(x) = ctpop(lsb - 1)
4348 // Since we can only compute the number of bits in a byte with vcnt.8, we
4349 // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4354 if (ElemTy == MVT::i64) {
4355 // Load constant 0xffff'ffff'ffff'ffff to register.
4356 SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4357 DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4358 Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4360 SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4361 DAG.getTargetConstant(1, dl, ElemTy));
4362 Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4365 // Count #bits with vcnt.8.
4366 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4367 SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4368 SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4370 // Gather the #bits with vpaddl (pairwise add.)
4371 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4372 SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4373 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4375 if (ElemTy == MVT::i16)
4378 EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4379 SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4380 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4382 if (ElemTy == MVT::i32)
4385 assert(ElemTy == MVT::i64);
4386 SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4387 DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4392 if (!ST->hasV6T2Ops())
4395 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4396 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4399 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4400 /// for each 16-bit element from operand, repeated. The basic idea is to
4401 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4403 /// Trace for v4i16:
4404 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4405 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4406 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4407 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4408 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4409 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4410 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4411 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4412 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4413 EVT VT = N->getValueType(0);
4416 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4417 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4418 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4419 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4420 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4421 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4424 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4425 /// bit-count for each 16-bit element from the operand. We need slightly
4426 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4427 /// 64/128-bit registers.
4429 /// Trace for v4i16:
4430 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4431 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4432 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4433 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4434 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4435 EVT VT = N->getValueType(0);
4438 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4439 if (VT.is64BitVector()) {
4440 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4441 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4442 DAG.getIntPtrConstant(0, DL));
4444 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4445 BitCounts, DAG.getIntPtrConstant(0, DL));
4446 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4450 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4451 /// bit-count for each 32-bit element from the operand. The idea here is
4452 /// to split the vector into 16-bit elements, leverage the 16-bit count
4453 /// routine, and then combine the results.
4455 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4456 /// input = [v0 v1 ] (vi: 32-bit elements)
4457 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4458 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4459 /// vrev: N0 = [k1 k0 k3 k2 ]
4461 /// N1 =+[k1 k0 k3 k2 ]
4463 /// N2 =+[k1 k3 k0 k2 ]
4465 /// Extended =+[k1 k3 k0 k2 ]
4467 /// Extracted=+[k1 k3 ]
4469 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4470 EVT VT = N->getValueType(0);
4473 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4475 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4476 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4477 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4478 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4479 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4481 if (VT.is64BitVector()) {
4482 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4483 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4484 DAG.getIntPtrConstant(0, DL));
4486 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4487 DAG.getIntPtrConstant(0, DL));
4488 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4492 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4493 const ARMSubtarget *ST) {
4494 EVT VT = N->getValueType(0);
4496 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4497 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4498 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4499 "Unexpected type for custom ctpop lowering");
4501 if (VT.getVectorElementType() == MVT::i32)
4502 return lowerCTPOP32BitElements(N, DAG);
4504 return lowerCTPOP16BitElements(N, DAG);
4507 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4508 const ARMSubtarget *ST) {
4509 EVT VT = N->getValueType(0);
4515 // Lower vector shifts on NEON to use VSHL.
4516 assert(ST->hasNEON() && "unexpected vector shift");
4518 // Left shifts translate directly to the vshiftu intrinsic.
4519 if (N->getOpcode() == ISD::SHL)
4520 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4521 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4523 N->getOperand(0), N->getOperand(1));
4525 assert((N->getOpcode() == ISD::SRA ||
4526 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4528 // NEON uses the same intrinsics for both left and right shifts. For
4529 // right shifts, the shift amounts are negative, so negate the vector of
4531 EVT ShiftVT = N->getOperand(1).getValueType();
4532 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4533 getZeroVector(ShiftVT, DAG, dl),
4535 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4536 Intrinsic::arm_neon_vshifts :
4537 Intrinsic::arm_neon_vshiftu);
4538 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4539 DAG.getConstant(vshiftInt, dl, MVT::i32),
4540 N->getOperand(0), NegatedCount);
4543 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4544 const ARMSubtarget *ST) {
4545 EVT VT = N->getValueType(0);
4548 // We can get here for a node like i32 = ISD::SHL i32, i64
4552 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4553 "Unknown shift to lower!");
4555 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4556 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4557 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4560 // If we are in thumb mode, we don't have RRX.
4561 if (ST->isThumb1Only()) return SDValue();
4563 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4564 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4565 DAG.getConstant(0, dl, MVT::i32));
4566 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4567 DAG.getConstant(1, dl, MVT::i32));
4569 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4570 // captures the result into a carry flag.
4571 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4572 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4574 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4575 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4577 // Merge the pieces into a single i64 value.
4578 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4581 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4582 SDValue TmpOp0, TmpOp1;
4583 bool Invert = false;
4587 SDValue Op0 = Op.getOperand(0);
4588 SDValue Op1 = Op.getOperand(1);
4589 SDValue CC = Op.getOperand(2);
4590 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4591 EVT VT = Op.getValueType();
4592 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4595 if (Op1.getValueType().isFloatingPoint()) {
4596 switch (SetCCOpcode) {
4597 default: llvm_unreachable("Illegal FP comparison");
4599 case ISD::SETNE: Invert = true; // Fallthrough
4601 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4603 case ISD::SETLT: Swap = true; // Fallthrough
4605 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4607 case ISD::SETLE: Swap = true; // Fallthrough
4609 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4610 case ISD::SETUGE: Swap = true; // Fallthrough
4611 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4612 case ISD::SETUGT: Swap = true; // Fallthrough
4613 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4614 case ISD::SETUEQ: Invert = true; // Fallthrough
4616 // Expand this to (OLT | OGT).
4620 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4621 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4623 case ISD::SETUO: Invert = true; // Fallthrough
4625 // Expand this to (OLT | OGE).
4629 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4630 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4634 // Integer comparisons.
4635 switch (SetCCOpcode) {
4636 default: llvm_unreachable("Illegal integer comparison");
4637 case ISD::SETNE: Invert = true;
4638 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4639 case ISD::SETLT: Swap = true;
4640 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4641 case ISD::SETLE: Swap = true;
4642 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4643 case ISD::SETULT: Swap = true;
4644 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4645 case ISD::SETULE: Swap = true;
4646 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4649 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4650 if (Opc == ARMISD::VCEQ) {
4653 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4655 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4658 // Ignore bitconvert.
4659 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4660 AndOp = AndOp.getOperand(0);
4662 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4664 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4665 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4672 std::swap(Op0, Op1);
4674 // If one of the operands is a constant vector zero, attempt to fold the
4675 // comparison to a specialized compare-against-zero form.
4677 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4679 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4680 if (Opc == ARMISD::VCGE)
4681 Opc = ARMISD::VCLEZ;
4682 else if (Opc == ARMISD::VCGT)
4683 Opc = ARMISD::VCLTZ;
4688 if (SingleOp.getNode()) {
4691 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4693 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4695 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4697 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4699 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4701 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4704 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4707 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4710 Result = DAG.getNOT(dl, Result, VT);
4715 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4716 /// valid vector constant for a NEON instruction with a "modified immediate"
4717 /// operand (e.g., VMOV). If so, return the encoded value.
4718 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4719 unsigned SplatBitSize, SelectionDAG &DAG,
4720 SDLoc dl, EVT &VT, bool is128Bits,
4721 NEONModImmType type) {
4722 unsigned OpCmode, Imm;
4724 // SplatBitSize is set to the smallest size that splats the vector, so a
4725 // zero vector will always have SplatBitSize == 8. However, NEON modified
4726 // immediate instructions others than VMOV do not support the 8-bit encoding
4727 // of a zero vector, and the default encoding of zero is supposed to be the
4732 switch (SplatBitSize) {
4734 if (type != VMOVModImm)
4736 // Any 1-byte value is OK. Op=0, Cmode=1110.
4737 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4740 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4744 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4745 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4746 if ((SplatBits & ~0xff) == 0) {
4747 // Value = 0x00nn: Op=x, Cmode=100x.
4752 if ((SplatBits & ~0xff00) == 0) {
4753 // Value = 0xnn00: Op=x, Cmode=101x.
4755 Imm = SplatBits >> 8;
4761 // NEON's 32-bit VMOV supports splat values where:
4762 // * only one byte is nonzero, or
4763 // * the least significant byte is 0xff and the second byte is nonzero, or
4764 // * the least significant 2 bytes are 0xff and the third is nonzero.
4765 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4766 if ((SplatBits & ~0xff) == 0) {
4767 // Value = 0x000000nn: Op=x, Cmode=000x.
4772 if ((SplatBits & ~0xff00) == 0) {
4773 // Value = 0x0000nn00: Op=x, Cmode=001x.
4775 Imm = SplatBits >> 8;
4778 if ((SplatBits & ~0xff0000) == 0) {
4779 // Value = 0x00nn0000: Op=x, Cmode=010x.
4781 Imm = SplatBits >> 16;
4784 if ((SplatBits & ~0xff000000) == 0) {
4785 // Value = 0xnn000000: Op=x, Cmode=011x.
4787 Imm = SplatBits >> 24;
4791 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4792 if (type == OtherModImm) return SDValue();
4794 if ((SplatBits & ~0xffff) == 0 &&
4795 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4796 // Value = 0x0000nnff: Op=x, Cmode=1100.
4798 Imm = SplatBits >> 8;
4802 if ((SplatBits & ~0xffffff) == 0 &&
4803 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4804 // Value = 0x00nnffff: Op=x, Cmode=1101.
4806 Imm = SplatBits >> 16;
4810 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4811 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4812 // VMOV.I32. A (very) minor optimization would be to replicate the value
4813 // and fall through here to test for a valid 64-bit splat. But, then the
4814 // caller would also need to check and handle the change in size.
4818 if (type != VMOVModImm)
4820 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4821 uint64_t BitMask = 0xff;
4823 unsigned ImmMask = 1;
4825 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4826 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4829 } else if ((SplatBits & BitMask) != 0) {
4836 if (DAG.getDataLayout().isBigEndian())
4837 // swap higher and lower 32 bit word
4838 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4840 // Op=1, Cmode=1110.
4842 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4847 llvm_unreachable("unexpected size for isNEONModifiedImm");
4850 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4851 return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4854 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4855 const ARMSubtarget *ST) const {
4859 bool IsDouble = Op.getValueType() == MVT::f64;
4860 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4862 // Use the default (constant pool) lowering for double constants when we have
4864 if (IsDouble && Subtarget->isFPOnlySP())
4867 // Try splatting with a VMOV.f32...
4868 APFloat FPVal = CFP->getValueAPF();
4869 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4872 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4873 // We have code in place to select a valid ConstantFP already, no need to
4878 // It's a float and we are trying to use NEON operations where
4879 // possible. Lower it to a splat followed by an extract.
4881 SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4882 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4884 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4885 DAG.getConstant(0, DL, MVT::i32));
4888 // The rest of our options are NEON only, make sure that's allowed before
4890 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4894 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4896 // It wouldn't really be worth bothering for doubles except for one very
4897 // important value, which does happen to match: 0.0. So make sure we don't do
4899 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4902 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4903 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4904 VMovVT, false, VMOVModImm);
4905 if (NewVal != SDValue()) {
4907 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4910 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4912 // It's a float: cast and extract a vector element.
4913 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4915 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4916 DAG.getConstant(0, DL, MVT::i32));
4919 // Finally, try a VMVN.i32
4920 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4922 if (NewVal != SDValue()) {
4924 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4927 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4929 // It's a float: cast and extract a vector element.
4930 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4932 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4933 DAG.getConstant(0, DL, MVT::i32));
4939 // check if an VEXT instruction can handle the shuffle mask when the
4940 // vector sources of the shuffle are the same.
4941 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4942 unsigned NumElts = VT.getVectorNumElements();
4944 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4950 // If this is a VEXT shuffle, the immediate value is the index of the first
4951 // element. The other shuffle indices must be the successive elements after
4953 unsigned ExpectedElt = Imm;
4954 for (unsigned i = 1; i < NumElts; ++i) {
4955 // Increment the expected index. If it wraps around, just follow it
4956 // back to index zero and keep going.
4958 if (ExpectedElt == NumElts)
4961 if (M[i] < 0) continue; // ignore UNDEF indices
4962 if (ExpectedElt != static_cast<unsigned>(M[i]))
4970 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4971 bool &ReverseVEXT, unsigned &Imm) {
4972 unsigned NumElts = VT.getVectorNumElements();
4973 ReverseVEXT = false;
4975 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4981 // If this is a VEXT shuffle, the immediate value is the index of the first
4982 // element. The other shuffle indices must be the successive elements after
4984 unsigned ExpectedElt = Imm;
4985 for (unsigned i = 1; i < NumElts; ++i) {
4986 // Increment the expected index. If it wraps around, it may still be
4987 // a VEXT but the source vectors must be swapped.
4989 if (ExpectedElt == NumElts * 2) {
4994 if (M[i] < 0) continue; // ignore UNDEF indices
4995 if (ExpectedElt != static_cast<unsigned>(M[i]))
4999 // Adjust the index value if the source operands will be swapped.
5006 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5007 /// instruction with the specified blocksize. (The order of the elements
5008 /// within each block of the vector is reversed.)
5009 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5010 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5011 "Only possible block sizes for VREV are: 16, 32, 64");
5013 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5017 unsigned NumElts = VT.getVectorNumElements();
5018 unsigned BlockElts = M[0] + 1;
5019 // If the first shuffle index is UNDEF, be optimistic.
5021 BlockElts = BlockSize / EltSz;
5023 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5026 for (unsigned i = 0; i < NumElts; ++i) {
5027 if (M[i] < 0) continue; // ignore UNDEF indices
5028 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5035 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5036 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5037 // range, then 0 is placed into the resulting vector. So pretty much any mask
5038 // of 8 elements can work here.
5039 return VT == MVT::v8i8 && M.size() == 8;
5042 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5043 // checking that pairs of elements in the shuffle mask represent the same index
5044 // in each vector, incrementing the expected index by 2 at each step.
5045 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5046 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5048 // WhichResult gives the offset for each element in the mask based on which
5049 // of the two results it belongs to.
5051 // The transpose can be represented either as:
5052 // result1 = shufflevector v1, v2, result1_shuffle_mask
5053 // result2 = shufflevector v1, v2, result2_shuffle_mask
5054 // where v1/v2 and the shuffle masks have the same number of elements
5055 // (here WhichResult (see below) indicates which result is being checked)
5058 // results = shufflevector v1, v2, shuffle_mask
5059 // where both results are returned in one vector and the shuffle mask has twice
5060 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5061 // want to check the low half and high half of the shuffle mask as if it were
5063 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5064 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5068 unsigned NumElts = VT.getVectorNumElements();
5069 if (M.size() != NumElts && M.size() != NumElts*2)
5072 // If the mask is twice as long as the result then we need to check the upper
5073 // and lower parts of the mask
5074 for (unsigned i = 0; i < M.size(); i += NumElts) {
5075 WhichResult = M[i] == 0 ? 0 : 1;
5076 for (unsigned j = 0; j < NumElts; j += 2) {
5077 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5078 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5083 if (M.size() == NumElts*2)
5089 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5090 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5091 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5092 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5093 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5097 unsigned NumElts = VT.getVectorNumElements();
5098 if (M.size() != NumElts && M.size() != NumElts*2)
5101 for (unsigned i = 0; i < M.size(); i += NumElts) {
5102 WhichResult = M[i] == 0 ? 0 : 1;
5103 for (unsigned j = 0; j < NumElts; j += 2) {
5104 if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5105 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5110 if (M.size() == NumElts*2)
5116 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5117 // that the mask elements are either all even and in steps of size 2 or all odd
5118 // and in steps of size 2.
5119 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5120 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5122 // Requires similar checks to that of isVTRNMask with
5123 // respect the how results are returned.
5124 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5125 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5129 unsigned NumElts = VT.getVectorNumElements();
5130 if (M.size() != NumElts && M.size() != NumElts*2)
5133 for (unsigned i = 0; i < M.size(); i += NumElts) {
5134 WhichResult = M[i] == 0 ? 0 : 1;
5135 for (unsigned j = 0; j < NumElts; ++j) {
5136 if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5141 if (M.size() == NumElts*2)
5144 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5145 if (VT.is64BitVector() && EltSz == 32)
5151 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5152 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5153 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5154 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5155 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5159 unsigned NumElts = VT.getVectorNumElements();
5160 if (M.size() != NumElts && M.size() != NumElts*2)
5163 unsigned Half = NumElts / 2;
5164 for (unsigned i = 0; i < M.size(); i += NumElts) {
5165 WhichResult = M[i] == 0 ? 0 : 1;
5166 for (unsigned j = 0; j < NumElts; j += Half) {
5167 unsigned Idx = WhichResult;
5168 for (unsigned k = 0; k < Half; ++k) {
5169 int MIdx = M[i + j + k];
5170 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5177 if (M.size() == NumElts*2)
5180 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5181 if (VT.is64BitVector() && EltSz == 32)
5187 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5188 // that pairs of elements of the shufflemask represent the same index in each
5189 // vector incrementing sequentially through the vectors.
5190 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5191 // v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5193 // Requires similar checks to that of isVTRNMask with respect the how results
5195 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5196 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5200 unsigned NumElts = VT.getVectorNumElements();
5201 if (M.size() != NumElts && M.size() != NumElts*2)
5204 for (unsigned i = 0; i < M.size(); i += NumElts) {
5205 WhichResult = M[i] == 0 ? 0 : 1;
5206 unsigned Idx = WhichResult * NumElts / 2;
5207 for (unsigned j = 0; j < NumElts; j += 2) {
5208 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5209 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5215 if (M.size() == NumElts*2)
5218 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5219 if (VT.is64BitVector() && EltSz == 32)
5225 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5226 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5227 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5228 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5229 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5233 unsigned NumElts = VT.getVectorNumElements();
5234 if (M.size() != NumElts && M.size() != NumElts*2)
5237 for (unsigned i = 0; i < M.size(); i += NumElts) {
5238 WhichResult = M[i] == 0 ? 0 : 1;
5239 unsigned Idx = WhichResult * NumElts / 2;
5240 for (unsigned j = 0; j < NumElts; j += 2) {
5241 if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5242 (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5248 if (M.size() == NumElts*2)
5251 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5252 if (VT.is64BitVector() && EltSz == 32)
5258 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5259 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5260 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5261 unsigned &WhichResult,
5264 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5265 return ARMISD::VTRN;
5266 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5267 return ARMISD::VUZP;
5268 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5269 return ARMISD::VZIP;
5272 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5273 return ARMISD::VTRN;
5274 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5275 return ARMISD::VUZP;
5276 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5277 return ARMISD::VZIP;
5282 /// \return true if this is a reverse operation on an vector.
5283 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5284 unsigned NumElts = VT.getVectorNumElements();
5285 // Make sure the mask has the right size.
5286 if (NumElts != M.size())
5289 // Look for <15, ..., 3, -1, 1, 0>.
5290 for (unsigned i = 0; i != NumElts; ++i)
5291 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5297 // If N is an integer constant that can be moved into a register in one
5298 // instruction, return an SDValue of such a constant (will become a MOV
5299 // instruction). Otherwise return null.
5300 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5301 const ARMSubtarget *ST, SDLoc dl) {
5303 if (!isa<ConstantSDNode>(N))
5305 Val = cast<ConstantSDNode>(N)->getZExtValue();
5307 if (ST->isThumb1Only()) {
5308 if (Val <= 255 || ~Val <= 255)
5309 return DAG.getConstant(Val, dl, MVT::i32);
5311 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5312 return DAG.getConstant(Val, dl, MVT::i32);
5317 // If this is a case we can't handle, return null and let the default
5318 // expansion code take care of it.
5319 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5320 const ARMSubtarget *ST) const {
5321 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5323 EVT VT = Op.getValueType();
5325 APInt SplatBits, SplatUndef;
5326 unsigned SplatBitSize;
5328 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5329 if (SplatBitSize <= 64) {
5330 // Check if an immediate VMOV works.
5332 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5333 SplatUndef.getZExtValue(), SplatBitSize,
5334 DAG, dl, VmovVT, VT.is128BitVector(),
5336 if (Val.getNode()) {
5337 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5338 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5341 // Try an immediate VMVN.
5342 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5343 Val = isNEONModifiedImm(NegatedImm,
5344 SplatUndef.getZExtValue(), SplatBitSize,
5345 DAG, dl, VmovVT, VT.is128BitVector(),
5347 if (Val.getNode()) {
5348 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5349 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5352 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5353 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5354 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5356 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5357 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5363 // Scan through the operands to see if only one value is used.
5365 // As an optimisation, even if more than one value is used it may be more
5366 // profitable to splat with one value then change some lanes.
5368 // Heuristically we decide to do this if the vector has a "dominant" value,
5369 // defined as splatted to more than half of the lanes.
5370 unsigned NumElts = VT.getVectorNumElements();
5371 bool isOnlyLowElement = true;
5372 bool usesOnlyOneValue = true;
5373 bool hasDominantValue = false;
5374 bool isConstant = true;
5376 // Map of the number of times a particular SDValue appears in the
5378 DenseMap<SDValue, unsigned> ValueCounts;
5380 for (unsigned i = 0; i < NumElts; ++i) {
5381 SDValue V = Op.getOperand(i);
5382 if (V.getOpcode() == ISD::UNDEF)
5385 isOnlyLowElement = false;
5386 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5389 ValueCounts.insert(std::make_pair(V, 0));
5390 unsigned &Count = ValueCounts[V];
5392 // Is this value dominant? (takes up more than half of the lanes)
5393 if (++Count > (NumElts / 2)) {
5394 hasDominantValue = true;
5398 if (ValueCounts.size() != 1)
5399 usesOnlyOneValue = false;
5400 if (!Value.getNode() && ValueCounts.size() > 0)
5401 Value = ValueCounts.begin()->first;
5403 if (ValueCounts.size() == 0)
5404 return DAG.getUNDEF(VT);
5406 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5407 // Keep going if we are hitting this case.
5408 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5409 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5411 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5413 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5414 // i32 and try again.
5415 if (hasDominantValue && EltSize <= 32) {
5419 // If we are VDUPing a value that comes directly from a vector, that will
5420 // cause an unnecessary move to and from a GPR, where instead we could
5421 // just use VDUPLANE. We can only do this if the lane being extracted
5422 // is at a constant index, as the VDUP from lane instructions only have
5423 // constant-index forms.
5424 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5425 isa<ConstantSDNode>(Value->getOperand(1))) {
5426 // We need to create a new undef vector to use for the VDUPLANE if the
5427 // size of the vector from which we get the value is different than the
5428 // size of the vector that we need to create. We will insert the element
5429 // such that the register coalescer will remove unnecessary copies.
5430 if (VT != Value->getOperand(0).getValueType()) {
5431 ConstantSDNode *constIndex;
5432 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5433 assert(constIndex && "The index is not a constant!");
5434 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5435 VT.getVectorNumElements();
5436 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5437 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5438 Value, DAG.getConstant(index, dl, MVT::i32)),
5439 DAG.getConstant(index, dl, MVT::i32));
5441 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5442 Value->getOperand(0), Value->getOperand(1));
5444 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5446 if (!usesOnlyOneValue) {
5447 // The dominant value was splatted as 'N', but we now have to insert
5448 // all differing elements.
5449 for (unsigned I = 0; I < NumElts; ++I) {
5450 if (Op.getOperand(I) == Value)
5452 SmallVector<SDValue, 3> Ops;
5454 Ops.push_back(Op.getOperand(I));
5455 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5456 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5461 if (VT.getVectorElementType().isFloatingPoint()) {
5462 SmallVector<SDValue, 8> Ops;
5463 for (unsigned i = 0; i < NumElts; ++i)
5464 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5466 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5467 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5468 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5470 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5472 if (usesOnlyOneValue) {
5473 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5474 if (isConstant && Val.getNode())
5475 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5479 // If all elements are constants and the case above didn't get hit, fall back
5480 // to the default expansion, which will generate a load from the constant
5485 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5487 SDValue shuffle = ReconstructShuffle(Op, DAG);
5488 if (shuffle != SDValue())
5492 // Vectors with 32- or 64-bit elements can be built by directly assigning
5493 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5494 // will be legalized.
5495 if (EltSize >= 32) {
5496 // Do the expansion with floating-point types, since that is what the VFP
5497 // registers are defined to use, and since i64 is not legal.
5498 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5499 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5500 SmallVector<SDValue, 8> Ops;
5501 for (unsigned i = 0; i < NumElts; ++i)
5502 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5503 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5504 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5507 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5508 // know the default expansion would otherwise fall back on something even
5509 // worse. For a vector with one or two non-undef values, that's
5510 // scalar_to_vector for the elements followed by a shuffle (provided the
5511 // shuffle is valid for the target) and materialization element by element
5512 // on the stack followed by a load for everything else.
5513 if (!isConstant && !usesOnlyOneValue) {
5514 SDValue Vec = DAG.getUNDEF(VT);
5515 for (unsigned i = 0 ; i < NumElts; ++i) {
5516 SDValue V = Op.getOperand(i);
5517 if (V.getOpcode() == ISD::UNDEF)
5519 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5520 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5528 // Gather data to see if the operation can be modelled as a
5529 // shuffle in combination with VEXTs.
5530 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5531 SelectionDAG &DAG) const {
5533 EVT VT = Op.getValueType();
5534 unsigned NumElts = VT.getVectorNumElements();
5536 SmallVector<SDValue, 2> SourceVecs;
5537 SmallVector<unsigned, 2> MinElts;
5538 SmallVector<unsigned, 2> MaxElts;
5540 for (unsigned i = 0; i < NumElts; ++i) {
5541 SDValue V = Op.getOperand(i);
5542 if (V.getOpcode() == ISD::UNDEF)
5544 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5545 // A shuffle can only come from building a vector from various
5546 // elements of other vectors.
5548 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5549 VT.getVectorElementType()) {
5550 // This code doesn't know how to handle shuffles where the vector
5551 // element types do not match (this happens because type legalization
5552 // promotes the return type of EXTRACT_VECTOR_ELT).
5553 // FIXME: It might be appropriate to extend this code to handle
5554 // mismatched types.
5558 // Record this extraction against the appropriate vector if possible...
5559 SDValue SourceVec = V.getOperand(0);
5560 // If the element number isn't a constant, we can't effectively
5561 // analyze what's going on.
5562 if (!isa<ConstantSDNode>(V.getOperand(1)))
5564 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5565 bool FoundSource = false;
5566 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5567 if (SourceVecs[j] == SourceVec) {
5568 if (MinElts[j] > EltNo)
5570 if (MaxElts[j] < EltNo)
5577 // Or record a new source if not...
5579 SourceVecs.push_back(SourceVec);
5580 MinElts.push_back(EltNo);
5581 MaxElts.push_back(EltNo);
5585 // Currently only do something sane when at most two source vectors
5587 if (SourceVecs.size() > 2)
5590 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5591 int VEXTOffsets[2] = {0, 0};
5593 // This loop extracts the usage patterns of the source vectors
5594 // and prepares appropriate SDValues for a shuffle if possible.
5595 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5596 if (SourceVecs[i].getValueType() == VT) {
5597 // No VEXT necessary
5598 ShuffleSrcs[i] = SourceVecs[i];
5601 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5602 // It probably isn't worth padding out a smaller vector just to
5603 // break it down again in a shuffle.
5607 // Since only 64-bit and 128-bit vectors are legal on ARM and
5608 // we've eliminated the other cases...
5609 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5610 "unexpected vector sizes in ReconstructShuffle");
5612 if (MaxElts[i] - MinElts[i] >= NumElts) {
5613 // Span too large for a VEXT to cope
5617 if (MinElts[i] >= NumElts) {
5618 // The extraction can just take the second half
5619 VEXTOffsets[i] = NumElts;
5620 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5622 DAG.getIntPtrConstant(NumElts, dl));
5623 } else if (MaxElts[i] < NumElts) {
5624 // The extraction can just take the first half
5626 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5628 DAG.getIntPtrConstant(0, dl));
5630 // An actual VEXT is needed
5631 VEXTOffsets[i] = MinElts[i];
5632 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5634 DAG.getIntPtrConstant(0, dl));
5635 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5637 DAG.getIntPtrConstant(NumElts, dl));
5638 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5639 DAG.getConstant(VEXTOffsets[i], dl,
5644 SmallVector<int, 8> Mask;
5646 for (unsigned i = 0; i < NumElts; ++i) {
5647 SDValue Entry = Op.getOperand(i);
5648 if (Entry.getOpcode() == ISD::UNDEF) {
5653 SDValue ExtractVec = Entry.getOperand(0);
5654 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5655 .getOperand(1))->getSExtValue();
5656 if (ExtractVec == SourceVecs[0]) {
5657 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5659 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5663 // Final check before we try to produce nonsense...
5664 if (isShuffleMaskLegal(Mask, VT))
5665 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5671 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5672 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5673 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5674 /// are assumed to be legal.
5676 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5678 if (VT.getVectorNumElements() == 4 &&
5679 (VT.is128BitVector() || VT.is64BitVector())) {
5680 unsigned PFIndexes[4];
5681 for (unsigned i = 0; i != 4; ++i) {
5685 PFIndexes[i] = M[i];
5688 // Compute the index in the perfect shuffle table.
5689 unsigned PFTableIndex =
5690 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5691 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5692 unsigned Cost = (PFEntry >> 30);
5698 bool ReverseVEXT, isV_UNDEF;
5699 unsigned Imm, WhichResult;
5701 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5702 return (EltSize >= 32 ||
5703 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5704 isVREVMask(M, VT, 64) ||
5705 isVREVMask(M, VT, 32) ||
5706 isVREVMask(M, VT, 16) ||
5707 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5708 isVTBLMask(M, VT) ||
5709 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5710 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5713 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5714 /// the specified operations to build the shuffle.
5715 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5716 SDValue RHS, SelectionDAG &DAG,
5718 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5719 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5720 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5723 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5732 OP_VUZPL, // VUZP, left result
5733 OP_VUZPR, // VUZP, right result
5734 OP_VZIPL, // VZIP, left result
5735 OP_VZIPR, // VZIP, right result
5736 OP_VTRNL, // VTRN, left result
5737 OP_VTRNR // VTRN, right result
5740 if (OpNum == OP_COPY) {
5741 if (LHSID == (1*9+2)*9+3) return LHS;
5742 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5746 SDValue OpLHS, OpRHS;
5747 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5748 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5749 EVT VT = OpLHS.getValueType();
5752 default: llvm_unreachable("Unknown shuffle opcode!");
5754 // VREV divides the vector in half and swaps within the half.
5755 if (VT.getVectorElementType() == MVT::i32 ||
5756 VT.getVectorElementType() == MVT::f32)
5757 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5758 // vrev <4 x i16> -> VREV32
5759 if (VT.getVectorElementType() == MVT::i16)
5760 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5761 // vrev <4 x i8> -> VREV16
5762 assert(VT.getVectorElementType() == MVT::i8);
5763 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5768 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5769 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5773 return DAG.getNode(ARMISD::VEXT, dl, VT,
5775 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5778 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5779 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5782 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5783 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5786 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5787 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5791 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5792 ArrayRef<int> ShuffleMask,
5793 SelectionDAG &DAG) {
5794 // Check to see if we can use the VTBL instruction.
5795 SDValue V1 = Op.getOperand(0);
5796 SDValue V2 = Op.getOperand(1);
5799 SmallVector<SDValue, 8> VTBLMask;
5800 for (ArrayRef<int>::iterator
5801 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5802 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5804 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5805 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5806 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5808 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5809 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5812 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5813 SelectionDAG &DAG) {
5815 SDValue OpLHS = Op.getOperand(0);
5816 EVT VT = OpLHS.getValueType();
5818 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5819 "Expect an v8i16/v16i8 type");
5820 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5821 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5822 // extract the first 8 bytes into the top double word and the last 8 bytes
5823 // into the bottom double word. The v8i16 case is similar.
5824 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5825 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5826 DAG.getConstant(ExtractNum, DL, MVT::i32));
5829 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5830 SDValue V1 = Op.getOperand(0);
5831 SDValue V2 = Op.getOperand(1);
5833 EVT VT = Op.getValueType();
5834 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5836 // Convert shuffles that are directly supported on NEON to target-specific
5837 // DAG nodes, instead of keeping them as shuffles and matching them again
5838 // during code selection. This is more efficient and avoids the possibility
5839 // of inconsistencies between legalization and selection.
5840 // FIXME: floating-point vectors should be canonicalized to integer vectors
5841 // of the same time so that they get CSEd properly.
5842 ArrayRef<int> ShuffleMask = SVN->getMask();
5844 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5845 if (EltSize <= 32) {
5846 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5847 int Lane = SVN->getSplatIndex();
5848 // If this is undef splat, generate it via "just" vdup, if possible.
5849 if (Lane == -1) Lane = 0;
5851 // Test if V1 is a SCALAR_TO_VECTOR.
5852 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5853 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5855 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5856 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5858 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5859 !isa<ConstantSDNode>(V1.getOperand(0))) {
5860 bool IsScalarToVector = true;
5861 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5862 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5863 IsScalarToVector = false;
5866 if (IsScalarToVector)
5867 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5869 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5870 DAG.getConstant(Lane, dl, MVT::i32));
5875 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5878 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5879 DAG.getConstant(Imm, dl, MVT::i32));
5882 if (isVREVMask(ShuffleMask, VT, 64))
5883 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5884 if (isVREVMask(ShuffleMask, VT, 32))
5885 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5886 if (isVREVMask(ShuffleMask, VT, 16))
5887 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5889 if (V2->getOpcode() == ISD::UNDEF &&
5890 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5891 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5892 DAG.getConstant(Imm, dl, MVT::i32));
5895 // Check for Neon shuffles that modify both input vectors in place.
5896 // If both results are used, i.e., if there are two shuffles with the same
5897 // source operands and with masks corresponding to both results of one of
5898 // these operations, DAG memoization will ensure that a single node is
5899 // used for both shuffles.
5900 unsigned WhichResult;
5902 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5903 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5906 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5907 .getValue(WhichResult);
5910 // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5911 // shuffles that produce a result larger than their operands with:
5912 // shuffle(concat(v1, undef), concat(v2, undef))
5914 // shuffle(concat(v1, v2), undef)
5915 // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
5917 // This is useful in the general case, but there are special cases where
5918 // native shuffles produce larger results: the two-result ops.
5920 // Look through the concat when lowering them:
5921 // shuffle(concat(v1, v2), undef)
5923 // concat(VZIP(v1, v2):0, :1)
5925 if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
5926 V2->getOpcode() == ISD::UNDEF) {
5927 SDValue SubV1 = V1->getOperand(0);
5928 SDValue SubV2 = V1->getOperand(1);
5929 EVT SubVT = SubV1.getValueType();
5931 // We expect these to have been canonicalized to -1.
5932 assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
5933 return i < (int)VT.getVectorNumElements();
5934 }) && "Unexpected shuffle index into UNDEF operand!");
5936 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5937 ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
5940 assert((WhichResult == 0) &&
5941 "In-place shuffle of concat can only have one result!");
5942 SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
5944 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
5950 // If the shuffle is not directly supported and it has 4 elements, use
5951 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5952 unsigned NumElts = VT.getVectorNumElements();
5954 unsigned PFIndexes[4];
5955 for (unsigned i = 0; i != 4; ++i) {
5956 if (ShuffleMask[i] < 0)
5959 PFIndexes[i] = ShuffleMask[i];
5962 // Compute the index in the perfect shuffle table.
5963 unsigned PFTableIndex =
5964 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5965 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5966 unsigned Cost = (PFEntry >> 30);
5969 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5972 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5973 if (EltSize >= 32) {
5974 // Do the expansion with floating-point types, since that is what the VFP
5975 // registers are defined to use, and since i64 is not legal.
5976 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5977 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5978 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5979 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5980 SmallVector<SDValue, 8> Ops;
5981 for (unsigned i = 0; i < NumElts; ++i) {
5982 if (ShuffleMask[i] < 0)
5983 Ops.push_back(DAG.getUNDEF(EltVT));
5985 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5986 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5987 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5990 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5991 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5994 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5995 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5997 if (VT == MVT::v8i8) {
5998 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5999 if (NewOp.getNode())
6006 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6007 // INSERT_VECTOR_ELT is legal only for immediate indexes.
6008 SDValue Lane = Op.getOperand(2);
6009 if (!isa<ConstantSDNode>(Lane))
6015 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6016 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6017 SDValue Lane = Op.getOperand(1);
6018 if (!isa<ConstantSDNode>(Lane))
6021 SDValue Vec = Op.getOperand(0);
6022 if (Op.getValueType() == MVT::i32 &&
6023 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6025 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6031 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6032 // The only time a CONCAT_VECTORS operation can have legal types is when
6033 // two 64-bit vectors are concatenated to a 128-bit vector.
6034 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6035 "unexpected CONCAT_VECTORS");
6037 SDValue Val = DAG.getUNDEF(MVT::v2f64);
6038 SDValue Op0 = Op.getOperand(0);
6039 SDValue Op1 = Op.getOperand(1);
6040 if (Op0.getOpcode() != ISD::UNDEF)
6041 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6042 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6043 DAG.getIntPtrConstant(0, dl));
6044 if (Op1.getOpcode() != ISD::UNDEF)
6045 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6046 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6047 DAG.getIntPtrConstant(1, dl));
6048 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6051 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6052 /// element has been zero/sign-extended, depending on the isSigned parameter,
6053 /// from an integer type half its size.
6054 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6056 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6057 EVT VT = N->getValueType(0);
6058 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6059 SDNode *BVN = N->getOperand(0).getNode();
6060 if (BVN->getValueType(0) != MVT::v4i32 ||
6061 BVN->getOpcode() != ISD::BUILD_VECTOR)
6063 unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6064 unsigned HiElt = 1 - LoElt;
6065 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6066 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6067 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6068 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6069 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6072 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6073 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6076 if (Hi0->isNullValue() && Hi1->isNullValue())
6082 if (N->getOpcode() != ISD::BUILD_VECTOR)
6085 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6086 SDNode *Elt = N->getOperand(i).getNode();
6087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6088 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6089 unsigned HalfSize = EltSize / 2;
6091 if (!isIntN(HalfSize, C->getSExtValue()))
6094 if (!isUIntN(HalfSize, C->getZExtValue()))
6105 /// isSignExtended - Check if a node is a vector value that is sign-extended
6106 /// or a constant BUILD_VECTOR with sign-extended elements.
6107 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6108 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6110 if (isExtendedBUILD_VECTOR(N, DAG, true))
6115 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6116 /// or a constant BUILD_VECTOR with zero-extended elements.
6117 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6118 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6120 if (isExtendedBUILD_VECTOR(N, DAG, false))
6125 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6126 if (OrigVT.getSizeInBits() >= 64)
6129 assert(OrigVT.isSimple() && "Expecting a simple value type");
6131 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6132 switch (OrigSimpleTy) {
6133 default: llvm_unreachable("Unexpected Vector Type");
6142 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6143 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6144 /// We insert the required extension here to get the vector to fill a D register.
6145 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6148 unsigned ExtOpcode) {
6149 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6150 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6151 // 64-bits we need to insert a new extension so that it will be 64-bits.
6152 assert(ExtTy.is128BitVector() && "Unexpected extension size");
6153 if (OrigTy.getSizeInBits() >= 64)
6156 // Must extend size to at least 64 bits to be used as an operand for VMULL.
6157 EVT NewVT = getExtensionTo64Bits(OrigTy);
6159 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6162 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6163 /// does not do any sign/zero extension. If the original vector is less
6164 /// than 64 bits, an appropriate extension will be added after the load to
6165 /// reach a total size of 64 bits. We have to add the extension separately
6166 /// because ARM does not have a sign/zero extending load for vectors.
6167 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6168 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6170 // The load already has the right type.
6171 if (ExtendedTy == LD->getMemoryVT())
6172 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6173 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6174 LD->isNonTemporal(), LD->isInvariant(),
6175 LD->getAlignment());
6177 // We need to create a zextload/sextload. We cannot just create a load
6178 // followed by a zext/zext node because LowerMUL is also run during normal
6179 // operation legalization where we can't create illegal types.
6180 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6181 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6182 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6183 LD->isNonTemporal(), LD->getAlignment());
6186 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6187 /// extending load, or BUILD_VECTOR with extended elements, return the
6188 /// unextended value. The unextended vector should be 64 bits so that it can
6189 /// be used as an operand to a VMULL instruction. If the original vector size
6190 /// before extension is less than 64 bits we add a an extension to resize
6191 /// the vector to 64 bits.
6192 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6193 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6194 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6195 N->getOperand(0)->getValueType(0),
6199 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6200 return SkipLoadExtensionForVMULL(LD, DAG);
6202 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
6203 // have been legalized as a BITCAST from v4i32.
6204 if (N->getOpcode() == ISD::BITCAST) {
6205 SDNode *BVN = N->getOperand(0).getNode();
6206 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6207 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6208 unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6209 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6210 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6212 // Construct a new BUILD_VECTOR with elements truncated to half the size.
6213 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6214 EVT VT = N->getValueType(0);
6215 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6216 unsigned NumElts = VT.getVectorNumElements();
6217 MVT TruncVT = MVT::getIntegerVT(EltSize);
6218 SmallVector<SDValue, 8> Ops;
6220 for (unsigned i = 0; i != NumElts; ++i) {
6221 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6222 const APInt &CInt = C->getAPIntValue();
6223 // Element types smaller than 32 bits are not legal, so use i32 elements.
6224 // The values are implicitly truncated so sext vs. zext doesn't matter.
6225 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6227 return DAG.getNode(ISD::BUILD_VECTOR, dl,
6228 MVT::getVectorVT(TruncVT, NumElts), Ops);
6231 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6232 unsigned Opcode = N->getOpcode();
6233 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6234 SDNode *N0 = N->getOperand(0).getNode();
6235 SDNode *N1 = N->getOperand(1).getNode();
6236 return N0->hasOneUse() && N1->hasOneUse() &&
6237 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6242 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6243 unsigned Opcode = N->getOpcode();
6244 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6245 SDNode *N0 = N->getOperand(0).getNode();
6246 SDNode *N1 = N->getOperand(1).getNode();
6247 return N0->hasOneUse() && N1->hasOneUse() &&
6248 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6253 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6254 // Multiplications are only custom-lowered for 128-bit vectors so that
6255 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6256 EVT VT = Op.getValueType();
6257 assert(VT.is128BitVector() && VT.isInteger() &&
6258 "unexpected type for custom-lowering ISD::MUL");
6259 SDNode *N0 = Op.getOperand(0).getNode();
6260 SDNode *N1 = Op.getOperand(1).getNode();
6261 unsigned NewOpc = 0;
6263 bool isN0SExt = isSignExtended(N0, DAG);
6264 bool isN1SExt = isSignExtended(N1, DAG);
6265 if (isN0SExt && isN1SExt)
6266 NewOpc = ARMISD::VMULLs;
6268 bool isN0ZExt = isZeroExtended(N0, DAG);
6269 bool isN1ZExt = isZeroExtended(N1, DAG);
6270 if (isN0ZExt && isN1ZExt)
6271 NewOpc = ARMISD::VMULLu;
6272 else if (isN1SExt || isN1ZExt) {
6273 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6274 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6275 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6276 NewOpc = ARMISD::VMULLs;
6278 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6279 NewOpc = ARMISD::VMULLu;
6281 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6283 NewOpc = ARMISD::VMULLu;
6289 if (VT == MVT::v2i64)
6290 // Fall through to expand this. It is not legal.
6293 // Other vector multiplications are legal.
6298 // Legalize to a VMULL instruction.
6301 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6303 Op0 = SkipExtensionForVMULL(N0, DAG);
6304 assert(Op0.getValueType().is64BitVector() &&
6305 Op1.getValueType().is64BitVector() &&
6306 "unexpected types for extended operands to VMULL");
6307 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6310 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6311 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6318 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6319 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6320 EVT Op1VT = Op1.getValueType();
6321 return DAG.getNode(N0->getOpcode(), DL, VT,
6322 DAG.getNode(NewOpc, DL, VT,
6323 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6324 DAG.getNode(NewOpc, DL, VT,
6325 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6329 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6331 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6332 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6333 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6334 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6335 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6336 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6337 // Get reciprocal estimate.
6338 // float4 recip = vrecpeq_f32(yf);
6339 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6340 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6342 // Because char has a smaller range than uchar, we can actually get away
6343 // without any newton steps. This requires that we use a weird bias
6344 // of 0xb000, however (again, this has been exhaustively tested).
6345 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6346 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6347 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6348 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6349 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6350 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6351 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6352 // Convert back to short.
6353 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6354 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6359 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6361 // Convert to float.
6362 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6363 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6364 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6365 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6366 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6367 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6369 // Use reciprocal estimate and one refinement step.
6370 // float4 recip = vrecpeq_f32(yf);
6371 // recip *= vrecpsq_f32(yf, recip);
6372 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6373 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6375 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6376 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6378 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6379 // Because short has a smaller range than ushort, we can actually get away
6380 // with only a single newton step. This requires that we use a weird bias
6381 // of 89, however (again, this has been exhaustively tested).
6382 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6383 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6384 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6385 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6386 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6387 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6388 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6389 // Convert back to integer and return.
6390 // return vmovn_s32(vcvt_s32_f32(result));
6391 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6392 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6396 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6397 EVT VT = Op.getValueType();
6398 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6399 "unexpected type for custom-lowering ISD::SDIV");
6402 SDValue N0 = Op.getOperand(0);
6403 SDValue N1 = Op.getOperand(1);
6406 if (VT == MVT::v8i8) {
6407 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6408 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6410 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6411 DAG.getIntPtrConstant(4, dl));
6412 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6413 DAG.getIntPtrConstant(4, dl));
6414 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6415 DAG.getIntPtrConstant(0, dl));
6416 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6417 DAG.getIntPtrConstant(0, dl));
6419 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6420 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6422 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6423 N0 = LowerCONCAT_VECTORS(N0, DAG);
6425 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6428 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6431 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6432 EVT VT = Op.getValueType();
6433 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6434 "unexpected type for custom-lowering ISD::UDIV");
6437 SDValue N0 = Op.getOperand(0);
6438 SDValue N1 = Op.getOperand(1);
6441 if (VT == MVT::v8i8) {
6442 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6443 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6445 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6446 DAG.getIntPtrConstant(4, dl));
6447 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6448 DAG.getIntPtrConstant(4, dl));
6449 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6450 DAG.getIntPtrConstant(0, dl));
6451 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6452 DAG.getIntPtrConstant(0, dl));
6454 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6455 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6457 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6458 N0 = LowerCONCAT_VECTORS(N0, DAG);
6460 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6461 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6467 // v4i16 sdiv ... Convert to float.
6468 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6469 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6470 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6471 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6472 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6473 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6475 // Use reciprocal estimate and two refinement steps.
6476 // float4 recip = vrecpeq_f32(yf);
6477 // recip *= vrecpsq_f32(yf, recip);
6478 // recip *= vrecpsq_f32(yf, recip);
6479 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6480 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6482 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6483 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6485 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6486 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6487 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6489 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6490 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6491 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6492 // and that it will never cause us to return an answer too large).
6493 // float4 result = as_float4(as_int4(xf*recip) + 2);
6494 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6495 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6496 N1 = DAG.getConstant(2, dl, MVT::i32);
6497 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6498 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6499 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6500 // Convert back to integer and return.
6501 // return vmovn_u32(vcvt_s32_f32(result));
6502 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6503 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6507 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6508 EVT VT = Op.getNode()->getValueType(0);
6509 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6512 bool ExtraOp = false;
6513 switch (Op.getOpcode()) {
6514 default: llvm_unreachable("Invalid code");
6515 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6516 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6517 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6518 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6522 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6524 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6525 Op.getOperand(1), Op.getOperand(2));
6528 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6529 assert(Subtarget->isTargetDarwin());
6531 // For iOS, we want to call an alternative entry point: __sincos_stret,
6532 // return values are passed via sret.
6534 SDValue Arg = Op.getOperand(0);
6535 EVT ArgVT = Arg.getValueType();
6536 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6537 auto PtrVT = getPointerTy(DAG.getDataLayout());
6539 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6541 // Pair of floats / doubles used to pass the result.
6542 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6544 // Create stack object for sret.
6545 auto &DL = DAG.getDataLayout();
6546 const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6547 const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6548 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6549 SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6555 Entry.Ty = RetTy->getPointerTo();
6556 Entry.isSExt = false;
6557 Entry.isZExt = false;
6558 Entry.isSRet = true;
6559 Args.push_back(Entry);
6563 Entry.isSExt = false;
6564 Entry.isZExt = false;
6565 Args.push_back(Entry);
6567 const char *LibcallName = (ArgVT == MVT::f64)
6568 ? "__sincos_stret" : "__sincosf_stret";
6569 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6571 TargetLowering::CallLoweringInfo CLI(DAG);
6572 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6573 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6575 .setDiscardResult();
6577 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6579 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6580 MachinePointerInfo(), false, false, false, 0);
6582 // Address of cos field.
6583 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6584 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6585 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6586 MachinePointerInfo(), false, false, false, 0);
6588 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6589 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6590 LoadSin.getValue(0), LoadCos.getValue(0));
6593 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6594 // Monotonic load/store is legal for all targets
6595 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6598 // Acquire/Release load/store is not legal for targets without a
6599 // dmb or equivalent available.
6603 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6604 SmallVectorImpl<SDValue> &Results,
6606 const ARMSubtarget *Subtarget) {
6608 SDValue Cycles32, OutChain;
6610 if (Subtarget->hasPerfMon()) {
6611 // Under Power Management extensions, the cycle-count is:
6612 // mrc p15, #0, <Rt>, c9, c13, #0
6613 SDValue Ops[] = { N->getOperand(0), // Chain
6614 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6615 DAG.getConstant(15, DL, MVT::i32),
6616 DAG.getConstant(0, DL, MVT::i32),
6617 DAG.getConstant(9, DL, MVT::i32),
6618 DAG.getConstant(13, DL, MVT::i32),
6619 DAG.getConstant(0, DL, MVT::i32)
6622 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6623 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6624 OutChain = Cycles32.getValue(1);
6626 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6627 // there are older ARM CPUs that have implementation-specific ways of
6628 // obtaining this information (FIXME!).
6629 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6630 OutChain = DAG.getEntryNode();
6634 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6635 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6636 Results.push_back(Cycles64);
6637 Results.push_back(OutChain);
6640 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6641 switch (Op.getOpcode()) {
6642 default: llvm_unreachable("Don't know how to custom lower this!");
6643 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6644 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6645 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6646 case ISD::GlobalAddress:
6647 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6648 default: llvm_unreachable("unknown object format");
6650 return LowerGlobalAddressWindows(Op, DAG);
6652 return LowerGlobalAddressELF(Op, DAG);
6654 return LowerGlobalAddressDarwin(Op, DAG);
6656 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6657 case ISD::SELECT: return LowerSELECT(Op, DAG);
6658 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6659 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6660 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6661 case ISD::VASTART: return LowerVASTART(Op, DAG);
6662 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6663 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6664 case ISD::SINT_TO_FP:
6665 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6666 case ISD::FP_TO_SINT:
6667 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6668 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6669 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6670 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6671 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6672 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6673 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6674 case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6675 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6677 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6680 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6681 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6682 case ISD::SRL_PARTS:
6683 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6685 case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6686 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6687 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6688 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6689 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6690 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6691 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6692 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6693 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6694 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6695 case ISD::MUL: return LowerMUL(Op, DAG);
6696 case ISD::SDIV: return LowerSDIV(Op, DAG);
6697 case ISD::UDIV: return LowerUDIV(Op, DAG);
6701 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6706 return LowerXALUO(Op, DAG);
6707 case ISD::ATOMIC_LOAD:
6708 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6709 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6711 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6712 case ISD::DYNAMIC_STACKALLOC:
6713 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6714 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6715 llvm_unreachable("Don't know how to custom lower this!");
6716 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6717 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6721 /// ReplaceNodeResults - Replace the results of node with an illegal result
6722 /// type with new values built out of custom code.
6723 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6724 SmallVectorImpl<SDValue>&Results,
6725 SelectionDAG &DAG) const {
6727 switch (N->getOpcode()) {
6729 llvm_unreachable("Don't know how to custom expand this!");
6730 case ISD::READ_REGISTER:
6731 ExpandREAD_REGISTER(N, Results, DAG);
6734 Res = ExpandBITCAST(N, DAG);
6738 Res = Expand64BitShift(N, DAG, Subtarget);
6740 case ISD::READCYCLECOUNTER:
6741 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6745 Results.push_back(Res);
6748 //===----------------------------------------------------------------------===//
6749 // ARM Scheduler Hooks
6750 //===----------------------------------------------------------------------===//
6752 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6753 /// registers the function context.
6754 void ARMTargetLowering::
6755 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6756 MachineBasicBlock *DispatchBB, int FI) const {
6757 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6758 DebugLoc dl = MI->getDebugLoc();
6759 MachineFunction *MF = MBB->getParent();
6760 MachineRegisterInfo *MRI = &MF->getRegInfo();
6761 MachineConstantPool *MCP = MF->getConstantPool();
6762 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6763 const Function *F = MF->getFunction();
6765 bool isThumb = Subtarget->isThumb();
6766 bool isThumb2 = Subtarget->isThumb2();
6768 unsigned PCLabelId = AFI->createPICLabelUId();
6769 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6770 ARMConstantPoolValue *CPV =
6771 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6772 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6774 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6775 : &ARM::GPRRegClass;
6777 // Grab constant pool and fixed stack memory operands.
6778 MachineMemOperand *CPMMO =
6779 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6780 MachineMemOperand::MOLoad, 4, 4);
6782 MachineMemOperand *FIMMOSt =
6783 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6784 MachineMemOperand::MOStore, 4, 4);
6786 // Load the address of the dispatch MBB into the jump buffer.
6788 // Incoming value: jbuf
6789 // ldr.n r5, LCPI1_1
6792 // str r5, [$jbuf, #+4] ; &jbuf[1]
6793 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6794 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6795 .addConstantPoolIndex(CPI)
6796 .addMemOperand(CPMMO));
6797 // Set the low bit because of thumb mode.
6798 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6800 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6801 .addReg(NewVReg1, RegState::Kill)
6803 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6804 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6805 .addReg(NewVReg2, RegState::Kill)
6807 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6808 .addReg(NewVReg3, RegState::Kill)
6810 .addImm(36) // &jbuf[1] :: pc
6811 .addMemOperand(FIMMOSt));
6812 } else if (isThumb) {
6813 // Incoming value: jbuf
6814 // ldr.n r1, LCPI1_4
6818 // add r2, $jbuf, #+4 ; &jbuf[1]
6820 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6821 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6822 .addConstantPoolIndex(CPI)
6823 .addMemOperand(CPMMO));
6824 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6825 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6826 .addReg(NewVReg1, RegState::Kill)
6828 // Set the low bit because of thumb mode.
6829 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6830 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6831 .addReg(ARM::CPSR, RegState::Define)
6833 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6834 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6835 .addReg(ARM::CPSR, RegState::Define)
6836 .addReg(NewVReg2, RegState::Kill)
6837 .addReg(NewVReg3, RegState::Kill));
6838 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6839 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6841 .addImm(36); // &jbuf[1] :: pc
6842 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6843 .addReg(NewVReg4, RegState::Kill)
6844 .addReg(NewVReg5, RegState::Kill)
6846 .addMemOperand(FIMMOSt));
6848 // Incoming value: jbuf
6851 // str r1, [$jbuf, #+4] ; &jbuf[1]
6852 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6853 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6854 .addConstantPoolIndex(CPI)
6856 .addMemOperand(CPMMO));
6857 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6858 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6859 .addReg(NewVReg1, RegState::Kill)
6860 .addImm(PCLabelId));
6861 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6862 .addReg(NewVReg2, RegState::Kill)
6864 .addImm(36) // &jbuf[1] :: pc
6865 .addMemOperand(FIMMOSt));
6869 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6870 MachineBasicBlock *MBB) const {
6871 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6872 DebugLoc dl = MI->getDebugLoc();
6873 MachineFunction *MF = MBB->getParent();
6874 MachineRegisterInfo *MRI = &MF->getRegInfo();
6875 MachineFrameInfo *MFI = MF->getFrameInfo();
6876 int FI = MFI->getFunctionContextIndex();
6878 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6879 : &ARM::GPRnopcRegClass;
6881 // Get a mapping of the call site numbers to all of the landing pads they're
6883 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6884 unsigned MaxCSNum = 0;
6885 MachineModuleInfo &MMI = MF->getMMI();
6886 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6888 if (!BB->isLandingPad()) continue;
6890 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6892 for (MachineBasicBlock::iterator
6893 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6894 if (!II->isEHLabel()) continue;
6896 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6897 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6899 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6900 for (SmallVectorImpl<unsigned>::iterator
6901 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6902 CSI != CSE; ++CSI) {
6903 CallSiteNumToLPad[*CSI].push_back(BB);
6904 MaxCSNum = std::max(MaxCSNum, *CSI);
6910 // Get an ordered list of the machine basic blocks for the jump table.
6911 std::vector<MachineBasicBlock*> LPadList;
6912 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6913 LPadList.reserve(CallSiteNumToLPad.size());
6914 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6915 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6916 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6917 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6918 LPadList.push_back(*II);
6919 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6923 assert(!LPadList.empty() &&
6924 "No landing pad destinations for the dispatch jump table!");
6926 // Create the jump table and associated information.
6927 MachineJumpTableInfo *JTI =
6928 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6929 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6930 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6932 // Create the MBBs for the dispatch code.
6934 // Shove the dispatch's address into the return slot in the function context.
6935 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6936 DispatchBB->setIsLandingPad();
6938 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6939 unsigned trap_opcode;
6940 if (Subtarget->isThumb())
6941 trap_opcode = ARM::tTRAP;
6943 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6945 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6946 DispatchBB->addSuccessor(TrapBB);
6948 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6949 DispatchBB->addSuccessor(DispContBB);
6952 MF->insert(MF->end(), DispatchBB);
6953 MF->insert(MF->end(), DispContBB);
6954 MF->insert(MF->end(), TrapBB);
6956 // Insert code into the entry block that creates and registers the function
6958 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6960 MachineMemOperand *FIMMOLd =
6961 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6962 MachineMemOperand::MOLoad |
6963 MachineMemOperand::MOVolatile, 4, 4);
6965 MachineInstrBuilder MIB;
6966 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6968 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6969 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6971 // Add a register mask with no preserved registers. This results in all
6972 // registers being marked as clobbered.
6973 MIB.addRegMask(RI.getNoPreservedMask());
6975 unsigned NumLPads = LPadList.size();
6976 if (Subtarget->isThumb2()) {
6977 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6978 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6981 .addMemOperand(FIMMOLd));
6983 if (NumLPads < 256) {
6984 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6986 .addImm(LPadList.size()));
6988 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6989 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6990 .addImm(NumLPads & 0xFFFF));
6992 unsigned VReg2 = VReg1;
6993 if ((NumLPads & 0xFFFF0000) != 0) {
6994 VReg2 = MRI->createVirtualRegister(TRC);
6995 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6997 .addImm(NumLPads >> 16));
7000 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7005 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7010 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7011 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7012 .addJumpTableIndex(MJTI));
7014 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7017 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7018 .addReg(NewVReg3, RegState::Kill)
7020 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7022 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7023 .addReg(NewVReg4, RegState::Kill)
7025 .addJumpTableIndex(MJTI);
7026 } else if (Subtarget->isThumb()) {
7027 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7028 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7031 .addMemOperand(FIMMOLd));
7033 if (NumLPads < 256) {
7034 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7038 MachineConstantPool *ConstantPool = MF->getConstantPool();
7039 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7040 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7042 // MachineConstantPool wants an explicit alignment.
7043 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7045 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7046 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7048 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7049 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7050 .addReg(VReg1, RegState::Define)
7051 .addConstantPoolIndex(Idx));
7052 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7057 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7062 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7063 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7064 .addReg(ARM::CPSR, RegState::Define)
7068 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7069 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7070 .addJumpTableIndex(MJTI));
7072 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7073 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7074 .addReg(ARM::CPSR, RegState::Define)
7075 .addReg(NewVReg2, RegState::Kill)
7078 MachineMemOperand *JTMMOLd =
7079 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7080 MachineMemOperand::MOLoad, 4, 4);
7082 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7083 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7084 .addReg(NewVReg4, RegState::Kill)
7086 .addMemOperand(JTMMOLd));
7088 unsigned NewVReg6 = NewVReg5;
7089 if (RelocM == Reloc::PIC_) {
7090 NewVReg6 = MRI->createVirtualRegister(TRC);
7091 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7092 .addReg(ARM::CPSR, RegState::Define)
7093 .addReg(NewVReg5, RegState::Kill)
7097 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7098 .addReg(NewVReg6, RegState::Kill)
7099 .addJumpTableIndex(MJTI);
7101 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7102 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7105 .addMemOperand(FIMMOLd));
7107 if (NumLPads < 256) {
7108 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7111 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7112 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7113 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7114 .addImm(NumLPads & 0xFFFF));
7116 unsigned VReg2 = VReg1;
7117 if ((NumLPads & 0xFFFF0000) != 0) {
7118 VReg2 = MRI->createVirtualRegister(TRC);
7119 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7121 .addImm(NumLPads >> 16));
7124 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7128 MachineConstantPool *ConstantPool = MF->getConstantPool();
7129 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7130 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7132 // MachineConstantPool wants an explicit alignment.
7133 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7135 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7136 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7138 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7139 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7140 .addReg(VReg1, RegState::Define)
7141 .addConstantPoolIndex(Idx)
7143 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7145 .addReg(VReg1, RegState::Kill));
7148 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7153 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7155 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7157 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7158 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7159 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7160 .addJumpTableIndex(MJTI));
7162 MachineMemOperand *JTMMOLd =
7163 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7164 MachineMemOperand::MOLoad, 4, 4);
7165 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7167 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7168 .addReg(NewVReg3, RegState::Kill)
7171 .addMemOperand(JTMMOLd));
7173 if (RelocM == Reloc::PIC_) {
7174 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7175 .addReg(NewVReg5, RegState::Kill)
7177 .addJumpTableIndex(MJTI);
7179 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7180 .addReg(NewVReg5, RegState::Kill)
7181 .addJumpTableIndex(MJTI);
7185 // Add the jump table entries as successors to the MBB.
7186 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7187 for (std::vector<MachineBasicBlock*>::iterator
7188 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7189 MachineBasicBlock *CurMBB = *I;
7190 if (SeenMBBs.insert(CurMBB).second)
7191 DispContBB->addSuccessor(CurMBB);
7194 // N.B. the order the invoke BBs are processed in doesn't matter here.
7195 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7196 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7197 for (MachineBasicBlock *BB : InvokeBBs) {
7199 // Remove the landing pad successor from the invoke block and replace it
7200 // with the new dispatch block.
7201 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7203 while (!Successors.empty()) {
7204 MachineBasicBlock *SMBB = Successors.pop_back_val();
7205 if (SMBB->isLandingPad()) {
7206 BB->removeSuccessor(SMBB);
7207 MBBLPads.push_back(SMBB);
7211 BB->addSuccessor(DispatchBB);
7213 // Find the invoke call and mark all of the callee-saved registers as
7214 // 'implicit defined' so that they're spilled. This prevents code from
7215 // moving instructions to before the EH block, where they will never be
7217 for (MachineBasicBlock::reverse_iterator
7218 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7219 if (!II->isCall()) continue;
7221 DenseMap<unsigned, bool> DefRegs;
7222 for (MachineInstr::mop_iterator
7223 OI = II->operands_begin(), OE = II->operands_end();
7225 if (!OI->isReg()) continue;
7226 DefRegs[OI->getReg()] = true;
7229 MachineInstrBuilder MIB(*MF, &*II);
7231 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7232 unsigned Reg = SavedRegs[i];
7233 if (Subtarget->isThumb2() &&
7234 !ARM::tGPRRegClass.contains(Reg) &&
7235 !ARM::hGPRRegClass.contains(Reg))
7237 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7239 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7242 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7249 // Mark all former landing pads as non-landing pads. The dispatch is the only
7251 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7252 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7253 (*I)->setIsLandingPad(false);
7255 // The instruction is gone now.
7256 MI->eraseFromParent();
7260 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7261 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7262 E = MBB->succ_end(); I != E; ++I)
7265 llvm_unreachable("Expecting a BB with two successors!");
7268 /// Return the load opcode for a given load size. If load size >= 8,
7269 /// neon opcode will be returned.
7270 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7272 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7273 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7275 return LdSize == 4 ? ARM::tLDRi
7276 : LdSize == 2 ? ARM::tLDRHi
7277 : LdSize == 1 ? ARM::tLDRBi : 0;
7279 return LdSize == 4 ? ARM::t2LDR_POST
7280 : LdSize == 2 ? ARM::t2LDRH_POST
7281 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7282 return LdSize == 4 ? ARM::LDR_POST_IMM
7283 : LdSize == 2 ? ARM::LDRH_POST
7284 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7287 /// Return the store opcode for a given store size. If store size >= 8,
7288 /// neon opcode will be returned.
7289 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7291 return StSize == 16 ? ARM::VST1q32wb_fixed
7292 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7294 return StSize == 4 ? ARM::tSTRi
7295 : StSize == 2 ? ARM::tSTRHi
7296 : StSize == 1 ? ARM::tSTRBi : 0;
7298 return StSize == 4 ? ARM::t2STR_POST
7299 : StSize == 2 ? ARM::t2STRH_POST
7300 : StSize == 1 ? ARM::t2STRB_POST : 0;
7301 return StSize == 4 ? ARM::STR_POST_IMM
7302 : StSize == 2 ? ARM::STRH_POST
7303 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7306 /// Emit a post-increment load operation with given size. The instructions
7307 /// will be added to BB at Pos.
7308 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7309 const TargetInstrInfo *TII, DebugLoc dl,
7310 unsigned LdSize, unsigned Data, unsigned AddrIn,
7311 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7312 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7313 assert(LdOpc != 0 && "Should have a load opcode");
7315 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7316 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7318 } else if (IsThumb1) {
7319 // load + update AddrIn
7320 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7321 .addReg(AddrIn).addImm(0));
7322 MachineInstrBuilder MIB =
7323 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7324 MIB = AddDefaultT1CC(MIB);
7325 MIB.addReg(AddrIn).addImm(LdSize);
7326 AddDefaultPred(MIB);
7327 } else if (IsThumb2) {
7328 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7329 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7332 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7333 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7334 .addReg(0).addImm(LdSize));
7338 /// Emit a post-increment store operation with given size. The instructions
7339 /// will be added to BB at Pos.
7340 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7341 const TargetInstrInfo *TII, DebugLoc dl,
7342 unsigned StSize, unsigned Data, unsigned AddrIn,
7343 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7344 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7345 assert(StOpc != 0 && "Should have a store opcode");
7347 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7348 .addReg(AddrIn).addImm(0).addReg(Data));
7349 } else if (IsThumb1) {
7350 // store + update AddrIn
7351 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7352 .addReg(AddrIn).addImm(0));
7353 MachineInstrBuilder MIB =
7354 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7355 MIB = AddDefaultT1CC(MIB);
7356 MIB.addReg(AddrIn).addImm(StSize);
7357 AddDefaultPred(MIB);
7358 } else if (IsThumb2) {
7359 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7360 .addReg(Data).addReg(AddrIn).addImm(StSize));
7362 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7363 .addReg(Data).addReg(AddrIn).addReg(0)
7369 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7370 MachineBasicBlock *BB) const {
7371 // This pseudo instruction has 3 operands: dst, src, size
7372 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7373 // Otherwise, we will generate unrolled scalar copies.
7374 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7375 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7376 MachineFunction::iterator It = BB;
7379 unsigned dest = MI->getOperand(0).getReg();
7380 unsigned src = MI->getOperand(1).getReg();
7381 unsigned SizeVal = MI->getOperand(2).getImm();
7382 unsigned Align = MI->getOperand(3).getImm();
7383 DebugLoc dl = MI->getDebugLoc();
7385 MachineFunction *MF = BB->getParent();
7386 MachineRegisterInfo &MRI = MF->getRegInfo();
7387 unsigned UnitSize = 0;
7388 const TargetRegisterClass *TRC = nullptr;
7389 const TargetRegisterClass *VecTRC = nullptr;
7391 bool IsThumb1 = Subtarget->isThumb1Only();
7392 bool IsThumb2 = Subtarget->isThumb2();
7396 } else if (Align & 2) {
7399 // Check whether we can use NEON instructions.
7400 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7401 Subtarget->hasNEON()) {
7402 if ((Align % 16 == 0) && SizeVal >= 16)
7404 else if ((Align % 8 == 0) && SizeVal >= 8)
7407 // Can't use NEON instructions.
7412 // Select the correct opcode and register class for unit size load/store
7413 bool IsNeon = UnitSize >= 8;
7414 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7416 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7417 : UnitSize == 8 ? &ARM::DPRRegClass
7420 unsigned BytesLeft = SizeVal % UnitSize;
7421 unsigned LoopSize = SizeVal - BytesLeft;
7423 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7424 // Use LDR and STR to copy.
7425 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7426 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7427 unsigned srcIn = src;
7428 unsigned destIn = dest;
7429 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7430 unsigned srcOut = MRI.createVirtualRegister(TRC);
7431 unsigned destOut = MRI.createVirtualRegister(TRC);
7432 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7433 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7434 IsThumb1, IsThumb2);
7435 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7436 IsThumb1, IsThumb2);
7441 // Handle the leftover bytes with LDRB and STRB.
7442 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7443 // [destOut] = STRB_POST(scratch, destIn, 1)
7444 for (unsigned i = 0; i < BytesLeft; i++) {
7445 unsigned srcOut = MRI.createVirtualRegister(TRC);
7446 unsigned destOut = MRI.createVirtualRegister(TRC);
7447 unsigned scratch = MRI.createVirtualRegister(TRC);
7448 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7449 IsThumb1, IsThumb2);
7450 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7451 IsThumb1, IsThumb2);
7455 MI->eraseFromParent(); // The instruction is gone now.
7459 // Expand the pseudo op to a loop.
7462 // movw varEnd, # --> with thumb2
7464 // ldrcp varEnd, idx --> without thumb2
7465 // fallthrough --> loopMBB
7467 // PHI varPhi, varEnd, varLoop
7468 // PHI srcPhi, src, srcLoop
7469 // PHI destPhi, dst, destLoop
7470 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7471 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7472 // subs varLoop, varPhi, #UnitSize
7474 // fallthrough --> exitMBB
7476 // epilogue to handle left-over bytes
7477 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7478 // [destOut] = STRB_POST(scratch, destLoop, 1)
7479 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7480 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7481 MF->insert(It, loopMBB);
7482 MF->insert(It, exitMBB);
7484 // Transfer the remainder of BB and its successor edges to exitMBB.
7485 exitMBB->splice(exitMBB->begin(), BB,
7486 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7487 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7489 // Load an immediate to varEnd.
7490 unsigned varEnd = MRI.createVirtualRegister(TRC);
7491 if (Subtarget->useMovt(*MF)) {
7492 unsigned Vtmp = varEnd;
7493 if ((LoopSize & 0xFFFF0000) != 0)
7494 Vtmp = MRI.createVirtualRegister(TRC);
7495 AddDefaultPred(BuildMI(BB, dl,
7496 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7497 Vtmp).addImm(LoopSize & 0xFFFF));
7499 if ((LoopSize & 0xFFFF0000) != 0)
7500 AddDefaultPred(BuildMI(BB, dl,
7501 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7504 .addImm(LoopSize >> 16));
7506 MachineConstantPool *ConstantPool = MF->getConstantPool();
7507 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7508 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7510 // MachineConstantPool wants an explicit alignment.
7511 unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7513 Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7514 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7517 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7518 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7520 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7521 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7523 BB->addSuccessor(loopMBB);
7525 // Generate the loop body:
7526 // varPhi = PHI(varLoop, varEnd)
7527 // srcPhi = PHI(srcLoop, src)
7528 // destPhi = PHI(destLoop, dst)
7529 MachineBasicBlock *entryBB = BB;
7531 unsigned varLoop = MRI.createVirtualRegister(TRC);
7532 unsigned varPhi = MRI.createVirtualRegister(TRC);
7533 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7534 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7535 unsigned destLoop = MRI.createVirtualRegister(TRC);
7536 unsigned destPhi = MRI.createVirtualRegister(TRC);
7538 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7539 .addReg(varLoop).addMBB(loopMBB)
7540 .addReg(varEnd).addMBB(entryBB);
7541 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7542 .addReg(srcLoop).addMBB(loopMBB)
7543 .addReg(src).addMBB(entryBB);
7544 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7545 .addReg(destLoop).addMBB(loopMBB)
7546 .addReg(dest).addMBB(entryBB);
7548 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7549 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7550 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7551 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7552 IsThumb1, IsThumb2);
7553 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7554 IsThumb1, IsThumb2);
7556 // Decrement loop variable by UnitSize.
7558 MachineInstrBuilder MIB =
7559 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7560 MIB = AddDefaultT1CC(MIB);
7561 MIB.addReg(varPhi).addImm(UnitSize);
7562 AddDefaultPred(MIB);
7564 MachineInstrBuilder MIB =
7565 BuildMI(*BB, BB->end(), dl,
7566 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7567 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7568 MIB->getOperand(5).setReg(ARM::CPSR);
7569 MIB->getOperand(5).setIsDef(true);
7571 BuildMI(*BB, BB->end(), dl,
7572 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7573 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7575 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7576 BB->addSuccessor(loopMBB);
7577 BB->addSuccessor(exitMBB);
7579 // Add epilogue to handle BytesLeft.
7581 MachineInstr *StartOfExit = exitMBB->begin();
7583 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7584 // [destOut] = STRB_POST(scratch, destLoop, 1)
7585 unsigned srcIn = srcLoop;
7586 unsigned destIn = destLoop;
7587 for (unsigned i = 0; i < BytesLeft; i++) {
7588 unsigned srcOut = MRI.createVirtualRegister(TRC);
7589 unsigned destOut = MRI.createVirtualRegister(TRC);
7590 unsigned scratch = MRI.createVirtualRegister(TRC);
7591 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7592 IsThumb1, IsThumb2);
7593 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7594 IsThumb1, IsThumb2);
7599 MI->eraseFromParent(); // The instruction is gone now.
7604 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7605 MachineBasicBlock *MBB) const {
7606 const TargetMachine &TM = getTargetMachine();
7607 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7608 DebugLoc DL = MI->getDebugLoc();
7610 assert(Subtarget->isTargetWindows() &&
7611 "__chkstk is only supported on Windows");
7612 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7614 // __chkstk takes the number of words to allocate on the stack in R4, and
7615 // returns the stack adjustment in number of bytes in R4. This will not
7616 // clober any other registers (other than the obvious lr).
7618 // Although, technically, IP should be considered a register which may be
7619 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7620 // thumb-2 environment, so there is no interworking required. As a result, we
7621 // do not expect a veneer to be emitted by the linker, clobbering IP.
7623 // Each module receives its own copy of __chkstk, so no import thunk is
7624 // required, again, ensuring that IP is not clobbered.
7626 // Finally, although some linkers may theoretically provide a trampoline for
7627 // out of range calls (which is quite common due to a 32M range limitation of
7628 // branches for Thumb), we can generate the long-call version via
7629 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7632 switch (TM.getCodeModel()) {
7633 case CodeModel::Small:
7634 case CodeModel::Medium:
7635 case CodeModel::Default:
7636 case CodeModel::Kernel:
7637 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7638 .addImm((unsigned)ARMCC::AL).addReg(0)
7639 .addExternalSymbol("__chkstk")
7640 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7641 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7642 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7644 case CodeModel::Large:
7645 case CodeModel::JITDefault: {
7646 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7647 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7649 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7650 .addExternalSymbol("__chkstk");
7651 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7652 .addImm((unsigned)ARMCC::AL).addReg(0)
7653 .addReg(Reg, RegState::Kill)
7654 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7655 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7656 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7661 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7663 .addReg(ARM::SP).addReg(ARM::R4)));
7665 MI->eraseFromParent();
7670 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7671 MachineBasicBlock *BB) const {
7672 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7673 DebugLoc dl = MI->getDebugLoc();
7674 bool isThumb2 = Subtarget->isThumb2();
7675 switch (MI->getOpcode()) {
7678 llvm_unreachable("Unexpected instr type to insert");
7680 // The Thumb2 pre-indexed stores have the same MI operands, they just
7681 // define them differently in the .td files from the isel patterns, so
7682 // they need pseudos.
7683 case ARM::t2STR_preidx:
7684 MI->setDesc(TII->get(ARM::t2STR_PRE));
7686 case ARM::t2STRB_preidx:
7687 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7689 case ARM::t2STRH_preidx:
7690 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7693 case ARM::STRi_preidx:
7694 case ARM::STRBi_preidx: {
7695 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7696 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7697 // Decode the offset.
7698 unsigned Offset = MI->getOperand(4).getImm();
7699 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7700 Offset = ARM_AM::getAM2Offset(Offset);
7704 MachineMemOperand *MMO = *MI->memoperands_begin();
7705 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7706 .addOperand(MI->getOperand(0)) // Rn_wb
7707 .addOperand(MI->getOperand(1)) // Rt
7708 .addOperand(MI->getOperand(2)) // Rn
7709 .addImm(Offset) // offset (skip GPR==zero_reg)
7710 .addOperand(MI->getOperand(5)) // pred
7711 .addOperand(MI->getOperand(6))
7712 .addMemOperand(MMO);
7713 MI->eraseFromParent();
7716 case ARM::STRr_preidx:
7717 case ARM::STRBr_preidx:
7718 case ARM::STRH_preidx: {
7720 switch (MI->getOpcode()) {
7721 default: llvm_unreachable("unexpected opcode!");
7722 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7723 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7724 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7726 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7727 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7728 MIB.addOperand(MI->getOperand(i));
7729 MI->eraseFromParent();
7733 case ARM::tMOVCCr_pseudo: {
7734 // To "insert" a SELECT_CC instruction, we actually have to insert the
7735 // diamond control-flow pattern. The incoming instruction knows the
7736 // destination vreg to set, the condition code register to branch on, the
7737 // true/false values to select between, and a branch opcode to use.
7738 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7739 MachineFunction::iterator It = BB;
7745 // cmpTY ccX, r1, r2
7747 // fallthrough --> copy0MBB
7748 MachineBasicBlock *thisMBB = BB;
7749 MachineFunction *F = BB->getParent();
7750 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7751 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7752 F->insert(It, copy0MBB);
7753 F->insert(It, sinkMBB);
7755 // Transfer the remainder of BB and its successor edges to sinkMBB.
7756 sinkMBB->splice(sinkMBB->begin(), BB,
7757 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7758 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7760 BB->addSuccessor(copy0MBB);
7761 BB->addSuccessor(sinkMBB);
7763 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7764 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7767 // %FalseValue = ...
7768 // # fallthrough to sinkMBB
7771 // Update machine-CFG edges
7772 BB->addSuccessor(sinkMBB);
7775 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7778 BuildMI(*BB, BB->begin(), dl,
7779 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7780 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7781 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7783 MI->eraseFromParent(); // The pseudo instruction is gone now.
7788 case ARM::BCCZi64: {
7789 // If there is an unconditional branch to the other successor, remove it.
7790 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7792 // Compare both parts that make up the double comparison separately for
7794 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7796 unsigned LHS1 = MI->getOperand(1).getReg();
7797 unsigned LHS2 = MI->getOperand(2).getReg();
7799 AddDefaultPred(BuildMI(BB, dl,
7800 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7801 .addReg(LHS1).addImm(0));
7802 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7803 .addReg(LHS2).addImm(0)
7804 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7806 unsigned RHS1 = MI->getOperand(3).getReg();
7807 unsigned RHS2 = MI->getOperand(4).getReg();
7808 AddDefaultPred(BuildMI(BB, dl,
7809 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7810 .addReg(LHS1).addReg(RHS1));
7811 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7812 .addReg(LHS2).addReg(RHS2)
7813 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7816 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7817 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7818 if (MI->getOperand(0).getImm() == ARMCC::NE)
7819 std::swap(destMBB, exitMBB);
7821 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7822 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7824 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7826 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7828 MI->eraseFromParent(); // The pseudo instruction is gone now.
7832 case ARM::Int_eh_sjlj_setjmp:
7833 case ARM::Int_eh_sjlj_setjmp_nofp:
7834 case ARM::tInt_eh_sjlj_setjmp:
7835 case ARM::t2Int_eh_sjlj_setjmp:
7836 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7839 case ARM::Int_eh_sjlj_setup_dispatch:
7840 EmitSjLjDispatchBlock(MI, BB);
7845 // To insert an ABS instruction, we have to insert the
7846 // diamond control-flow pattern. The incoming instruction knows the
7847 // source vreg to test against 0, the destination vreg to set,
7848 // the condition code register to branch on, the
7849 // true/false values to select between, and a branch opcode to use.
7854 // BCC (branch to SinkBB if V0 >= 0)
7855 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7856 // SinkBB: V1 = PHI(V2, V3)
7857 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7858 MachineFunction::iterator BBI = BB;
7860 MachineFunction *Fn = BB->getParent();
7861 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7862 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7863 Fn->insert(BBI, RSBBB);
7864 Fn->insert(BBI, SinkBB);
7866 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7867 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7868 bool ABSSrcKIll = MI->getOperand(1).isKill();
7869 bool isThumb2 = Subtarget->isThumb2();
7870 MachineRegisterInfo &MRI = Fn->getRegInfo();
7871 // In Thumb mode S must not be specified if source register is the SP or
7872 // PC and if destination register is the SP, so restrict register class
7873 unsigned NewRsbDstReg =
7874 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7876 // Transfer the remainder of BB and its successor edges to sinkMBB.
7877 SinkBB->splice(SinkBB->begin(), BB,
7878 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7879 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7881 BB->addSuccessor(RSBBB);
7882 BB->addSuccessor(SinkBB);
7884 // fall through to SinkMBB
7885 RSBBB->addSuccessor(SinkBB);
7887 // insert a cmp at the end of BB
7888 AddDefaultPred(BuildMI(BB, dl,
7889 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7890 .addReg(ABSSrcReg).addImm(0));
7892 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7894 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7895 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7897 // insert rsbri in RSBBB
7898 // Note: BCC and rsbri will be converted into predicated rsbmi
7899 // by if-conversion pass
7900 BuildMI(*RSBBB, RSBBB->begin(), dl,
7901 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7902 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7903 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7905 // insert PHI in SinkBB,
7906 // reuse ABSDstReg to not change uses of ABS instruction
7907 BuildMI(*SinkBB, SinkBB->begin(), dl,
7908 TII->get(ARM::PHI), ABSDstReg)
7909 .addReg(NewRsbDstReg).addMBB(RSBBB)
7910 .addReg(ABSSrcReg).addMBB(BB);
7912 // remove ABS instruction
7913 MI->eraseFromParent();
7915 // return last added BB
7918 case ARM::COPY_STRUCT_BYVAL_I32:
7920 return EmitStructByval(MI, BB);
7921 case ARM::WIN__CHKSTK:
7922 return EmitLowered__chkstk(MI, BB);
7926 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7927 SDNode *Node) const {
7928 const MCInstrDesc *MCID = &MI->getDesc();
7929 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7930 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7931 // operand is still set to noreg. If needed, set the optional operand's
7932 // register to CPSR, and remove the redundant implicit def.
7934 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7936 // Rename pseudo opcodes.
7937 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7939 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7940 MCID = &TII->get(NewOpc);
7942 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7943 "converted opcode should be the same except for cc_out");
7947 // Add the optional cc_out operand
7948 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7950 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7952 // Any ARM instruction that sets the 's' bit should specify an optional
7953 // "cc_out" operand in the last operand position.
7954 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7955 assert(!NewOpc && "Optional cc_out operand required");
7958 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7959 // since we already have an optional CPSR def.
7960 bool definesCPSR = false;
7961 bool deadCPSR = false;
7962 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7964 const MachineOperand &MO = MI->getOperand(i);
7965 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7969 MI->RemoveOperand(i);
7974 assert(!NewOpc && "Optional cc_out operand required");
7977 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7979 assert(!MI->getOperand(ccOutIdx).getReg() &&
7980 "expect uninitialized optional cc_out operand");
7984 // If this instruction was defined with an optional CPSR def and its dag node
7985 // had a live implicit CPSR def, then activate the optional CPSR def.
7986 MachineOperand &MO = MI->getOperand(ccOutIdx);
7987 MO.setReg(ARM::CPSR);
7991 //===----------------------------------------------------------------------===//
7992 // ARM Optimization Hooks
7993 //===----------------------------------------------------------------------===//
7995 // Helper function that checks if N is a null or all ones constant.
7996 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7997 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8000 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8003 // Return true if N is conditionally 0 or all ones.
8004 // Detects these expressions where cc is an i1 value:
8006 // (select cc 0, y) [AllOnes=0]
8007 // (select cc y, 0) [AllOnes=0]
8008 // (zext cc) [AllOnes=0]
8009 // (sext cc) [AllOnes=0/1]
8010 // (select cc -1, y) [AllOnes=1]
8011 // (select cc y, -1) [AllOnes=1]
8013 // Invert is set when N is the null/all ones constant when CC is false.
8014 // OtherOp is set to the alternative value of N.
8015 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8016 SDValue &CC, bool &Invert,
8018 SelectionDAG &DAG) {
8019 switch (N->getOpcode()) {
8020 default: return false;
8022 CC = N->getOperand(0);
8023 SDValue N1 = N->getOperand(1);
8024 SDValue N2 = N->getOperand(2);
8025 if (isZeroOrAllOnes(N1, AllOnes)) {
8030 if (isZeroOrAllOnes(N2, AllOnes)) {
8037 case ISD::ZERO_EXTEND:
8038 // (zext cc) can never be the all ones value.
8042 case ISD::SIGN_EXTEND: {
8044 EVT VT = N->getValueType(0);
8045 CC = N->getOperand(0);
8046 if (CC.getValueType() != MVT::i1)
8050 // When looking for an AllOnes constant, N is an sext, and the 'other'
8052 OtherOp = DAG.getConstant(0, dl, VT);
8053 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8054 // When looking for a 0 constant, N can be zext or sext.
8055 OtherOp = DAG.getConstant(1, dl, VT);
8057 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8064 // Combine a constant select operand into its use:
8066 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8067 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8068 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8069 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8070 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8072 // The transform is rejected if the select doesn't have a constant operand that
8073 // is null, or all ones when AllOnes is set.
8075 // Also recognize sext/zext from i1:
8077 // (add (zext cc), x) -> (select cc (add x, 1), x)
8078 // (add (sext cc), x) -> (select cc (add x, -1), x)
8080 // These transformations eventually create predicated instructions.
8082 // @param N The node to transform.
8083 // @param Slct The N operand that is a select.
8084 // @param OtherOp The other N operand (x above).
8085 // @param DCI Context.
8086 // @param AllOnes Require the select constant to be all ones instead of null.
8087 // @returns The new node, or SDValue() on failure.
8089 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8090 TargetLowering::DAGCombinerInfo &DCI,
8091 bool AllOnes = false) {
8092 SelectionDAG &DAG = DCI.DAG;
8093 EVT VT = N->getValueType(0);
8094 SDValue NonConstantVal;
8097 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8098 NonConstantVal, DAG))
8101 // Slct is now know to be the desired identity constant when CC is true.
8102 SDValue TrueVal = OtherOp;
8103 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8104 OtherOp, NonConstantVal);
8105 // Unless SwapSelectOps says CC should be false.
8107 std::swap(TrueVal, FalseVal);
8109 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8110 CCOp, TrueVal, FalseVal);
8113 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8115 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8116 TargetLowering::DAGCombinerInfo &DCI) {
8117 SDValue N0 = N->getOperand(0);
8118 SDValue N1 = N->getOperand(1);
8119 if (N0.getNode()->hasOneUse()) {
8120 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8121 if (Result.getNode())
8124 if (N1.getNode()->hasOneUse()) {
8125 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8126 if (Result.getNode())
8132 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8133 // (only after legalization).
8134 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8135 TargetLowering::DAGCombinerInfo &DCI,
8136 const ARMSubtarget *Subtarget) {
8138 // Only perform optimization if after legalize, and if NEON is available. We
8139 // also expected both operands to be BUILD_VECTORs.
8140 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8141 || N0.getOpcode() != ISD::BUILD_VECTOR
8142 || N1.getOpcode() != ISD::BUILD_VECTOR)
8145 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8146 EVT VT = N->getValueType(0);
8147 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8150 // Check that the vector operands are of the right form.
8151 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8152 // operands, where N is the size of the formed vector.
8153 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8154 // index such that we have a pair wise add pattern.
8156 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8157 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8159 SDValue Vec = N0->getOperand(0)->getOperand(0);
8160 SDNode *V = Vec.getNode();
8161 unsigned nextIndex = 0;
8163 // For each operands to the ADD which are BUILD_VECTORs,
8164 // check to see if each of their operands are an EXTRACT_VECTOR with
8165 // the same vector and appropriate index.
8166 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8167 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8168 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8170 SDValue ExtVec0 = N0->getOperand(i);
8171 SDValue ExtVec1 = N1->getOperand(i);
8173 // First operand is the vector, verify its the same.
8174 if (V != ExtVec0->getOperand(0).getNode() ||
8175 V != ExtVec1->getOperand(0).getNode())
8178 // Second is the constant, verify its correct.
8179 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8180 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8182 // For the constant, we want to see all the even or all the odd.
8183 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8184 || C1->getZExtValue() != nextIndex+1)
8193 // Create VPADDL node.
8194 SelectionDAG &DAG = DCI.DAG;
8195 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8199 // Build operand list.
8200 SmallVector<SDValue, 8> Ops;
8201 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8202 TLI.getPointerTy(DAG.getDataLayout())));
8204 // Input is the vector.
8207 // Get widened type and narrowed type.
8209 unsigned numElem = VT.getVectorNumElements();
8211 EVT inputLaneType = Vec.getValueType().getVectorElementType();
8212 switch (inputLaneType.getSimpleVT().SimpleTy) {
8213 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8214 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8215 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8217 llvm_unreachable("Invalid vector element type for padd optimization.");
8220 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8221 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8222 return DAG.getNode(ExtOp, dl, VT, tmp);
8225 static SDValue findMUL_LOHI(SDValue V) {
8226 if (V->getOpcode() == ISD::UMUL_LOHI ||
8227 V->getOpcode() == ISD::SMUL_LOHI)
8232 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8233 TargetLowering::DAGCombinerInfo &DCI,
8234 const ARMSubtarget *Subtarget) {
8236 if (Subtarget->isThumb1Only()) return SDValue();
8238 // Only perform the checks after legalize when the pattern is available.
8239 if (DCI.isBeforeLegalize()) return SDValue();
8241 // Look for multiply add opportunities.
8242 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8243 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8244 // a glue link from the first add to the second add.
8245 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8246 // a S/UMLAL instruction.
8249 // / \ [no multiline comment]
8255 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8256 SDValue AddcOp0 = AddcNode->getOperand(0);
8257 SDValue AddcOp1 = AddcNode->getOperand(1);
8259 // Check if the two operands are from the same mul_lohi node.
8260 if (AddcOp0.getNode() == AddcOp1.getNode())
8263 assert(AddcNode->getNumValues() == 2 &&
8264 AddcNode->getValueType(0) == MVT::i32 &&
8265 "Expect ADDC with two result values. First: i32");
8267 // Check that we have a glued ADDC node.
8268 if (AddcNode->getValueType(1) != MVT::Glue)
8271 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8272 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8273 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8274 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8275 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8278 // Look for the glued ADDE.
8279 SDNode* AddeNode = AddcNode->getGluedUser();
8283 // Make sure it is really an ADDE.
8284 if (AddeNode->getOpcode() != ISD::ADDE)
8287 assert(AddeNode->getNumOperands() == 3 &&
8288 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8289 "ADDE node has the wrong inputs");
8291 // Check for the triangle shape.
8292 SDValue AddeOp0 = AddeNode->getOperand(0);
8293 SDValue AddeOp1 = AddeNode->getOperand(1);
8295 // Make sure that the ADDE operands are not coming from the same node.
8296 if (AddeOp0.getNode() == AddeOp1.getNode())
8299 // Find the MUL_LOHI node walking up ADDE's operands.
8300 bool IsLeftOperandMUL = false;
8301 SDValue MULOp = findMUL_LOHI(AddeOp0);
8302 if (MULOp == SDValue())
8303 MULOp = findMUL_LOHI(AddeOp1);
8305 IsLeftOperandMUL = true;
8306 if (MULOp == SDValue())
8309 // Figure out the right opcode.
8310 unsigned Opc = MULOp->getOpcode();
8311 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8313 // Figure out the high and low input values to the MLAL node.
8314 SDValue* HiAdd = nullptr;
8315 SDValue* LoMul = nullptr;
8316 SDValue* LowAdd = nullptr;
8318 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8319 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8322 if (IsLeftOperandMUL)
8328 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8329 // whose low result is fed to the ADDC we are checking.
8331 if (AddcOp0 == MULOp.getValue(0)) {
8335 if (AddcOp1 == MULOp.getValue(0)) {
8343 // Create the merged node.
8344 SelectionDAG &DAG = DCI.DAG;
8346 // Build operand list.
8347 SmallVector<SDValue, 8> Ops;
8348 Ops.push_back(LoMul->getOperand(0));
8349 Ops.push_back(LoMul->getOperand(1));
8350 Ops.push_back(*LowAdd);
8351 Ops.push_back(*HiAdd);
8353 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8354 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8356 // Replace the ADDs' nodes uses by the MLA node's values.
8357 SDValue HiMLALResult(MLALNode.getNode(), 1);
8358 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8360 SDValue LoMLALResult(MLALNode.getNode(), 0);
8361 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8363 // Return original node to notify the driver to stop replacing.
8364 SDValue resNode(AddcNode, 0);
8368 /// PerformADDCCombine - Target-specific dag combine transform from
8369 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8370 static SDValue PerformADDCCombine(SDNode *N,
8371 TargetLowering::DAGCombinerInfo &DCI,
8372 const ARMSubtarget *Subtarget) {
8374 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8378 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8379 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8380 /// called with the default operands, and if that fails, with commuted
8382 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8383 TargetLowering::DAGCombinerInfo &DCI,
8384 const ARMSubtarget *Subtarget){
8386 // Attempt to create vpaddl for this add.
8387 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8388 if (Result.getNode())
8391 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8392 if (N0.getNode()->hasOneUse()) {
8393 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8394 if (Result.getNode()) return Result;
8399 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8401 static SDValue PerformADDCombine(SDNode *N,
8402 TargetLowering::DAGCombinerInfo &DCI,
8403 const ARMSubtarget *Subtarget) {
8404 SDValue N0 = N->getOperand(0);
8405 SDValue N1 = N->getOperand(1);
8407 // First try with the default operand order.
8408 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8409 if (Result.getNode())
8412 // If that didn't work, try again with the operands commuted.
8413 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8416 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8418 static SDValue PerformSUBCombine(SDNode *N,
8419 TargetLowering::DAGCombinerInfo &DCI) {
8420 SDValue N0 = N->getOperand(0);
8421 SDValue N1 = N->getOperand(1);
8423 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8424 if (N1.getNode()->hasOneUse()) {
8425 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8426 if (Result.getNode()) return Result;
8432 /// PerformVMULCombine
8433 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8434 /// special multiplier accumulator forwarding.
8440 // However, for (A + B) * (A + B),
8447 static SDValue PerformVMULCombine(SDNode *N,
8448 TargetLowering::DAGCombinerInfo &DCI,
8449 const ARMSubtarget *Subtarget) {
8450 if (!Subtarget->hasVMLxForwarding())
8453 SelectionDAG &DAG = DCI.DAG;
8454 SDValue N0 = N->getOperand(0);
8455 SDValue N1 = N->getOperand(1);
8456 unsigned Opcode = N0.getOpcode();
8457 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8458 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8459 Opcode = N1.getOpcode();
8460 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8461 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8469 EVT VT = N->getValueType(0);
8471 SDValue N00 = N0->getOperand(0);
8472 SDValue N01 = N0->getOperand(1);
8473 return DAG.getNode(Opcode, DL, VT,
8474 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8475 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8478 static SDValue PerformMULCombine(SDNode *N,
8479 TargetLowering::DAGCombinerInfo &DCI,
8480 const ARMSubtarget *Subtarget) {
8481 SelectionDAG &DAG = DCI.DAG;
8483 if (Subtarget->isThumb1Only())
8486 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8489 EVT VT = N->getValueType(0);
8490 if (VT.is64BitVector() || VT.is128BitVector())
8491 return PerformVMULCombine(N, DCI, Subtarget);
8495 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8499 int64_t MulAmt = C->getSExtValue();
8500 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8502 ShiftAmt = ShiftAmt & (32 - 1);
8503 SDValue V = N->getOperand(0);
8507 MulAmt >>= ShiftAmt;
8510 if (isPowerOf2_32(MulAmt - 1)) {
8511 // (mul x, 2^N + 1) => (add (shl x, N), x)
8512 Res = DAG.getNode(ISD::ADD, DL, VT,
8514 DAG.getNode(ISD::SHL, DL, VT,
8516 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8518 } else if (isPowerOf2_32(MulAmt + 1)) {
8519 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8520 Res = DAG.getNode(ISD::SUB, DL, VT,
8521 DAG.getNode(ISD::SHL, DL, VT,
8523 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8529 uint64_t MulAmtAbs = -MulAmt;
8530 if (isPowerOf2_32(MulAmtAbs + 1)) {
8531 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8532 Res = DAG.getNode(ISD::SUB, DL, VT,
8534 DAG.getNode(ISD::SHL, DL, VT,
8536 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8538 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8539 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8540 Res = DAG.getNode(ISD::ADD, DL, VT,
8542 DAG.getNode(ISD::SHL, DL, VT,
8544 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8546 Res = DAG.getNode(ISD::SUB, DL, VT,
8547 DAG.getConstant(0, DL, MVT::i32), Res);
8554 Res = DAG.getNode(ISD::SHL, DL, VT,
8555 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8557 // Do not add new nodes to DAG combiner worklist.
8558 DCI.CombineTo(N, Res, false);
8562 static SDValue PerformANDCombine(SDNode *N,
8563 TargetLowering::DAGCombinerInfo &DCI,
8564 const ARMSubtarget *Subtarget) {
8566 // Attempt to use immediate-form VBIC
8567 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8569 EVT VT = N->getValueType(0);
8570 SelectionDAG &DAG = DCI.DAG;
8572 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8575 APInt SplatBits, SplatUndef;
8576 unsigned SplatBitSize;
8579 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8580 if (SplatBitSize <= 64) {
8582 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8583 SplatUndef.getZExtValue(), SplatBitSize,
8584 DAG, dl, VbicVT, VT.is128BitVector(),
8586 if (Val.getNode()) {
8588 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8589 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8590 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8595 if (!Subtarget->isThumb1Only()) {
8596 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8597 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8598 if (Result.getNode())
8605 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8606 static SDValue PerformORCombine(SDNode *N,
8607 TargetLowering::DAGCombinerInfo &DCI,
8608 const ARMSubtarget *Subtarget) {
8609 // Attempt to use immediate-form VORR
8610 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8612 EVT VT = N->getValueType(0);
8613 SelectionDAG &DAG = DCI.DAG;
8615 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8618 APInt SplatBits, SplatUndef;
8619 unsigned SplatBitSize;
8621 if (BVN && Subtarget->hasNEON() &&
8622 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8623 if (SplatBitSize <= 64) {
8625 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8626 SplatUndef.getZExtValue(), SplatBitSize,
8627 DAG, dl, VorrVT, VT.is128BitVector(),
8629 if (Val.getNode()) {
8631 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8632 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8633 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8638 if (!Subtarget->isThumb1Only()) {
8639 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8640 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8641 if (Result.getNode())
8645 // The code below optimizes (or (and X, Y), Z).
8646 // The AND operand needs to have a single user to make these optimizations
8648 SDValue N0 = N->getOperand(0);
8649 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8651 SDValue N1 = N->getOperand(1);
8653 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8654 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8655 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8657 unsigned SplatBitSize;
8660 APInt SplatBits0, SplatBits1;
8661 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8662 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8663 // Ensure that the second operand of both ands are constants
8664 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8665 HasAnyUndefs) && !HasAnyUndefs) {
8666 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8667 HasAnyUndefs) && !HasAnyUndefs) {
8668 // Ensure that the bit width of the constants are the same and that
8669 // the splat arguments are logical inverses as per the pattern we
8670 // are trying to simplify.
8671 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8672 SplatBits0 == ~SplatBits1) {
8673 // Canonicalize the vector type to make instruction selection
8675 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8676 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8680 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8686 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8689 // BFI is only available on V6T2+
8690 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8694 // 1) or (and A, mask), val => ARMbfi A, val, mask
8695 // iff (val & mask) == val
8697 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8698 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8699 // && mask == ~mask2
8700 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8701 // && ~mask == mask2
8702 // (i.e., copy a bitfield value into another bitfield of the same width)
8707 SDValue N00 = N0.getOperand(0);
8709 // The value and the mask need to be constants so we can verify this is
8710 // actually a bitfield set. If the mask is 0xffff, we can do better
8711 // via a movt instruction, so don't use BFI in that case.
8712 SDValue MaskOp = N0.getOperand(1);
8713 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8716 unsigned Mask = MaskC->getZExtValue();
8720 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8721 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8723 unsigned Val = N1C->getZExtValue();
8724 if ((Val & ~Mask) != Val)
8727 if (ARM::isBitFieldInvertedMask(Mask)) {
8728 Val >>= countTrailingZeros(~Mask);
8730 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8731 DAG.getConstant(Val, DL, MVT::i32),
8732 DAG.getConstant(Mask, DL, MVT::i32));
8734 // Do not add new nodes to DAG combiner worklist.
8735 DCI.CombineTo(N, Res, false);
8738 } else if (N1.getOpcode() == ISD::AND) {
8739 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8740 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8743 unsigned Mask2 = N11C->getZExtValue();
8745 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8747 if (ARM::isBitFieldInvertedMask(Mask) &&
8749 // The pack halfword instruction works better for masks that fit it,
8750 // so use that when it's available.
8751 if (Subtarget->hasT2ExtractPack() &&
8752 (Mask == 0xffff || Mask == 0xffff0000))
8755 unsigned amt = countTrailingZeros(Mask2);
8756 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8757 DAG.getConstant(amt, DL, MVT::i32));
8758 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8759 DAG.getConstant(Mask, DL, MVT::i32));
8760 // Do not add new nodes to DAG combiner worklist.
8761 DCI.CombineTo(N, Res, false);
8763 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8765 // The pack halfword instruction works better for masks that fit it,
8766 // so use that when it's available.
8767 if (Subtarget->hasT2ExtractPack() &&
8768 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8771 unsigned lsb = countTrailingZeros(Mask);
8772 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8773 DAG.getConstant(lsb, DL, MVT::i32));
8774 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8775 DAG.getConstant(Mask2, DL, MVT::i32));
8776 // Do not add new nodes to DAG combiner worklist.
8777 DCI.CombineTo(N, Res, false);
8782 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8783 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8784 ARM::isBitFieldInvertedMask(~Mask)) {
8785 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8786 // where lsb(mask) == #shamt and masked bits of B are known zero.
8787 SDValue ShAmt = N00.getOperand(1);
8788 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8789 unsigned LSB = countTrailingZeros(Mask);
8793 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8794 DAG.getConstant(~Mask, DL, MVT::i32));
8796 // Do not add new nodes to DAG combiner worklist.
8797 DCI.CombineTo(N, Res, false);
8803 static SDValue PerformXORCombine(SDNode *N,
8804 TargetLowering::DAGCombinerInfo &DCI,
8805 const ARMSubtarget *Subtarget) {
8806 EVT VT = N->getValueType(0);
8807 SelectionDAG &DAG = DCI.DAG;
8809 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8812 if (!Subtarget->isThumb1Only()) {
8813 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8814 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8815 if (Result.getNode())
8822 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8823 /// the bits being cleared by the AND are not demanded by the BFI.
8824 static SDValue PerformBFICombine(SDNode *N,
8825 TargetLowering::DAGCombinerInfo &DCI) {
8826 SDValue N1 = N->getOperand(1);
8827 if (N1.getOpcode() == ISD::AND) {
8828 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8831 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8832 unsigned LSB = countTrailingZeros(~InvMask);
8833 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8835 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8836 "undefined behavior");
8837 unsigned Mask = (1u << Width) - 1;
8838 unsigned Mask2 = N11C->getZExtValue();
8839 if ((Mask & (~Mask2)) == 0)
8840 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8841 N->getOperand(0), N1.getOperand(0),
8847 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8848 /// ARMISD::VMOVRRD.
8849 static SDValue PerformVMOVRRDCombine(SDNode *N,
8850 TargetLowering::DAGCombinerInfo &DCI,
8851 const ARMSubtarget *Subtarget) {
8852 // vmovrrd(vmovdrr x, y) -> x,y
8853 SDValue InDouble = N->getOperand(0);
8854 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8855 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8857 // vmovrrd(load f64) -> (load i32), (load i32)
8858 SDNode *InNode = InDouble.getNode();
8859 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8860 InNode->getValueType(0) == MVT::f64 &&
8861 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8862 !cast<LoadSDNode>(InNode)->isVolatile()) {
8863 // TODO: Should this be done for non-FrameIndex operands?
8864 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8866 SelectionDAG &DAG = DCI.DAG;
8868 SDValue BasePtr = LD->getBasePtr();
8869 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8870 LD->getPointerInfo(), LD->isVolatile(),
8871 LD->isNonTemporal(), LD->isInvariant(),
8872 LD->getAlignment());
8874 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8875 DAG.getConstant(4, DL, MVT::i32));
8876 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8877 LD->getPointerInfo(), LD->isVolatile(),
8878 LD->isNonTemporal(), LD->isInvariant(),
8879 std::min(4U, LD->getAlignment() / 2));
8881 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8882 if (DCI.DAG.getDataLayout().isBigEndian())
8883 std::swap (NewLD1, NewLD2);
8884 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8891 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8892 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8893 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8894 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8895 SDValue Op0 = N->getOperand(0);
8896 SDValue Op1 = N->getOperand(1);
8897 if (Op0.getOpcode() == ISD::BITCAST)
8898 Op0 = Op0.getOperand(0);
8899 if (Op1.getOpcode() == ISD::BITCAST)
8900 Op1 = Op1.getOperand(0);
8901 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8902 Op0.getNode() == Op1.getNode() &&
8903 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8904 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8905 N->getValueType(0), Op0.getOperand(0));
8909 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8910 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8911 /// i64 vector to have f64 elements, since the value can then be loaded
8912 /// directly into a VFP register.
8913 static bool hasNormalLoadOperand(SDNode *N) {
8914 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8915 for (unsigned i = 0; i < NumElts; ++i) {
8916 SDNode *Elt = N->getOperand(i).getNode();
8917 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8923 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8924 /// ISD::BUILD_VECTOR.
8925 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8926 TargetLowering::DAGCombinerInfo &DCI,
8927 const ARMSubtarget *Subtarget) {
8928 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8929 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8930 // into a pair of GPRs, which is fine when the value is used as a scalar,
8931 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8932 SelectionDAG &DAG = DCI.DAG;
8933 if (N->getNumOperands() == 2) {
8934 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8939 // Load i64 elements as f64 values so that type legalization does not split
8940 // them up into i32 values.
8941 EVT VT = N->getValueType(0);
8942 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8945 SmallVector<SDValue, 8> Ops;
8946 unsigned NumElts = VT.getVectorNumElements();
8947 for (unsigned i = 0; i < NumElts; ++i) {
8948 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8950 // Make the DAGCombiner fold the bitcast.
8951 DCI.AddToWorklist(V.getNode());
8953 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8954 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8955 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8958 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8960 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8961 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8962 // At that time, we may have inserted bitcasts from integer to float.
8963 // If these bitcasts have survived DAGCombine, change the lowering of this
8964 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8965 // force to use floating point types.
8967 // Make sure we can change the type of the vector.
8968 // This is possible iff:
8969 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8970 // 1.1. Vector is used only once.
8971 // 1.2. Use is a bit convert to an integer type.
8972 // 2. The size of its operands are 32-bits (64-bits are not legal).
8973 EVT VT = N->getValueType(0);
8974 EVT EltVT = VT.getVectorElementType();
8976 // Check 1.1. and 2.
8977 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8980 // By construction, the input type must be float.
8981 assert(EltVT == MVT::f32 && "Unexpected type!");
8984 SDNode *Use = *N->use_begin();
8985 if (Use->getOpcode() != ISD::BITCAST ||
8986 Use->getValueType(0).isFloatingPoint())
8989 // Check profitability.
8990 // Model is, if more than half of the relevant operands are bitcast from
8991 // i32, turn the build_vector into a sequence of insert_vector_elt.
8992 // Relevant operands are everything that is not statically
8993 // (i.e., at compile time) bitcasted.
8994 unsigned NumOfBitCastedElts = 0;
8995 unsigned NumElts = VT.getVectorNumElements();
8996 unsigned NumOfRelevantElts = NumElts;
8997 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8998 SDValue Elt = N->getOperand(Idx);
8999 if (Elt->getOpcode() == ISD::BITCAST) {
9000 // Assume only bit cast to i32 will go away.
9001 if (Elt->getOperand(0).getValueType() == MVT::i32)
9002 ++NumOfBitCastedElts;
9003 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9004 // Constants are statically casted, thus do not count them as
9005 // relevant operands.
9006 --NumOfRelevantElts;
9009 // Check if more than half of the elements require a non-free bitcast.
9010 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9013 SelectionDAG &DAG = DCI.DAG;
9014 // Create the new vector type.
9015 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9016 // Check if the type is legal.
9017 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9018 if (!TLI.isTypeLegal(VecVT))
9022 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9023 // => BITCAST INSERT_VECTOR_ELT
9024 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9026 SDValue Vec = DAG.getUNDEF(VecVT);
9028 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9029 SDValue V = N->getOperand(Idx);
9030 if (V.getOpcode() == ISD::UNDEF)
9032 if (V.getOpcode() == ISD::BITCAST &&
9033 V->getOperand(0).getValueType() == MVT::i32)
9034 // Fold obvious case.
9035 V = V.getOperand(0);
9037 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9038 // Make the DAGCombiner fold the bitcasts.
9039 DCI.AddToWorklist(V.getNode());
9041 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9042 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9044 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9045 // Make the DAGCombiner fold the bitcasts.
9046 DCI.AddToWorklist(Vec.getNode());
9050 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9051 /// ISD::INSERT_VECTOR_ELT.
9052 static SDValue PerformInsertEltCombine(SDNode *N,
9053 TargetLowering::DAGCombinerInfo &DCI) {
9054 // Bitcast an i64 load inserted into a vector to f64.
9055 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9056 EVT VT = N->getValueType(0);
9057 SDNode *Elt = N->getOperand(1).getNode();
9058 if (VT.getVectorElementType() != MVT::i64 ||
9059 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9062 SelectionDAG &DAG = DCI.DAG;
9064 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9065 VT.getVectorNumElements());
9066 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9067 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9068 // Make the DAGCombiner fold the bitcasts.
9069 DCI.AddToWorklist(Vec.getNode());
9070 DCI.AddToWorklist(V.getNode());
9071 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9072 Vec, V, N->getOperand(2));
9073 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9076 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9077 /// ISD::VECTOR_SHUFFLE.
9078 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9079 // The LLVM shufflevector instruction does not require the shuffle mask
9080 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9081 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9082 // operands do not match the mask length, they are extended by concatenating
9083 // them with undef vectors. That is probably the right thing for other
9084 // targets, but for NEON it is better to concatenate two double-register
9085 // size vector operands into a single quad-register size vector. Do that
9086 // transformation here:
9087 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9088 // shuffle(concat(v1, v2), undef)
9089 SDValue Op0 = N->getOperand(0);
9090 SDValue Op1 = N->getOperand(1);
9091 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9092 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9093 Op0.getNumOperands() != 2 ||
9094 Op1.getNumOperands() != 2)
9096 SDValue Concat0Op1 = Op0.getOperand(1);
9097 SDValue Concat1Op1 = Op1.getOperand(1);
9098 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9099 Concat1Op1.getOpcode() != ISD::UNDEF)
9101 // Skip the transformation if any of the types are illegal.
9102 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9103 EVT VT = N->getValueType(0);
9104 if (!TLI.isTypeLegal(VT) ||
9105 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9106 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9109 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9110 Op0.getOperand(0), Op1.getOperand(0));
9111 // Translate the shuffle mask.
9112 SmallVector<int, 16> NewMask;
9113 unsigned NumElts = VT.getVectorNumElements();
9114 unsigned HalfElts = NumElts/2;
9115 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9116 for (unsigned n = 0; n < NumElts; ++n) {
9117 int MaskElt = SVN->getMaskElt(n);
9119 if (MaskElt < (int)HalfElts)
9121 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9122 NewElt = HalfElts + MaskElt - NumElts;
9123 NewMask.push_back(NewElt);
9125 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9126 DAG.getUNDEF(VT), NewMask.data());
9129 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9130 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9131 /// base address updates.
9132 /// For generic load/stores, the memory type is assumed to be a vector.
9133 /// The caller is assumed to have checked legality.
9134 static SDValue CombineBaseUpdate(SDNode *N,
9135 TargetLowering::DAGCombinerInfo &DCI) {
9136 SelectionDAG &DAG = DCI.DAG;
9137 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9138 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9139 const bool isStore = N->getOpcode() == ISD::STORE;
9140 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9141 SDValue Addr = N->getOperand(AddrOpIdx);
9142 MemSDNode *MemN = cast<MemSDNode>(N);
9145 // Search for a use of the address operand that is an increment.
9146 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9147 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9149 if (User->getOpcode() != ISD::ADD ||
9150 UI.getUse().getResNo() != Addr.getResNo())
9153 // Check that the add is independent of the load/store. Otherwise, folding
9154 // it would create a cycle.
9155 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9158 // Find the new opcode for the updating load/store.
9159 bool isLoadOp = true;
9160 bool isLaneOp = false;
9161 unsigned NewOpc = 0;
9162 unsigned NumVecs = 0;
9164 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9166 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9167 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9169 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9171 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9173 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9175 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9176 NumVecs = 2; isLaneOp = true; break;
9177 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9178 NumVecs = 3; isLaneOp = true; break;
9179 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9180 NumVecs = 4; isLaneOp = true; break;
9181 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9182 NumVecs = 1; isLoadOp = false; break;
9183 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9184 NumVecs = 2; isLoadOp = false; break;
9185 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9186 NumVecs = 3; isLoadOp = false; break;
9187 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9188 NumVecs = 4; isLoadOp = false; break;
9189 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9190 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9191 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9192 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9193 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9194 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9198 switch (N->getOpcode()) {
9199 default: llvm_unreachable("unexpected opcode for Neon base update");
9200 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9201 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9202 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9203 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
9204 NumVecs = 1; isLaneOp = false; break;
9205 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
9206 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9210 // Find the size of memory referenced by the load/store.
9213 VecTy = N->getValueType(0);
9214 } else if (isIntrinsic) {
9215 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9217 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9218 VecTy = N->getOperand(1).getValueType();
9221 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9223 NumBytes /= VecTy.getVectorNumElements();
9225 // If the increment is a constant, it must match the memory ref size.
9226 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9227 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9228 uint64_t IncVal = CInc->getZExtValue();
9229 if (IncVal != NumBytes)
9231 } else if (NumBytes >= 3 * 16) {
9232 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9233 // separate instructions that make it harder to use a non-constant update.
9237 // OK, we found an ADD we can fold into the base update.
9238 // Now, create a _UPD node, taking care of not breaking alignment.
9240 EVT AlignedVecTy = VecTy;
9241 unsigned Alignment = MemN->getAlignment();
9243 // If this is a less-than-standard-aligned load/store, change the type to
9244 // match the standard alignment.
9245 // The alignment is overlooked when selecting _UPD variants; and it's
9246 // easier to introduce bitcasts here than fix that.
9247 // There are 3 ways to get to this base-update combine:
9248 // - intrinsics: they are assumed to be properly aligned (to the standard
9249 // alignment of the memory type), so we don't need to do anything.
9250 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9251 // intrinsics, so, likewise, there's nothing to do.
9252 // - generic load/store instructions: the alignment is specified as an
9253 // explicit operand, rather than implicitly as the standard alignment
9254 // of the memory type (like the intrisics). We need to change the
9255 // memory type to match the explicit alignment. That way, we don't
9256 // generate non-standard-aligned ARMISD::VLDx nodes.
9257 if (isa<LSBaseSDNode>(N)) {
9260 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9261 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9262 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9263 assert(!isLaneOp && "Unexpected generic load/store lane.");
9264 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9265 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9267 // Don't set an explicit alignment on regular load/stores that we want
9268 // to transform to VLD/VST 1_UPD nodes.
9269 // This matches the behavior of regular load/stores, which only get an
9270 // explicit alignment if the MMO alignment is larger than the standard
9271 // alignment of the memory type.
9272 // Intrinsics, however, always get an explicit alignment, set to the
9273 // alignment of the MMO.
9277 // Create the new updating load/store node.
9278 // First, create an SDVTList for the new updating node's results.
9280 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9282 for (n = 0; n < NumResultVecs; ++n)
9283 Tys[n] = AlignedVecTy;
9284 Tys[n++] = MVT::i32;
9285 Tys[n] = MVT::Other;
9286 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9288 // Then, gather the new node's operands.
9289 SmallVector<SDValue, 8> Ops;
9290 Ops.push_back(N->getOperand(0)); // incoming chain
9291 Ops.push_back(N->getOperand(AddrOpIdx));
9294 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9295 // Try to match the intrinsic's signature
9296 Ops.push_back(StN->getValue());
9298 // Loads (and of course intrinsics) match the intrinsics' signature,
9299 // so just add all but the alignment operand.
9300 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9301 Ops.push_back(N->getOperand(i));
9304 // For all node types, the alignment operand is always the last one.
9305 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9307 // If this is a non-standard-aligned STORE, the penultimate operand is the
9308 // stored value. Bitcast it to the aligned type.
9309 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9310 SDValue &StVal = Ops[Ops.size()-2];
9311 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9314 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9316 MemN->getMemOperand());
9319 SmallVector<SDValue, 5> NewResults;
9320 for (unsigned i = 0; i < NumResultVecs; ++i)
9321 NewResults.push_back(SDValue(UpdN.getNode(), i));
9323 // If this is an non-standard-aligned LOAD, the first result is the loaded
9324 // value. Bitcast it to the expected result type.
9325 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9326 SDValue &LdVal = NewResults[0];
9327 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9330 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9331 DCI.CombineTo(N, NewResults);
9332 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9339 static SDValue PerformVLDCombine(SDNode *N,
9340 TargetLowering::DAGCombinerInfo &DCI) {
9341 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9344 return CombineBaseUpdate(N, DCI);
9347 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9348 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9349 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9351 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9352 SelectionDAG &DAG = DCI.DAG;
9353 EVT VT = N->getValueType(0);
9354 // vldN-dup instructions only support 64-bit vectors for N > 1.
9355 if (!VT.is64BitVector())
9358 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9359 SDNode *VLD = N->getOperand(0).getNode();
9360 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9362 unsigned NumVecs = 0;
9363 unsigned NewOpc = 0;
9364 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9365 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9367 NewOpc = ARMISD::VLD2DUP;
9368 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9370 NewOpc = ARMISD::VLD3DUP;
9371 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9373 NewOpc = ARMISD::VLD4DUP;
9378 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9379 // numbers match the load.
9380 unsigned VLDLaneNo =
9381 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9382 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9384 // Ignore uses of the chain result.
9385 if (UI.getUse().getResNo() == NumVecs)
9388 if (User->getOpcode() != ARMISD::VDUPLANE ||
9389 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9393 // Create the vldN-dup node.
9396 for (n = 0; n < NumVecs; ++n)
9398 Tys[n] = MVT::Other;
9399 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9400 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9401 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9402 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9403 Ops, VLDMemInt->getMemoryVT(),
9404 VLDMemInt->getMemOperand());
9407 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9409 unsigned ResNo = UI.getUse().getResNo();
9410 // Ignore uses of the chain result.
9411 if (ResNo == NumVecs)
9414 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9417 // Now the vldN-lane intrinsic is dead except for its chain result.
9418 // Update uses of the chain.
9419 std::vector<SDValue> VLDDupResults;
9420 for (unsigned n = 0; n < NumVecs; ++n)
9421 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9422 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9423 DCI.CombineTo(VLD, VLDDupResults);
9428 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9429 /// ARMISD::VDUPLANE.
9430 static SDValue PerformVDUPLANECombine(SDNode *N,
9431 TargetLowering::DAGCombinerInfo &DCI) {
9432 SDValue Op = N->getOperand(0);
9434 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9435 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9436 if (CombineVLDDUP(N, DCI))
9437 return SDValue(N, 0);
9439 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9440 // redundant. Ignore bit_converts for now; element sizes are checked below.
9441 while (Op.getOpcode() == ISD::BITCAST)
9442 Op = Op.getOperand(0);
9443 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9446 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9447 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9448 // The canonical VMOV for a zero vector uses a 32-bit element size.
9449 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9451 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9453 EVT VT = N->getValueType(0);
9454 if (EltSize > VT.getVectorElementType().getSizeInBits())
9457 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9460 static SDValue PerformLOADCombine(SDNode *N,
9461 TargetLowering::DAGCombinerInfo &DCI) {
9462 EVT VT = N->getValueType(0);
9464 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9465 if (ISD::isNormalLoad(N) && VT.isVector() &&
9466 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9467 return CombineBaseUpdate(N, DCI);
9472 /// PerformSTORECombine - Target-specific dag combine xforms for
9474 static SDValue PerformSTORECombine(SDNode *N,
9475 TargetLowering::DAGCombinerInfo &DCI) {
9476 StoreSDNode *St = cast<StoreSDNode>(N);
9477 if (St->isVolatile())
9480 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9481 // pack all of the elements in one place. Next, store to memory in fewer
9483 SDValue StVal = St->getValue();
9484 EVT VT = StVal.getValueType();
9485 if (St->isTruncatingStore() && VT.isVector()) {
9486 SelectionDAG &DAG = DCI.DAG;
9487 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9488 EVT StVT = St->getMemoryVT();
9489 unsigned NumElems = VT.getVectorNumElements();
9490 assert(StVT != VT && "Cannot truncate to the same type");
9491 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9492 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9494 // From, To sizes and ElemCount must be pow of two
9495 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9497 // We are going to use the original vector elt for storing.
9498 // Accumulated smaller vector elements must be a multiple of the store size.
9499 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9501 unsigned SizeRatio = FromEltSz / ToEltSz;
9502 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9504 // Create a type on which we perform the shuffle.
9505 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9506 NumElems*SizeRatio);
9507 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9510 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9511 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9512 for (unsigned i = 0; i < NumElems; ++i)
9513 ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9514 ? (i + 1) * SizeRatio - 1
9517 // Can't shuffle using an illegal type.
9518 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9520 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9521 DAG.getUNDEF(WideVec.getValueType()),
9523 // At this point all of the data is stored at the bottom of the
9524 // register. We now need to save it to mem.
9526 // Find the largest store unit
9527 MVT StoreType = MVT::i8;
9528 for (MVT Tp : MVT::integer_valuetypes()) {
9529 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9532 // Didn't find a legal store type.
9533 if (!TLI.isTypeLegal(StoreType))
9536 // Bitcast the original vector into a vector of store-size units
9537 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9538 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9539 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9540 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9541 SmallVector<SDValue, 8> Chains;
9542 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9543 TLI.getPointerTy(DAG.getDataLayout()));
9544 SDValue BasePtr = St->getBasePtr();
9546 // Perform one or more big stores into memory.
9547 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9548 for (unsigned I = 0; I < E; I++) {
9549 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9550 StoreType, ShuffWide,
9551 DAG.getIntPtrConstant(I, DL));
9552 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9553 St->getPointerInfo(), St->isVolatile(),
9554 St->isNonTemporal(), St->getAlignment());
9555 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9557 Chains.push_back(Ch);
9559 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9562 if (!ISD::isNormalStore(St))
9565 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9566 // ARM stores of arguments in the same cache line.
9567 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9568 StVal.getNode()->hasOneUse()) {
9569 SelectionDAG &DAG = DCI.DAG;
9570 bool isBigEndian = DAG.getDataLayout().isBigEndian();
9572 SDValue BasePtr = St->getBasePtr();
9573 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9574 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9575 BasePtr, St->getPointerInfo(), St->isVolatile(),
9576 St->isNonTemporal(), St->getAlignment());
9578 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9579 DAG.getConstant(4, DL, MVT::i32));
9580 return DAG.getStore(NewST1.getValue(0), DL,
9581 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9582 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9583 St->isNonTemporal(),
9584 std::min(4U, St->getAlignment() / 2));
9587 if (StVal.getValueType() == MVT::i64 &&
9588 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9590 // Bitcast an i64 store extracted from a vector to f64.
9591 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9592 SelectionDAG &DAG = DCI.DAG;
9594 SDValue IntVec = StVal.getOperand(0);
9595 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9596 IntVec.getValueType().getVectorNumElements());
9597 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9598 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9599 Vec, StVal.getOperand(1));
9601 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9602 // Make the DAGCombiner fold the bitcasts.
9603 DCI.AddToWorklist(Vec.getNode());
9604 DCI.AddToWorklist(ExtElt.getNode());
9605 DCI.AddToWorklist(V.getNode());
9606 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9607 St->getPointerInfo(), St->isVolatile(),
9608 St->isNonTemporal(), St->getAlignment(),
9612 // If this is a legal vector store, try to combine it into a VST1_UPD.
9613 if (ISD::isNormalStore(N) && VT.isVector() &&
9614 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9615 return CombineBaseUpdate(N, DCI);
9620 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9621 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9622 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9626 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9628 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9633 APFloat APF = C->getValueAPF();
9634 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9635 != APFloat::opOK || !isExact)
9638 c0 = (I == 0) ? cN : c0;
9639 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9646 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9647 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9648 /// when the VMUL has a constant operand that is a power of 2.
9650 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9651 /// vmul.f32 d16, d17, d16
9652 /// vcvt.s32.f32 d16, d16
9654 /// vcvt.s32.f32 d16, d16, #3
9655 static SDValue PerformVCVTCombine(SDNode *N,
9656 TargetLowering::DAGCombinerInfo &DCI,
9657 const ARMSubtarget *Subtarget) {
9658 SelectionDAG &DAG = DCI.DAG;
9659 SDValue Op = N->getOperand(0);
9661 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9662 Op.getOpcode() != ISD::FMUL)
9666 SDValue N0 = Op->getOperand(0);
9667 SDValue ConstVec = Op->getOperand(1);
9668 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9670 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9671 !isConstVecPow2(ConstVec, isSigned, C))
9674 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9675 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9676 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9677 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9679 // These instructions only exist converting from f32 to i32. We can handle
9680 // smaller integers by generating an extra truncate, but larger ones would
9681 // be lossy. We also can't handle more then 4 lanes, since these intructions
9682 // only support v2i32/v4i32 types.
9687 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9688 Intrinsic::arm_neon_vcvtfp2fxu;
9689 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9690 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9691 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9693 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9695 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9696 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9701 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9702 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9703 /// when the VDIV has a constant operand that is a power of 2.
9705 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9706 /// vcvt.f32.s32 d16, d16
9707 /// vdiv.f32 d16, d17, d16
9709 /// vcvt.f32.s32 d16, d16, #3
9710 static SDValue PerformVDIVCombine(SDNode *N,
9711 TargetLowering::DAGCombinerInfo &DCI,
9712 const ARMSubtarget *Subtarget) {
9713 SelectionDAG &DAG = DCI.DAG;
9714 SDValue Op = N->getOperand(0);
9715 unsigned OpOpcode = Op.getNode()->getOpcode();
9717 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9718 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9722 SDValue ConstVec = N->getOperand(1);
9723 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9725 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9726 !isConstVecPow2(ConstVec, isSigned, C))
9729 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9730 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9731 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9732 // These instructions only exist converting from i32 to f32. We can handle
9733 // smaller integers by generating an extra extend, but larger ones would
9739 SDValue ConvInput = Op.getOperand(0);
9740 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9741 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9742 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9743 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9746 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9747 Intrinsic::arm_neon_vcvtfxu2fp;
9748 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9750 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9751 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9754 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9755 /// operand of a vector shift operation, where all the elements of the
9756 /// build_vector must have the same constant integer value.
9757 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9758 // Ignore bit_converts.
9759 while (Op.getOpcode() == ISD::BITCAST)
9760 Op = Op.getOperand(0);
9761 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9762 APInt SplatBits, SplatUndef;
9763 unsigned SplatBitSize;
9765 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9766 HasAnyUndefs, ElementBits) ||
9767 SplatBitSize > ElementBits)
9769 Cnt = SplatBits.getSExtValue();
9773 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9774 /// operand of a vector shift left operation. That value must be in the range:
9775 /// 0 <= Value < ElementBits for a left shift; or
9776 /// 0 <= Value <= ElementBits for a long left shift.
9777 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9778 assert(VT.isVector() && "vector shift count is not a vector type");
9779 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9780 if (! getVShiftImm(Op, ElementBits, Cnt))
9782 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9785 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9786 /// operand of a vector shift right operation. For a shift opcode, the value
9787 /// is positive, but for an intrinsic the value count must be negative. The
9788 /// absolute value must be in the range:
9789 /// 1 <= |Value| <= ElementBits for a right shift; or
9790 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9791 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9793 assert(VT.isVector() && "vector shift count is not a vector type");
9794 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9795 if (! getVShiftImm(Op, ElementBits, Cnt))
9798 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9799 if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9806 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9807 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9808 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9811 // Don't do anything for most intrinsics.
9814 case Intrinsic::arm_neon_vabds:
9815 if (!N->getValueType(0).isInteger())
9817 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9818 N->getOperand(1), N->getOperand(2));
9819 case Intrinsic::arm_neon_vabdu:
9820 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9821 N->getOperand(1), N->getOperand(2));
9823 // Vector shifts: check for immediate versions and lower them.
9824 // Note: This is done during DAG combining instead of DAG legalizing because
9825 // the build_vectors for 64-bit vector element shift counts are generally
9826 // not legal, and it is hard to see their values after they get legalized to
9827 // loads from a constant pool.
9828 case Intrinsic::arm_neon_vshifts:
9829 case Intrinsic::arm_neon_vshiftu:
9830 case Intrinsic::arm_neon_vrshifts:
9831 case Intrinsic::arm_neon_vrshiftu:
9832 case Intrinsic::arm_neon_vrshiftn:
9833 case Intrinsic::arm_neon_vqshifts:
9834 case Intrinsic::arm_neon_vqshiftu:
9835 case Intrinsic::arm_neon_vqshiftsu:
9836 case Intrinsic::arm_neon_vqshiftns:
9837 case Intrinsic::arm_neon_vqshiftnu:
9838 case Intrinsic::arm_neon_vqshiftnsu:
9839 case Intrinsic::arm_neon_vqrshiftns:
9840 case Intrinsic::arm_neon_vqrshiftnu:
9841 case Intrinsic::arm_neon_vqrshiftnsu: {
9842 EVT VT = N->getOperand(1).getValueType();
9844 unsigned VShiftOpc = 0;
9847 case Intrinsic::arm_neon_vshifts:
9848 case Intrinsic::arm_neon_vshiftu:
9849 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9850 VShiftOpc = ARMISD::VSHL;
9853 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9854 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9855 ARMISD::VSHRs : ARMISD::VSHRu);
9860 case Intrinsic::arm_neon_vrshifts:
9861 case Intrinsic::arm_neon_vrshiftu:
9862 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9866 case Intrinsic::arm_neon_vqshifts:
9867 case Intrinsic::arm_neon_vqshiftu:
9868 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9872 case Intrinsic::arm_neon_vqshiftsu:
9873 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9875 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9877 case Intrinsic::arm_neon_vrshiftn:
9878 case Intrinsic::arm_neon_vqshiftns:
9879 case Intrinsic::arm_neon_vqshiftnu:
9880 case Intrinsic::arm_neon_vqshiftnsu:
9881 case Intrinsic::arm_neon_vqrshiftns:
9882 case Intrinsic::arm_neon_vqrshiftnu:
9883 case Intrinsic::arm_neon_vqrshiftnsu:
9884 // Narrowing shifts require an immediate right shift.
9885 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9887 llvm_unreachable("invalid shift count for narrowing vector shift "
9891 llvm_unreachable("unhandled vector shift");
9895 case Intrinsic::arm_neon_vshifts:
9896 case Intrinsic::arm_neon_vshiftu:
9897 // Opcode already set above.
9899 case Intrinsic::arm_neon_vrshifts:
9900 VShiftOpc = ARMISD::VRSHRs; break;
9901 case Intrinsic::arm_neon_vrshiftu:
9902 VShiftOpc = ARMISD::VRSHRu; break;
9903 case Intrinsic::arm_neon_vrshiftn:
9904 VShiftOpc = ARMISD::VRSHRN; break;
9905 case Intrinsic::arm_neon_vqshifts:
9906 VShiftOpc = ARMISD::VQSHLs; break;
9907 case Intrinsic::arm_neon_vqshiftu:
9908 VShiftOpc = ARMISD::VQSHLu; break;
9909 case Intrinsic::arm_neon_vqshiftsu:
9910 VShiftOpc = ARMISD::VQSHLsu; break;
9911 case Intrinsic::arm_neon_vqshiftns:
9912 VShiftOpc = ARMISD::VQSHRNs; break;
9913 case Intrinsic::arm_neon_vqshiftnu:
9914 VShiftOpc = ARMISD::VQSHRNu; break;
9915 case Intrinsic::arm_neon_vqshiftnsu:
9916 VShiftOpc = ARMISD::VQSHRNsu; break;
9917 case Intrinsic::arm_neon_vqrshiftns:
9918 VShiftOpc = ARMISD::VQRSHRNs; break;
9919 case Intrinsic::arm_neon_vqrshiftnu:
9920 VShiftOpc = ARMISD::VQRSHRNu; break;
9921 case Intrinsic::arm_neon_vqrshiftnsu:
9922 VShiftOpc = ARMISD::VQRSHRNsu; break;
9926 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9927 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9930 case Intrinsic::arm_neon_vshiftins: {
9931 EVT VT = N->getOperand(1).getValueType();
9933 unsigned VShiftOpc = 0;
9935 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9936 VShiftOpc = ARMISD::VSLI;
9937 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9938 VShiftOpc = ARMISD::VSRI;
9940 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9944 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9945 N->getOperand(1), N->getOperand(2),
9946 DAG.getConstant(Cnt, dl, MVT::i32));
9949 case Intrinsic::arm_neon_vqrshifts:
9950 case Intrinsic::arm_neon_vqrshiftu:
9951 // No immediate versions of these to check for.
9958 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9959 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9960 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9961 /// vector element shift counts are generally not legal, and it is hard to see
9962 /// their values after they get legalized to loads from a constant pool.
9963 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9964 const ARMSubtarget *ST) {
9965 EVT VT = N->getValueType(0);
9966 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9967 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9968 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9969 SDValue N1 = N->getOperand(1);
9970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9971 SDValue N0 = N->getOperand(0);
9972 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9973 DAG.MaskedValueIsZero(N0.getOperand(0),
9974 APInt::getHighBitsSet(32, 16)))
9975 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9979 // Nothing to be done for scalar shifts.
9980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9981 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9984 assert(ST->hasNEON() && "unexpected vector shift");
9987 switch (N->getOpcode()) {
9988 default: llvm_unreachable("unexpected shift opcode");
9991 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9993 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9994 DAG.getConstant(Cnt, dl, MVT::i32));
10000 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10001 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10002 ARMISD::VSHRs : ARMISD::VSHRu);
10004 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10005 DAG.getConstant(Cnt, dl, MVT::i32));
10011 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10012 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10013 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10014 const ARMSubtarget *ST) {
10015 SDValue N0 = N->getOperand(0);
10017 // Check for sign- and zero-extensions of vector extract operations of 8-
10018 // and 16-bit vector elements. NEON supports these directly. They are
10019 // handled during DAG combining because type legalization will promote them
10020 // to 32-bit types and it is messy to recognize the operations after that.
10021 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10022 SDValue Vec = N0.getOperand(0);
10023 SDValue Lane = N0.getOperand(1);
10024 EVT VT = N->getValueType(0);
10025 EVT EltVT = N0.getValueType();
10026 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10028 if (VT == MVT::i32 &&
10029 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10030 TLI.isTypeLegal(Vec.getValueType()) &&
10031 isa<ConstantSDNode>(Lane)) {
10034 switch (N->getOpcode()) {
10035 default: llvm_unreachable("unexpected opcode");
10036 case ISD::SIGN_EXTEND:
10037 Opc = ARMISD::VGETLANEs;
10039 case ISD::ZERO_EXTEND:
10040 case ISD::ANY_EXTEND:
10041 Opc = ARMISD::VGETLANEu;
10044 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10051 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10052 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10053 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10054 const ARMSubtarget *ST) {
10055 // If the target supports NEON, try to use vmax/vmin instructions for f32
10056 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10057 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10058 // a NaN; only do the transformation when it matches that behavior.
10060 // For now only do this when using NEON for FP operations; if using VFP, it
10061 // is not obvious that the benefit outweighs the cost of switching to the
10063 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10064 N->getValueType(0) != MVT::f32)
10067 SDValue CondLHS = N->getOperand(0);
10068 SDValue CondRHS = N->getOperand(1);
10069 SDValue LHS = N->getOperand(2);
10070 SDValue RHS = N->getOperand(3);
10071 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10073 unsigned Opcode = 0;
10075 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10076 IsReversed = false; // x CC y ? x : y
10077 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10078 IsReversed = true ; // x CC y ? y : x
10092 // If LHS is NaN, an ordered comparison will be false and the result will
10093 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10094 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10095 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10096 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10098 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10099 // will return -0, so vmin can only be used for unsafe math or if one of
10100 // the operands is known to be nonzero.
10101 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10102 !DAG.getTarget().Options.UnsafeFPMath &&
10103 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10105 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10114 // If LHS is NaN, an ordered comparison will be false and the result will
10115 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10116 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10117 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10118 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10120 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10121 // will return +0, so vmax can only be used for unsafe math or if one of
10122 // the operands is known to be nonzero.
10123 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10124 !DAG.getTarget().Options.UnsafeFPMath &&
10125 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10127 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10133 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10136 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10138 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10139 SDValue Cmp = N->getOperand(4);
10140 if (Cmp.getOpcode() != ARMISD::CMPZ)
10141 // Only looking at EQ and NE cases.
10144 EVT VT = N->getValueType(0);
10146 SDValue LHS = Cmp.getOperand(0);
10147 SDValue RHS = Cmp.getOperand(1);
10148 SDValue FalseVal = N->getOperand(0);
10149 SDValue TrueVal = N->getOperand(1);
10150 SDValue ARMcc = N->getOperand(2);
10151 ARMCC::CondCodes CC =
10152 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10170 /// FIXME: Turn this into a target neutral optimization?
10172 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10173 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10174 N->getOperand(3), Cmp);
10175 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10177 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10178 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10179 N->getOperand(3), NewCmp);
10182 if (Res.getNode()) {
10183 APInt KnownZero, KnownOne;
10184 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10185 // Capture demanded bits information that would be otherwise lost.
10186 if (KnownZero == 0xfffffffe)
10187 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10188 DAG.getValueType(MVT::i1));
10189 else if (KnownZero == 0xffffff00)
10190 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10191 DAG.getValueType(MVT::i8));
10192 else if (KnownZero == 0xffff0000)
10193 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10194 DAG.getValueType(MVT::i16));
10200 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10201 DAGCombinerInfo &DCI) const {
10202 switch (N->getOpcode()) {
10204 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10205 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10206 case ISD::SUB: return PerformSUBCombine(N, DCI);
10207 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10208 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10209 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10210 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10211 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10212 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10213 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10214 case ISD::STORE: return PerformSTORECombine(N, DCI);
10215 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10216 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10217 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10218 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10219 case ISD::FP_TO_SINT:
10220 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10221 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10222 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10225 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10226 case ISD::SIGN_EXTEND:
10227 case ISD::ZERO_EXTEND:
10228 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10229 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10230 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10231 case ISD::LOAD: return PerformLOADCombine(N, DCI);
10232 case ARMISD::VLD2DUP:
10233 case ARMISD::VLD3DUP:
10234 case ARMISD::VLD4DUP:
10235 return PerformVLDCombine(N, DCI);
10236 case ARMISD::BUILD_VECTOR:
10237 return PerformARMBUILD_VECTORCombine(N, DCI);
10238 case ISD::INTRINSIC_VOID:
10239 case ISD::INTRINSIC_W_CHAIN:
10240 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10241 case Intrinsic::arm_neon_vld1:
10242 case Intrinsic::arm_neon_vld2:
10243 case Intrinsic::arm_neon_vld3:
10244 case Intrinsic::arm_neon_vld4:
10245 case Intrinsic::arm_neon_vld2lane:
10246 case Intrinsic::arm_neon_vld3lane:
10247 case Intrinsic::arm_neon_vld4lane:
10248 case Intrinsic::arm_neon_vst1:
10249 case Intrinsic::arm_neon_vst2:
10250 case Intrinsic::arm_neon_vst3:
10251 case Intrinsic::arm_neon_vst4:
10252 case Intrinsic::arm_neon_vst2lane:
10253 case Intrinsic::arm_neon_vst3lane:
10254 case Intrinsic::arm_neon_vst4lane:
10255 return PerformVLDCombine(N, DCI);
10263 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10265 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10268 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10271 bool *Fast) const {
10272 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10273 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10275 switch (VT.getSimpleVT().SimpleTy) {
10281 // Unaligned access can use (for example) LRDB, LRDH, LDR
10282 if (AllowsUnaligned) {
10284 *Fast = Subtarget->hasV7Ops();
10291 // For any little-endian targets with neon, we can support unaligned ld/st
10292 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10293 // A big-endian target may also explicitly support unaligned accesses
10294 if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10304 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10305 unsigned AlignCheck) {
10306 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10307 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10310 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10311 unsigned DstAlign, unsigned SrcAlign,
10312 bool IsMemset, bool ZeroMemset,
10314 MachineFunction &MF) const {
10315 const Function *F = MF.getFunction();
10317 // See if we can use NEON instructions for this...
10318 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10319 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10322 (memOpAlign(SrcAlign, DstAlign, 16) ||
10323 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10325 } else if (Size >= 8 &&
10326 (memOpAlign(SrcAlign, DstAlign, 8) ||
10327 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10333 // Lowering to i32/i16 if the size permits.
10336 else if (Size >= 2)
10339 // Let the target-independent logic figure it out.
10343 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10344 if (Val.getOpcode() != ISD::LOAD)
10347 EVT VT1 = Val.getValueType();
10348 if (!VT1.isSimple() || !VT1.isInteger() ||
10349 !VT2.isSimple() || !VT2.isInteger())
10352 switch (VT1.getSimpleVT().SimpleTy) {
10357 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10364 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10365 EVT VT = ExtVal.getValueType();
10367 if (!isTypeLegal(VT))
10370 // Don't create a loadext if we can fold the extension into a wide/long
10372 // If there's more than one user instruction, the loadext is desirable no
10373 // matter what. There can be two uses by the same instruction.
10374 if (ExtVal->use_empty() ||
10375 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10378 SDNode *U = *ExtVal->use_begin();
10379 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10380 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10386 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10387 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10390 if (!isTypeLegal(EVT::getEVT(Ty1)))
10393 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10395 // Assuming the caller doesn't have a zeroext or signext return parameter,
10396 // truncation all the way down to i1 is valid.
10401 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10405 unsigned Scale = 1;
10406 switch (VT.getSimpleVT().SimpleTy) {
10407 default: return false;
10422 if ((V & (Scale - 1)) != 0)
10425 return V == (V & ((1LL << 5) - 1));
10428 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10429 const ARMSubtarget *Subtarget) {
10430 bool isNeg = false;
10436 switch (VT.getSimpleVT().SimpleTy) {
10437 default: return false;
10442 // + imm12 or - imm8
10444 return V == (V & ((1LL << 8) - 1));
10445 return V == (V & ((1LL << 12) - 1));
10448 // Same as ARM mode. FIXME: NEON?
10449 if (!Subtarget->hasVFP2())
10454 return V == (V & ((1LL << 8) - 1));
10458 /// isLegalAddressImmediate - Return true if the integer value can be used
10459 /// as the offset of the target addressing mode for load / store of the
10461 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10462 const ARMSubtarget *Subtarget) {
10466 if (!VT.isSimple())
10469 if (Subtarget->isThumb1Only())
10470 return isLegalT1AddressImmediate(V, VT);
10471 else if (Subtarget->isThumb2())
10472 return isLegalT2AddressImmediate(V, VT, Subtarget);
10477 switch (VT.getSimpleVT().SimpleTy) {
10478 default: return false;
10483 return V == (V & ((1LL << 12) - 1));
10486 return V == (V & ((1LL << 8) - 1));
10489 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10494 return V == (V & ((1LL << 8) - 1));
10498 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10500 int Scale = AM.Scale;
10504 switch (VT.getSimpleVT().SimpleTy) {
10505 default: return false;
10513 Scale = Scale & ~1;
10514 return Scale == 2 || Scale == 4 || Scale == 8;
10517 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10521 // Note, we allow "void" uses (basically, uses that aren't loads or
10522 // stores), because arm allows folding a scale into many arithmetic
10523 // operations. This should be made more precise and revisited later.
10525 // Allow r << imm, but the imm has to be a multiple of two.
10526 if (Scale & 1) return false;
10527 return isPowerOf2_32(Scale);
10531 /// isLegalAddressingMode - Return true if the addressing mode represented
10532 /// by AM is legal for this target, for a load/store of the specified type.
10533 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10534 const AddrMode &AM, Type *Ty,
10535 unsigned AS) const {
10536 EVT VT = getValueType(DL, Ty, true);
10537 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10540 // Can never fold addr of global into load/store.
10544 switch (AM.Scale) {
10545 case 0: // no scale reg, must be "r+i" or "r", or "i".
10548 if (Subtarget->isThumb1Only())
10552 // ARM doesn't support any R+R*scale+imm addr modes.
10556 if (!VT.isSimple())
10559 if (Subtarget->isThumb2())
10560 return isLegalT2ScaledAddressingMode(AM, VT);
10562 int Scale = AM.Scale;
10563 switch (VT.getSimpleVT().SimpleTy) {
10564 default: return false;
10568 if (Scale < 0) Scale = -Scale;
10572 return isPowerOf2_32(Scale & ~1);
10576 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10581 // Note, we allow "void" uses (basically, uses that aren't loads or
10582 // stores), because arm allows folding a scale into many arithmetic
10583 // operations. This should be made more precise and revisited later.
10585 // Allow r << imm, but the imm has to be a multiple of two.
10586 if (Scale & 1) return false;
10587 return isPowerOf2_32(Scale);
10593 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10594 /// icmp immediate, that is the target has icmp instructions which can compare
10595 /// a register against the immediate without having to materialize the
10596 /// immediate into a register.
10597 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10598 // Thumb2 and ARM modes can use cmn for negative immediates.
10599 if (!Subtarget->isThumb())
10600 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10601 if (Subtarget->isThumb2())
10602 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10603 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10604 return Imm >= 0 && Imm <= 255;
10607 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10608 /// *or sub* immediate, that is the target has add or sub instructions which can
10609 /// add a register with the immediate without having to materialize the
10610 /// immediate into a register.
10611 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10612 // Same encoding for add/sub, just flip the sign.
10613 int64_t AbsImm = std::abs(Imm);
10614 if (!Subtarget->isThumb())
10615 return ARM_AM::getSOImmVal(AbsImm) != -1;
10616 if (Subtarget->isThumb2())
10617 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10618 // Thumb1 only has 8-bit unsigned immediate.
10619 return AbsImm >= 0 && AbsImm <= 255;
10622 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10623 bool isSEXTLoad, SDValue &Base,
10624 SDValue &Offset, bool &isInc,
10625 SelectionDAG &DAG) {
10626 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10629 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10630 // AddressingMode 3
10631 Base = Ptr->getOperand(0);
10632 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10633 int RHSC = (int)RHS->getZExtValue();
10634 if (RHSC < 0 && RHSC > -256) {
10635 assert(Ptr->getOpcode() == ISD::ADD);
10637 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10641 isInc = (Ptr->getOpcode() == ISD::ADD);
10642 Offset = Ptr->getOperand(1);
10644 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10645 // AddressingMode 2
10646 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10647 int RHSC = (int)RHS->getZExtValue();
10648 if (RHSC < 0 && RHSC > -0x1000) {
10649 assert(Ptr->getOpcode() == ISD::ADD);
10651 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10652 Base = Ptr->getOperand(0);
10657 if (Ptr->getOpcode() == ISD::ADD) {
10659 ARM_AM::ShiftOpc ShOpcVal=
10660 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10661 if (ShOpcVal != ARM_AM::no_shift) {
10662 Base = Ptr->getOperand(1);
10663 Offset = Ptr->getOperand(0);
10665 Base = Ptr->getOperand(0);
10666 Offset = Ptr->getOperand(1);
10671 isInc = (Ptr->getOpcode() == ISD::ADD);
10672 Base = Ptr->getOperand(0);
10673 Offset = Ptr->getOperand(1);
10677 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10681 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10682 bool isSEXTLoad, SDValue &Base,
10683 SDValue &Offset, bool &isInc,
10684 SelectionDAG &DAG) {
10685 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10688 Base = Ptr->getOperand(0);
10689 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10690 int RHSC = (int)RHS->getZExtValue();
10691 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10692 assert(Ptr->getOpcode() == ISD::ADD);
10694 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10696 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10697 isInc = Ptr->getOpcode() == ISD::ADD;
10698 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10706 /// getPreIndexedAddressParts - returns true by value, base pointer and
10707 /// offset pointer and addressing mode by reference if the node's address
10708 /// can be legally represented as pre-indexed load / store address.
10710 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10712 ISD::MemIndexedMode &AM,
10713 SelectionDAG &DAG) const {
10714 if (Subtarget->isThumb1Only())
10719 bool isSEXTLoad = false;
10720 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10721 Ptr = LD->getBasePtr();
10722 VT = LD->getMemoryVT();
10723 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10724 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10725 Ptr = ST->getBasePtr();
10726 VT = ST->getMemoryVT();
10731 bool isLegal = false;
10732 if (Subtarget->isThumb2())
10733 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10734 Offset, isInc, DAG);
10736 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10737 Offset, isInc, DAG);
10741 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10745 /// getPostIndexedAddressParts - returns true by value, base pointer and
10746 /// offset pointer and addressing mode by reference if this node can be
10747 /// combined with a load / store to form a post-indexed load / store.
10748 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10751 ISD::MemIndexedMode &AM,
10752 SelectionDAG &DAG) const {
10753 if (Subtarget->isThumb1Only())
10758 bool isSEXTLoad = false;
10759 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10760 VT = LD->getMemoryVT();
10761 Ptr = LD->getBasePtr();
10762 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10763 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10764 VT = ST->getMemoryVT();
10765 Ptr = ST->getBasePtr();
10770 bool isLegal = false;
10771 if (Subtarget->isThumb2())
10772 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10775 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10781 // Swap base ptr and offset to catch more post-index load / store when
10782 // it's legal. In Thumb2 mode, offset must be an immediate.
10783 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10784 !Subtarget->isThumb2())
10785 std::swap(Base, Offset);
10787 // Post-indexed load / store update the base pointer.
10792 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10796 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10799 const SelectionDAG &DAG,
10800 unsigned Depth) const {
10801 unsigned BitWidth = KnownOne.getBitWidth();
10802 KnownZero = KnownOne = APInt(BitWidth, 0);
10803 switch (Op.getOpcode()) {
10809 // These nodes' second result is a boolean
10810 if (Op.getResNo() == 0)
10812 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10814 case ARMISD::CMOV: {
10815 // Bits are known zero/one if known on the LHS and RHS.
10816 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10817 if (KnownZero == 0 && KnownOne == 0) return;
10819 APInt KnownZeroRHS, KnownOneRHS;
10820 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10821 KnownZero &= KnownZeroRHS;
10822 KnownOne &= KnownOneRHS;
10825 case ISD::INTRINSIC_W_CHAIN: {
10826 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10827 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10830 case Intrinsic::arm_ldaex:
10831 case Intrinsic::arm_ldrex: {
10832 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10833 unsigned MemBits = VT.getScalarType().getSizeInBits();
10834 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10842 //===----------------------------------------------------------------------===//
10843 // ARM Inline Assembly Support
10844 //===----------------------------------------------------------------------===//
10846 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10847 // Looking for "rev" which is V6+.
10848 if (!Subtarget->hasV6Ops())
10851 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10852 std::string AsmStr = IA->getAsmString();
10853 SmallVector<StringRef, 4> AsmPieces;
10854 SplitString(AsmStr, AsmPieces, ";\n");
10856 switch (AsmPieces.size()) {
10857 default: return false;
10859 AsmStr = AsmPieces[0];
10861 SplitString(AsmStr, AsmPieces, " \t,");
10864 if (AsmPieces.size() == 3 &&
10865 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10866 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10867 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10868 if (Ty && Ty->getBitWidth() == 32)
10869 return IntrinsicLowering::LowerToByteSwap(CI);
10877 /// getConstraintType - Given a constraint letter, return the type of
10878 /// constraint it is for this target.
10879 ARMTargetLowering::ConstraintType
10880 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10881 if (Constraint.size() == 1) {
10882 switch (Constraint[0]) {
10884 case 'l': return C_RegisterClass;
10885 case 'w': return C_RegisterClass;
10886 case 'h': return C_RegisterClass;
10887 case 'x': return C_RegisterClass;
10888 case 't': return C_RegisterClass;
10889 case 'j': return C_Other; // Constant for movw.
10890 // An address with a single base register. Due to the way we
10891 // currently handle addresses it is the same as an 'r' memory constraint.
10892 case 'Q': return C_Memory;
10894 } else if (Constraint.size() == 2) {
10895 switch (Constraint[0]) {
10897 // All 'U+' constraints are addresses.
10898 case 'U': return C_Memory;
10901 return TargetLowering::getConstraintType(Constraint);
10904 /// Examine constraint type and operand type and determine a weight value.
10905 /// This object must already have been set up with the operand type
10906 /// and the current alternative constraint selected.
10907 TargetLowering::ConstraintWeight
10908 ARMTargetLowering::getSingleConstraintMatchWeight(
10909 AsmOperandInfo &info, const char *constraint) const {
10910 ConstraintWeight weight = CW_Invalid;
10911 Value *CallOperandVal = info.CallOperandVal;
10912 // If we don't have a value, we can't do a match,
10913 // but allow it at the lowest weight.
10914 if (!CallOperandVal)
10916 Type *type = CallOperandVal->getType();
10917 // Look at the constraint type.
10918 switch (*constraint) {
10920 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10923 if (type->isIntegerTy()) {
10924 if (Subtarget->isThumb())
10925 weight = CW_SpecificReg;
10927 weight = CW_Register;
10931 if (type->isFloatingPointTy())
10932 weight = CW_Register;
10938 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10939 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
10940 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
10941 if (Constraint.size() == 1) {
10942 // GCC ARM Constraint Letters
10943 switch (Constraint[0]) {
10944 case 'l': // Low regs or general regs.
10945 if (Subtarget->isThumb())
10946 return RCPair(0U, &ARM::tGPRRegClass);
10947 return RCPair(0U, &ARM::GPRRegClass);
10948 case 'h': // High regs or no regs.
10949 if (Subtarget->isThumb())
10950 return RCPair(0U, &ARM::hGPRRegClass);
10953 if (Subtarget->isThumb1Only())
10954 return RCPair(0U, &ARM::tGPRRegClass);
10955 return RCPair(0U, &ARM::GPRRegClass);
10957 if (VT == MVT::Other)
10959 if (VT == MVT::f32)
10960 return RCPair(0U, &ARM::SPRRegClass);
10961 if (VT.getSizeInBits() == 64)
10962 return RCPair(0U, &ARM::DPRRegClass);
10963 if (VT.getSizeInBits() == 128)
10964 return RCPair(0U, &ARM::QPRRegClass);
10967 if (VT == MVT::Other)
10969 if (VT == MVT::f32)
10970 return RCPair(0U, &ARM::SPR_8RegClass);
10971 if (VT.getSizeInBits() == 64)
10972 return RCPair(0U, &ARM::DPR_8RegClass);
10973 if (VT.getSizeInBits() == 128)
10974 return RCPair(0U, &ARM::QPR_8RegClass);
10977 if (VT == MVT::f32)
10978 return RCPair(0U, &ARM::SPRRegClass);
10982 if (StringRef("{cc}").equals_lower(Constraint))
10983 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10985 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10988 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10989 /// vector. If it is invalid, don't add anything to Ops.
10990 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10991 std::string &Constraint,
10992 std::vector<SDValue>&Ops,
10993 SelectionDAG &DAG) const {
10996 // Currently only support length 1 constraints.
10997 if (Constraint.length() != 1) return;
10999 char ConstraintLetter = Constraint[0];
11000 switch (ConstraintLetter) {
11003 case 'I': case 'J': case 'K': case 'L':
11004 case 'M': case 'N': case 'O':
11005 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11009 int64_t CVal64 = C->getSExtValue();
11010 int CVal = (int) CVal64;
11011 // None of these constraints allow values larger than 32 bits. Check
11012 // that the value fits in an int.
11013 if (CVal != CVal64)
11016 switch (ConstraintLetter) {
11018 // Constant suitable for movw, must be between 0 and
11020 if (Subtarget->hasV6T2Ops())
11021 if (CVal >= 0 && CVal <= 65535)
11025 if (Subtarget->isThumb1Only()) {
11026 // This must be a constant between 0 and 255, for ADD
11028 if (CVal >= 0 && CVal <= 255)
11030 } else if (Subtarget->isThumb2()) {
11031 // A constant that can be used as an immediate value in a
11032 // data-processing instruction.
11033 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11036 // A constant that can be used as an immediate value in a
11037 // data-processing instruction.
11038 if (ARM_AM::getSOImmVal(CVal) != -1)
11044 if (Subtarget->isThumb()) { // FIXME thumb2
11045 // This must be a constant between -255 and -1, for negated ADD
11046 // immediates. This can be used in GCC with an "n" modifier that
11047 // prints the negated value, for use with SUB instructions. It is
11048 // not useful otherwise but is implemented for compatibility.
11049 if (CVal >= -255 && CVal <= -1)
11052 // This must be a constant between -4095 and 4095. It is not clear
11053 // what this constraint is intended for. Implemented for
11054 // compatibility with GCC.
11055 if (CVal >= -4095 && CVal <= 4095)
11061 if (Subtarget->isThumb1Only()) {
11062 // A 32-bit value where only one byte has a nonzero value. Exclude
11063 // zero to match GCC. This constraint is used by GCC internally for
11064 // constants that can be loaded with a move/shift combination.
11065 // It is not useful otherwise but is implemented for compatibility.
11066 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11068 } else if (Subtarget->isThumb2()) {
11069 // A constant whose bitwise inverse can be used as an immediate
11070 // value in a data-processing instruction. This can be used in GCC
11071 // with a "B" modifier that prints the inverted value, for use with
11072 // BIC and MVN instructions. It is not useful otherwise but is
11073 // implemented for compatibility.
11074 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11077 // A constant whose bitwise inverse can be used as an immediate
11078 // value in a data-processing instruction. This can be used in GCC
11079 // with a "B" modifier that prints the inverted value, for use with
11080 // BIC and MVN instructions. It is not useful otherwise but is
11081 // implemented for compatibility.
11082 if (ARM_AM::getSOImmVal(~CVal) != -1)
11088 if (Subtarget->isThumb1Only()) {
11089 // This must be a constant between -7 and 7,
11090 // for 3-operand ADD/SUB immediate instructions.
11091 if (CVal >= -7 && CVal < 7)
11093 } else if (Subtarget->isThumb2()) {
11094 // A constant whose negation can be used as an immediate value in a
11095 // data-processing instruction. This can be used in GCC with an "n"
11096 // modifier that prints the negated value, for use with SUB
11097 // instructions. It is not useful otherwise but is implemented for
11099 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11102 // A constant whose negation can be used as an immediate value in a
11103 // data-processing instruction. This can be used in GCC with an "n"
11104 // modifier that prints the negated value, for use with SUB
11105 // instructions. It is not useful otherwise but is implemented for
11107 if (ARM_AM::getSOImmVal(-CVal) != -1)
11113 if (Subtarget->isThumb()) { // FIXME thumb2
11114 // This must be a multiple of 4 between 0 and 1020, for
11115 // ADD sp + immediate.
11116 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11119 // A power of two or a constant between 0 and 32. This is used in
11120 // GCC for the shift amount on shifted register operands, but it is
11121 // useful in general for any shift amounts.
11122 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11128 if (Subtarget->isThumb()) { // FIXME thumb2
11129 // This must be a constant between 0 and 31, for shift amounts.
11130 if (CVal >= 0 && CVal <= 31)
11136 if (Subtarget->isThumb()) { // FIXME thumb2
11137 // This must be a multiple of 4 between -508 and 508, for
11138 // ADD/SUB sp = sp + immediate.
11139 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11144 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11148 if (Result.getNode()) {
11149 Ops.push_back(Result);
11152 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11155 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11156 assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11157 "Register-based DivRem lowering only");
11158 unsigned Opcode = Op->getOpcode();
11159 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11160 "Invalid opcode for Div/Rem lowering");
11161 bool isSigned = (Opcode == ISD::SDIVREM);
11162 EVT VT = Op->getValueType(0);
11163 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11166 switch (VT.getSimpleVT().SimpleTy) {
11167 default: llvm_unreachable("Unexpected request for libcall!");
11168 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11169 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11170 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11171 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11174 SDValue InChain = DAG.getEntryNode();
11176 TargetLowering::ArgListTy Args;
11177 TargetLowering::ArgListEntry Entry;
11178 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11179 EVT ArgVT = Op->getOperand(i).getValueType();
11180 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11181 Entry.Node = Op->getOperand(i);
11183 Entry.isSExt = isSigned;
11184 Entry.isZExt = !isSigned;
11185 Args.push_back(Entry);
11188 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11189 getPointerTy(DAG.getDataLayout()));
11191 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11194 TargetLowering::CallLoweringInfo CLI(DAG);
11195 CLI.setDebugLoc(dl).setChain(InChain)
11196 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11197 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11199 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11200 return CallInfo.first;
11204 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11205 assert(Subtarget->isTargetWindows() && "unsupported target platform");
11209 SDValue Chain = Op.getOperand(0);
11210 SDValue Size = Op.getOperand(1);
11212 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11213 DAG.getConstant(2, DL, MVT::i32));
11216 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11217 Flag = Chain.getValue(1);
11219 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11220 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11222 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11223 Chain = NewSP.getValue(1);
11225 SDValue Ops[2] = { NewSP, Chain };
11226 return DAG.getMergeValues(Ops, DL);
11229 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11230 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11231 "Unexpected type for custom-lowering FP_EXTEND");
11234 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11236 SDValue SrcVal = Op.getOperand(0);
11237 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11238 /*isSigned*/ false, SDLoc(Op)).first;
11241 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11242 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11243 Subtarget->isFPOnlySP() &&
11244 "Unexpected type for custom-lowering FP_ROUND");
11247 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11249 SDValue SrcVal = Op.getOperand(0);
11250 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11251 /*isSigned*/ false, SDLoc(Op)).first;
11255 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11256 // The ARM target isn't yet aware of offsets.
11260 bool ARM::isBitFieldInvertedMask(unsigned v) {
11261 if (v == 0xffffffff)
11264 // there can be 1's on either or both "outsides", all the "inside"
11265 // bits must be 0's
11266 return isShiftedMask_32(~v);
11269 /// isFPImmLegal - Returns true if the target can instruction select the
11270 /// specified FP immediate natively. If false, the legalizer will
11271 /// materialize the FP immediate as a load from a constant pool.
11272 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11273 if (!Subtarget->hasVFP3())
11275 if (VT == MVT::f32)
11276 return ARM_AM::getFP32Imm(Imm) != -1;
11277 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11278 return ARM_AM::getFP64Imm(Imm) != -1;
11282 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11283 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11284 /// specified in the intrinsic calls.
11285 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11287 unsigned Intrinsic) const {
11288 switch (Intrinsic) {
11289 case Intrinsic::arm_neon_vld1:
11290 case Intrinsic::arm_neon_vld2:
11291 case Intrinsic::arm_neon_vld3:
11292 case Intrinsic::arm_neon_vld4:
11293 case Intrinsic::arm_neon_vld2lane:
11294 case Intrinsic::arm_neon_vld3lane:
11295 case Intrinsic::arm_neon_vld4lane: {
11296 Info.opc = ISD::INTRINSIC_W_CHAIN;
11297 // Conservatively set memVT to the entire set of vectors loaded.
11298 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11299 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11300 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11301 Info.ptrVal = I.getArgOperand(0);
11303 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11304 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11305 Info.vol = false; // volatile loads with NEON intrinsics not supported
11306 Info.readMem = true;
11307 Info.writeMem = false;
11310 case Intrinsic::arm_neon_vst1:
11311 case Intrinsic::arm_neon_vst2:
11312 case Intrinsic::arm_neon_vst3:
11313 case Intrinsic::arm_neon_vst4:
11314 case Intrinsic::arm_neon_vst2lane:
11315 case Intrinsic::arm_neon_vst3lane:
11316 case Intrinsic::arm_neon_vst4lane: {
11317 Info.opc = ISD::INTRINSIC_VOID;
11318 // Conservatively set memVT to the entire set of vectors stored.
11319 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11320 unsigned NumElts = 0;
11321 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11322 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11323 if (!ArgTy->isVectorTy())
11325 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11327 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11328 Info.ptrVal = I.getArgOperand(0);
11330 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11331 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11332 Info.vol = false; // volatile stores with NEON intrinsics not supported
11333 Info.readMem = false;
11334 Info.writeMem = true;
11337 case Intrinsic::arm_ldaex:
11338 case Intrinsic::arm_ldrex: {
11339 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11340 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11341 Info.opc = ISD::INTRINSIC_W_CHAIN;
11342 Info.memVT = MVT::getVT(PtrTy->getElementType());
11343 Info.ptrVal = I.getArgOperand(0);
11345 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11347 Info.readMem = true;
11348 Info.writeMem = false;
11351 case Intrinsic::arm_stlex:
11352 case Intrinsic::arm_strex: {
11353 auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11354 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11355 Info.opc = ISD::INTRINSIC_W_CHAIN;
11356 Info.memVT = MVT::getVT(PtrTy->getElementType());
11357 Info.ptrVal = I.getArgOperand(1);
11359 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11361 Info.readMem = false;
11362 Info.writeMem = true;
11365 case Intrinsic::arm_stlexd:
11366 case Intrinsic::arm_strexd: {
11367 Info.opc = ISD::INTRINSIC_W_CHAIN;
11368 Info.memVT = MVT::i64;
11369 Info.ptrVal = I.getArgOperand(2);
11373 Info.readMem = false;
11374 Info.writeMem = true;
11377 case Intrinsic::arm_ldaexd:
11378 case Intrinsic::arm_ldrexd: {
11379 Info.opc = ISD::INTRINSIC_W_CHAIN;
11380 Info.memVT = MVT::i64;
11381 Info.ptrVal = I.getArgOperand(0);
11385 Info.readMem = true;
11386 Info.writeMem = false;
11396 /// \brief Returns true if it is beneficial to convert a load of a constant
11397 /// to just the constant itself.
11398 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11400 assert(Ty->isIntegerTy());
11402 unsigned Bits = Ty->getPrimitiveSizeInBits();
11403 if (Bits == 0 || Bits > 32)
11408 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11410 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11411 ARM_MB::MemBOpt Domain) const {
11412 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11414 // First, if the target has no DMB, see what fallback we can use.
11415 if (!Subtarget->hasDataBarrier()) {
11416 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11417 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11419 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11420 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11421 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11422 Builder.getInt32(0), Builder.getInt32(7),
11423 Builder.getInt32(10), Builder.getInt32(5)};
11424 return Builder.CreateCall(MCR, args);
11426 // Instead of using barriers, atomic accesses on these subtargets use
11428 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11431 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11432 // Only a full system barrier exists in the M-class architectures.
11433 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11434 Constant *CDomain = Builder.getInt32(Domain);
11435 return Builder.CreateCall(DMB, CDomain);
11439 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11440 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11441 AtomicOrdering Ord, bool IsStore,
11442 bool IsLoad) const {
11443 if (!getInsertFencesForAtomic())
11449 llvm_unreachable("Invalid fence: unordered/non-atomic");
11452 return nullptr; // Nothing to do
11453 case SequentiallyConsistent:
11455 return nullptr; // Nothing to do
11458 case AcquireRelease:
11459 if (Subtarget->isSwift())
11460 return makeDMB(Builder, ARM_MB::ISHST);
11461 // FIXME: add a comment with a link to documentation justifying this.
11463 return makeDMB(Builder, ARM_MB::ISH);
11465 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11468 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11469 AtomicOrdering Ord, bool IsStore,
11470 bool IsLoad) const {
11471 if (!getInsertFencesForAtomic())
11477 llvm_unreachable("Invalid fence: unordered/not-atomic");
11480 return nullptr; // Nothing to do
11482 case AcquireRelease:
11483 case SequentiallyConsistent:
11484 return makeDMB(Builder, ARM_MB::ISH);
11486 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11489 // Loads and stores less than 64-bits are already atomic; ones above that
11490 // are doomed anyway, so defer to the default libcall and blame the OS when
11491 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11492 // anything for those.
11493 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11494 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11495 return (Size == 64) && !Subtarget->isMClass();
11498 // Loads and stores less than 64-bits are already atomic; ones above that
11499 // are doomed anyway, so defer to the default libcall and blame the OS when
11500 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11501 // anything for those.
11502 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11503 // guarantee, see DDI0406C ARM architecture reference manual,
11504 // sections A8.8.72-74 LDRD)
11505 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11506 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11507 return (Size == 64) && !Subtarget->isMClass();
11510 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11511 // and up to 64 bits on the non-M profiles
11512 TargetLoweringBase::AtomicRMWExpansionKind
11513 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11514 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11515 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11516 ? AtomicRMWExpansionKind::LLSC
11517 : AtomicRMWExpansionKind::None;
11520 // This has so far only been implemented for MachO.
11521 bool ARMTargetLowering::useLoadStackGuardNode() const {
11522 return Subtarget->isTargetMachO();
11525 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11526 unsigned &Cost) const {
11527 // If we do not have NEON, vector types are not natively supported.
11528 if (!Subtarget->hasNEON())
11531 // Floating point values and vector values map to the same register file.
11532 // Therefore, althought we could do a store extract of a vector type, this is
11533 // better to leave at float as we have more freedom in the addressing mode for
11535 if (VectorTy->isFPOrFPVectorTy())
11538 // If the index is unknown at compile time, this is very expensive to lower
11539 // and it is not possible to combine the store with the extract.
11540 if (!isa<ConstantInt>(Idx))
11543 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11544 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11545 // We can do a store + vector extract on any vector that fits perfectly in a D
11547 if (BitWidth == 64 || BitWidth == 128) {
11554 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11555 AtomicOrdering Ord) const {
11556 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11557 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11558 bool IsAcquire = isAtLeastAcquire(Ord);
11560 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11561 // intrinsic must return {i32, i32} and we have to recombine them into a
11562 // single i64 here.
11563 if (ValTy->getPrimitiveSizeInBits() == 64) {
11564 Intrinsic::ID Int =
11565 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11566 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11568 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11569 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11571 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11572 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11573 if (!Subtarget->isLittle())
11574 std::swap (Lo, Hi);
11575 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11576 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11577 return Builder.CreateOr(
11578 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11581 Type *Tys[] = { Addr->getType() };
11582 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11583 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11585 return Builder.CreateTruncOrBitCast(
11586 Builder.CreateCall(Ldrex, Addr),
11587 cast<PointerType>(Addr->getType())->getElementType());
11590 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11592 AtomicOrdering Ord) const {
11593 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11594 bool IsRelease = isAtLeastRelease(Ord);
11596 // Since the intrinsics must have legal type, the i64 intrinsics take two
11597 // parameters: "i32, i32". We must marshal Val into the appropriate form
11598 // before the call.
11599 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11600 Intrinsic::ID Int =
11601 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11602 Function *Strex = Intrinsic::getDeclaration(M, Int);
11603 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11605 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11606 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11607 if (!Subtarget->isLittle())
11608 std::swap (Lo, Hi);
11609 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11610 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11613 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11614 Type *Tys[] = { Addr->getType() };
11615 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11617 return Builder.CreateCall(
11618 Strex, {Builder.CreateZExtOrBitCast(
11619 Val, Strex->getFunctionType()->getParamType(0)),
11623 /// \brief Lower an interleaved load into a vldN intrinsic.
11625 /// E.g. Lower an interleaved load (Factor = 2):
11626 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11627 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
11628 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
11631 /// %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11632 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11633 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11634 bool ARMTargetLowering::lowerInterleavedLoad(
11635 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11636 ArrayRef<unsigned> Indices, unsigned Factor) const {
11637 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11638 "Invalid interleave factor");
11639 assert(!Shuffles.empty() && "Empty shufflevector input");
11640 assert(Shuffles.size() == Indices.size() &&
11641 "Unmatched number of shufflevectors and indices");
11643 VectorType *VecTy = Shuffles[0]->getType();
11644 Type *EltTy = VecTy->getVectorElementType();
11646 const DataLayout &DL = LI->getModule()->getDataLayout();
11647 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11648 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11650 // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11651 // support i64/f64 element).
11652 if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11655 // A pointer vector can not be the return type of the ldN intrinsics. Need to
11656 // load integer vectors first and then convert to pointer vectors.
11657 if (EltTy->isPointerTy())
11659 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11661 static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11662 Intrinsic::arm_neon_vld3,
11663 Intrinsic::arm_neon_vld4};
11665 Function *VldnFunc =
11666 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11668 IRBuilder<> Builder(LI);
11669 SmallVector<Value *, 2> Ops;
11671 Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11672 Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11673 Ops.push_back(Builder.getInt32(LI->getAlignment()));
11675 CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11677 // Replace uses of each shufflevector with the corresponding vector loaded
11679 for (unsigned i = 0; i < Shuffles.size(); i++) {
11680 ShuffleVectorInst *SV = Shuffles[i];
11681 unsigned Index = Indices[i];
11683 Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11685 // Convert the integer vector to pointer vector if the element is pointer.
11686 if (EltTy->isPointerTy())
11687 SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11689 SV->replaceAllUsesWith(SubVec);
11695 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11697 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11698 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11699 unsigned NumElts) {
11700 SmallVector<Constant *, 16> Mask;
11701 for (unsigned i = 0; i < NumElts; i++)
11702 Mask.push_back(Builder.getInt32(Start + i));
11704 return ConstantVector::get(Mask);
11707 /// \brief Lower an interleaved store into a vstN intrinsic.
11709 /// E.g. Lower an interleaved store (Factor = 3):
11710 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11711 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11712 /// store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11715 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11716 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11717 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11718 /// call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11720 /// Note that the new shufflevectors will be removed and we'll only generate one
11721 /// vst3 instruction in CodeGen.
11722 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11723 ShuffleVectorInst *SVI,
11724 unsigned Factor) const {
11725 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11726 "Invalid interleave factor");
11728 VectorType *VecTy = SVI->getType();
11729 assert(VecTy->getVectorNumElements() % Factor == 0 &&
11730 "Invalid interleaved store");
11732 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11733 Type *EltTy = VecTy->getVectorElementType();
11734 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11736 const DataLayout &DL = SI->getModule()->getDataLayout();
11737 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11738 bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11740 // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11741 // doesn't support i64/f64 element).
11742 if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11745 Value *Op0 = SVI->getOperand(0);
11746 Value *Op1 = SVI->getOperand(1);
11747 IRBuilder<> Builder(SI);
11749 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11750 // vectors to integer vectors.
11751 if (EltTy->isPointerTy()) {
11752 Type *IntTy = DL.getIntPtrType(EltTy);
11754 // Convert to the corresponding integer vector.
11756 VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11757 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11758 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11760 SubVecTy = VectorType::get(IntTy, NumSubElts);
11763 static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11764 Intrinsic::arm_neon_vst3,
11765 Intrinsic::arm_neon_vst4};
11766 Function *VstNFunc = Intrinsic::getDeclaration(
11767 SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11769 SmallVector<Value *, 6> Ops;
11771 Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11772 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11774 // Split the shufflevector operands into sub vectors for the new vstN call.
11775 for (unsigned i = 0; i < Factor; i++)
11776 Ops.push_back(Builder.CreateShuffleVector(
11777 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11779 Ops.push_back(Builder.getInt32(SI->getAlignment()));
11780 Builder.CreateCall(VstNFunc, Ops);
11792 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11793 uint64_t &Members) {
11794 if (auto *ST = dyn_cast<StructType>(Ty)) {
11795 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11796 uint64_t SubMembers = 0;
11797 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11799 Members += SubMembers;
11801 } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11802 uint64_t SubMembers = 0;
11803 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11805 Members += SubMembers * AT->getNumElements();
11806 } else if (Ty->isFloatTy()) {
11807 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11811 } else if (Ty->isDoubleTy()) {
11812 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11816 } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11823 return VT->getBitWidth() == 64;
11825 return VT->getBitWidth() == 128;
11827 switch (VT->getBitWidth()) {
11840 return (Members > 0 && Members <= 4);
11843 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11844 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11845 /// passing according to AAPCS rules.
11846 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11847 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11848 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11849 CallingConv::ARM_AAPCS_VFP)
11852 HABaseType Base = HA_UNKNOWN;
11853 uint64_t Members = 0;
11854 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11855 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11857 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11858 return IsHA || IsIntArray;