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/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75 : CCState(CC, isVarArg, MF, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159 if (TT.isOSBinFormatMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TT.isOSWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168 Subtarget = &TM.getSubtarget<ARMSubtarget>();
169 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 if (Subtarget->isTargetMachO()) {
175 // Uses VFP for Thumb libfuncs if available.
176 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178 // Single-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184 // Double-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190 // Single-precision comparisons.
191 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
198 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
200 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
209 // Double-precision comparisons.
210 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
217 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
219 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
228 // Floating-point to integer conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236 // Conversions between floating types.
237 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
240 // Integer to floating-point conversions.
241 // i64 conversions are done via library routines even when generating VFP
242 // instructions, so use the same ones.
243 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244 // e.g., __floatunsidf vs. __floatunssidfvfp.
245 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
252 // These libcalls are not available in 32-bit.
253 setLibcallName(RTLIB::SHL_I128, nullptr);
254 setLibcallName(RTLIB::SRL_I128, nullptr);
255 setLibcallName(RTLIB::SRA_I128, nullptr);
257 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258 !Subtarget->isTargetWindows()) {
259 static const struct {
260 const RTLIB::Libcall Op;
261 const char * const Name;
262 const CallingConv::ID CC;
263 const ISD::CondCode Cond;
265 // Double-precision floating-point arithmetic helper functions
266 // RTABI chapter 4.1.2, Table 2
267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 // FIXME: double __aeabi_drsub(double x, double y) (rsub)
271 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 // FIXME: void __aeabi_cdcmpeq(double, double)
276 // FIXME: void __aeabi_cdcmple(double, double)
277 // FIXME: void __aeabi_cdrcmple(double, double)
278 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
280 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
283 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
284 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
285 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 // Single-precision floating-point arithmetic helper functions
288 // RTABI chapter 4.1.2, Table 4
289 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
292 // FIXME: void __aeabi_frsub(float x, float y)
293 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295 // Single-precision floating-point comparison helper functions
296 // RTABI chapter 4.1.2, Table 5
297 // FIXME: void __aeabi_cfcmpeq(float, float)
298 // FIXME: void __aeabi_cfcmple(float, float)
299 // FIXME: void __aeabi_cfrcmple(float, float)
300 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
301 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
302 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
303 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
304 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
305 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
306 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
307 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
309 // Floating-point to integer conversions.
310 // RTABI chapter 4.1.2, Table 6
311 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 // Conversions between floating types.
321 // RTABI chapter 4.1.2, Table 7
322 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 // FIXME: float __aeabi_f2f(short)
325 // FIXME: float __aeabi_h2f_alt(short)
326 // FIXME: short __aeabi_f2h(float)
327 // FIXME: short __aeabi_f2h_alt(float)
328 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // FIXME: short __aeabi_d2h_alt(double)
331 // Integer to floating-point conversions.
332 // RTABI chapter 4.1.2, Table 8
333 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 // Long long helper functions
343 // RTABI chapter 4.2, Table 9
344 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 // FIXME: __aeabi_ldivmod is SDIVREM not SDIV; we should custom lower this
346 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 // FIXME: __aeabi_uldivmod is UDIVREM not UDIV; we should custom lower this
349 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 // FIXME: int __aeabi_lcmp(long long, long long)
355 // FIXME: int __aeabi_ulcmp(unsigned long long, unsigned long long)
357 // Integer division functions
358 // RTABI chapter 4.3.1
359 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
360 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
361 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
362 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
363 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
364 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
365 { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366 { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367 { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368 { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369 { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370 { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373 // RTABI chapter 4.3.4
374 // FIXME: void __aeabi_memcpy8(void *, const void *, size_t)
375 // FIXME: void __aeabi_memcpy4(void *, const void *, size_t)
376 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377 // FIXME: void __aeabi_memmove8(void *, const void *, size_t)
378 // FIXME: void __aeabi_memmove4(void *, const void *, size_t)
379 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380 // FIXME: void __aeabi_memset8(void *, size_t, int)
381 // FIXME: void __aeabi_memset4(void *, size_t, int)
382 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383 // FIXME: void __aeabi_memclr8(void *, size_t)
384 // FIXME: void __aeabi_memclr4(void *, size_t)
385 // FIXME: void __aeabi_memclr(void *, size_t)
388 for (const auto &LC : LibraryCalls) {
389 setLibcallName(LC.Op, LC.Name);
390 setLibcallCallingConv(LC.Op, LC.CC);
391 if (LC.Cond != ISD::SETCC_INVALID)
392 setCmpLibcallCC(LC.Op, LC.Cond);
395 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
396 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
399 if (Subtarget->isTargetWindows()) {
400 static const struct {
401 const RTLIB::Libcall Op;
402 const char * const Name;
403 const CallingConv::ID CC;
405 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
406 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
407 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
408 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
409 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
410 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
411 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
412 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
415 for (const auto &LC : LibraryCalls) {
416 setLibcallName(LC.Op, LC.Name);
417 setLibcallCallingConv(LC.Op, LC.CC);
421 // Use divmod compiler-rt calls for iOS 5.0 and later.
422 if (Subtarget->getTargetTriple().isiOS() &&
423 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
424 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
425 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
428 // The half <-> float conversion functions are always soft-float, but are
429 // needed for some targets which use a hard-float calling convention by
431 if (Subtarget->isAAPCS_ABI()) {
432 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
433 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
434 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
436 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
437 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
438 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
441 if (Subtarget->isThumb1Only())
442 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
444 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
445 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
446 !Subtarget->isThumb1Only()) {
447 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
448 if (!Subtarget->isFPOnlySP())
449 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
452 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
453 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
454 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
455 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
456 setTruncStoreAction((MVT::SimpleValueType)VT,
457 (MVT::SimpleValueType)InnerVT, Expand);
458 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
460 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
462 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
463 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
464 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
465 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
467 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
470 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
471 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
473 if (Subtarget->hasNEON()) {
474 addDRTypeForNEON(MVT::v2f32);
475 addDRTypeForNEON(MVT::v8i8);
476 addDRTypeForNEON(MVT::v4i16);
477 addDRTypeForNEON(MVT::v2i32);
478 addDRTypeForNEON(MVT::v1i64);
480 addQRTypeForNEON(MVT::v4f32);
481 addQRTypeForNEON(MVT::v2f64);
482 addQRTypeForNEON(MVT::v16i8);
483 addQRTypeForNEON(MVT::v8i16);
484 addQRTypeForNEON(MVT::v4i32);
485 addQRTypeForNEON(MVT::v2i64);
487 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
488 // neither Neon nor VFP support any arithmetic operations on it.
489 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
490 // supported for v4f32.
491 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
492 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
493 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
494 // FIXME: Code duplication: FDIV and FREM are expanded always, see
495 // ARMTargetLowering::addTypeForNEON method for details.
496 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
497 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
498 // FIXME: Create unittest.
499 // In another words, find a way when "copysign" appears in DAG with vector
501 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
502 // FIXME: Code duplication: SETCC has custom operation action, see
503 // ARMTargetLowering::addTypeForNEON method for details.
504 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
505 // FIXME: Create unittest for FNEG and for FABS.
506 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
507 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
508 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
510 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
511 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
512 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
513 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
514 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
515 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
516 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
517 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
518 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
519 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
520 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
521 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
522 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
523 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
524 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
526 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
527 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
528 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
529 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
530 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
531 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
532 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
533 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
534 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
535 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
536 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
537 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
538 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
540 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
542 // Mark v2f32 intrinsics.
543 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
544 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
545 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
546 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
547 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
548 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
549 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
550 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
551 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
552 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
553 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
554 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
555 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
556 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
557 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
559 // Neon does not support some operations on v1i64 and v2i64 types.
560 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
561 // Custom handling for some quad-vector types to detect VMULL.
562 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
563 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
564 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
565 // Custom handling for some vector types to avoid expensive expansions
566 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
567 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
568 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
569 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
570 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
571 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
572 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
573 // a destination type that is wider than the source, and nor does
574 // it have a FP_TO_[SU]INT instruction with a narrower destination than
576 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
578 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
579 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
581 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
582 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
584 // NEON does not have single instruction CTPOP for vectors with element
585 // types wider than 8-bits. However, custom lowering can leverage the
586 // v8i8/v16i8 vcnt instruction.
587 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
588 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
589 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
590 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
592 // NEON only has FMA instructions as of VFP4.
593 if (!Subtarget->hasVFP4()) {
594 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
595 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
598 setTargetDAGCombine(ISD::INTRINSIC_VOID);
599 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
600 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
601 setTargetDAGCombine(ISD::SHL);
602 setTargetDAGCombine(ISD::SRL);
603 setTargetDAGCombine(ISD::SRA);
604 setTargetDAGCombine(ISD::SIGN_EXTEND);
605 setTargetDAGCombine(ISD::ZERO_EXTEND);
606 setTargetDAGCombine(ISD::ANY_EXTEND);
607 setTargetDAGCombine(ISD::SELECT_CC);
608 setTargetDAGCombine(ISD::BUILD_VECTOR);
609 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
610 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
611 setTargetDAGCombine(ISD::STORE);
612 setTargetDAGCombine(ISD::FP_TO_SINT);
613 setTargetDAGCombine(ISD::FP_TO_UINT);
614 setTargetDAGCombine(ISD::FDIV);
616 // It is legal to extload from v4i8 to v4i16 or v4i32.
617 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
618 MVT::v4i16, MVT::v2i16,
620 for (unsigned i = 0; i < 6; ++i) {
621 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
622 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
623 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
627 // ARM and Thumb2 support UMLAL/SMLAL.
628 if (!Subtarget->isThumb1Only())
629 setTargetDAGCombine(ISD::ADDC);
632 computeRegisterProperties();
634 // ARM does not have floating-point extending loads.
635 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
636 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
638 // ... or truncating stores
639 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
640 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
641 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
643 // ARM does not have i1 sign extending load.
644 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
646 // ARM supports all 4 flavors of integer indexed load / store.
647 if (!Subtarget->isThumb1Only()) {
648 for (unsigned im = (unsigned)ISD::PRE_INC;
649 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
650 setIndexedLoadAction(im, MVT::i1, Legal);
651 setIndexedLoadAction(im, MVT::i8, Legal);
652 setIndexedLoadAction(im, MVT::i16, Legal);
653 setIndexedLoadAction(im, MVT::i32, Legal);
654 setIndexedStoreAction(im, MVT::i1, Legal);
655 setIndexedStoreAction(im, MVT::i8, Legal);
656 setIndexedStoreAction(im, MVT::i16, Legal);
657 setIndexedStoreAction(im, MVT::i32, Legal);
661 setOperationAction(ISD::SADDO, MVT::i32, Custom);
662 setOperationAction(ISD::UADDO, MVT::i32, Custom);
663 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
664 setOperationAction(ISD::USUBO, MVT::i32, Custom);
666 // i64 operation support.
667 setOperationAction(ISD::MUL, MVT::i64, Expand);
668 setOperationAction(ISD::MULHU, MVT::i32, Expand);
669 if (Subtarget->isThumb1Only()) {
670 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
671 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
673 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
674 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
675 setOperationAction(ISD::MULHS, MVT::i32, Expand);
677 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
678 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
679 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
680 setOperationAction(ISD::SRL, MVT::i64, Custom);
681 setOperationAction(ISD::SRA, MVT::i64, Custom);
683 if (!Subtarget->isThumb1Only()) {
684 // FIXME: We should do this for Thumb1 as well.
685 setOperationAction(ISD::ADDC, MVT::i32, Custom);
686 setOperationAction(ISD::ADDE, MVT::i32, Custom);
687 setOperationAction(ISD::SUBC, MVT::i32, Custom);
688 setOperationAction(ISD::SUBE, MVT::i32, Custom);
691 // ARM does not have ROTL.
692 setOperationAction(ISD::ROTL, MVT::i32, Expand);
693 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
694 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
695 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
696 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
698 // These just redirect to CTTZ and CTLZ on ARM.
699 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
700 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
702 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
704 // Only ARMv6 has BSWAP.
705 if (!Subtarget->hasV6Ops())
706 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
708 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
709 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
710 // These are expanded into libcalls if the cpu doesn't have HW divider.
711 setOperationAction(ISD::SDIV, MVT::i32, Expand);
712 setOperationAction(ISD::UDIV, MVT::i32, Expand);
715 // FIXME: Also set divmod for SREM on EABI
716 setOperationAction(ISD::SREM, MVT::i32, Expand);
717 setOperationAction(ISD::UREM, MVT::i32, Expand);
718 if (!Subtarget->isTargetAEABI()) {
719 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
720 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
723 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
724 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
725 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
726 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
727 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
729 setOperationAction(ISD::TRAP, MVT::Other, Legal);
731 // Use the default implementation.
732 setOperationAction(ISD::VASTART, MVT::Other, Custom);
733 setOperationAction(ISD::VAARG, MVT::Other, Expand);
734 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
735 setOperationAction(ISD::VAEND, MVT::Other, Expand);
736 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
737 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
739 if (!Subtarget->isTargetMachO()) {
740 // Non-MachO platforms may return values in these registers via the
741 // personality function.
742 setExceptionPointerRegister(ARM::R0);
743 setExceptionSelectorRegister(ARM::R1);
746 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
747 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
749 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
751 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
752 // the default expansion.
753 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
754 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
755 // to ldrex/strex loops already.
756 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
758 // On v8, we have particularly efficient implementations of atomic fences
759 // if they can be combined with nearby atomic loads and stores.
760 if (!Subtarget->hasV8Ops()) {
761 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
762 setInsertFencesForAtomic(true);
765 // If there's anything we can use as a barrier, go through custom lowering
767 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
768 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
770 // Set them all for expansion, which will force libcalls.
771 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
772 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
773 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
774 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
775 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
776 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
777 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
778 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
779 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
780 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
781 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
782 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
783 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
784 // Unordered/Monotonic case.
785 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
786 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
789 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
791 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
792 if (!Subtarget->hasV6Ops()) {
793 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
794 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
796 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
798 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
799 !Subtarget->isThumb1Only()) {
800 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
801 // iff target supports vfp2.
802 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
803 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
806 // We want to custom lower some of our intrinsics.
807 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
808 if (Subtarget->isTargetDarwin()) {
809 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
810 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
811 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
814 setOperationAction(ISD::SETCC, MVT::i32, Expand);
815 setOperationAction(ISD::SETCC, MVT::f32, Expand);
816 setOperationAction(ISD::SETCC, MVT::f64, Expand);
817 setOperationAction(ISD::SELECT, MVT::i32, Custom);
818 setOperationAction(ISD::SELECT, MVT::f32, Custom);
819 setOperationAction(ISD::SELECT, MVT::f64, Custom);
820 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
821 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
822 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
824 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
825 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
826 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
827 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
828 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
830 // We don't support sin/cos/fmod/copysign/pow
831 setOperationAction(ISD::FSIN, MVT::f64, Expand);
832 setOperationAction(ISD::FSIN, MVT::f32, Expand);
833 setOperationAction(ISD::FCOS, MVT::f32, Expand);
834 setOperationAction(ISD::FCOS, MVT::f64, Expand);
835 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
836 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
837 setOperationAction(ISD::FREM, MVT::f64, Expand);
838 setOperationAction(ISD::FREM, MVT::f32, Expand);
839 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
840 !Subtarget->isThumb1Only()) {
841 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
842 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
844 setOperationAction(ISD::FPOW, MVT::f64, Expand);
845 setOperationAction(ISD::FPOW, MVT::f32, Expand);
847 if (!Subtarget->hasVFP4()) {
848 setOperationAction(ISD::FMA, MVT::f64, Expand);
849 setOperationAction(ISD::FMA, MVT::f32, Expand);
852 // Various VFP goodness
853 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
854 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
855 if (Subtarget->hasVFP2()) {
856 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
857 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
858 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
859 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
862 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
863 if (!Subtarget->hasV8Ops()) {
864 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
865 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
868 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
869 if (!Subtarget->hasFP16()) {
870 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
871 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
875 // Combine sin / cos into one node or libcall if possible.
876 if (Subtarget->hasSinCos()) {
877 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
878 setLibcallName(RTLIB::SINCOS_F64, "sincos");
879 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
880 // For iOS, we don't want to the normal expansion of a libcall to
881 // sincos. We want to issue a libcall to __sincos_stret.
882 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
883 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
887 // ARMv8 implements a lot of rounding-like FP operations.
888 if (Subtarget->hasV8Ops()) {
889 static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
890 for (const auto Ty : RoundingTypes) {
891 setOperationAction(ISD::FFLOOR, Ty, Legal);
892 setOperationAction(ISD::FCEIL, Ty, Legal);
893 setOperationAction(ISD::FROUND, Ty, Legal);
894 setOperationAction(ISD::FTRUNC, Ty, Legal);
895 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
896 setOperationAction(ISD::FRINT, Ty, Legal);
899 // We have target-specific dag combine patterns for the following nodes:
900 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
901 setTargetDAGCombine(ISD::ADD);
902 setTargetDAGCombine(ISD::SUB);
903 setTargetDAGCombine(ISD::MUL);
904 setTargetDAGCombine(ISD::AND);
905 setTargetDAGCombine(ISD::OR);
906 setTargetDAGCombine(ISD::XOR);
908 if (Subtarget->hasV6Ops())
909 setTargetDAGCombine(ISD::SRL);
911 setStackPointerRegisterToSaveRestore(ARM::SP);
913 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
914 !Subtarget->hasVFP2())
915 setSchedulingPreference(Sched::RegPressure);
917 setSchedulingPreference(Sched::Hybrid);
919 //// temporary - rewrite interface to use type
920 MaxStoresPerMemset = 8;
921 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
922 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
923 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
924 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
925 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
927 // On ARM arguments smaller than 4 bytes are extended, so all arguments
928 // are at least 4 bytes aligned.
929 setMinStackArgumentAlignment(4);
931 // Prefer likely predicted branches to selects on out-of-order cores.
932 PredictableSelectIsExpensive = Subtarget->isLikeA9();
934 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
937 // FIXME: It might make sense to define the representative register class as the
938 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
939 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
940 // SPR's representative would be DPR_VFP2. This should work well if register
941 // pressure tracking were modified such that a register use would increment the
942 // pressure of the register class's representative and all of it's super
943 // classes' representatives transitively. We have not implemented this because
944 // of the difficulty prior to coalescing of modeling operand register classes
945 // due to the common occurrence of cross class copies and subregister insertions
947 std::pair<const TargetRegisterClass*, uint8_t>
948 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
949 const TargetRegisterClass *RRC = nullptr;
951 switch (VT.SimpleTy) {
953 return TargetLowering::findRepresentativeClass(VT);
954 // Use DPR as representative register class for all floating point
955 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
956 // the cost is 1 for both f32 and f64.
957 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
958 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
959 RRC = &ARM::DPRRegClass;
960 // When NEON is used for SP, only half of the register file is available
961 // because operations that define both SP and DP results will be constrained
962 // to the VFP2 class (D0-D15). We currently model this constraint prior to
963 // coalescing by double-counting the SP regs. See the FIXME above.
964 if (Subtarget->useNEONForSinglePrecisionFP())
967 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
968 case MVT::v4f32: case MVT::v2f64:
969 RRC = &ARM::DPRRegClass;
973 RRC = &ARM::DPRRegClass;
977 RRC = &ARM::DPRRegClass;
981 return std::make_pair(RRC, Cost);
984 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
986 default: return nullptr;
987 case ARMISD::Wrapper: return "ARMISD::Wrapper";
988 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
989 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
990 case ARMISD::CALL: return "ARMISD::CALL";
991 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
992 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
993 case ARMISD::tCALL: return "ARMISD::tCALL";
994 case ARMISD::BRCOND: return "ARMISD::BRCOND";
995 case ARMISD::BR_JT: return "ARMISD::BR_JT";
996 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
997 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
998 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
999 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1000 case ARMISD::CMP: return "ARMISD::CMP";
1001 case ARMISD::CMN: return "ARMISD::CMN";
1002 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1003 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1004 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1005 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1006 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1008 case ARMISD::CMOV: return "ARMISD::CMOV";
1010 case ARMISD::RBIT: return "ARMISD::RBIT";
1012 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1013 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1014 case ARMISD::SITOF: return "ARMISD::SITOF";
1015 case ARMISD::UITOF: return "ARMISD::UITOF";
1017 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1018 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1019 case ARMISD::RRX: return "ARMISD::RRX";
1021 case ARMISD::ADDC: return "ARMISD::ADDC";
1022 case ARMISD::ADDE: return "ARMISD::ADDE";
1023 case ARMISD::SUBC: return "ARMISD::SUBC";
1024 case ARMISD::SUBE: return "ARMISD::SUBE";
1026 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1027 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1029 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1030 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1032 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1034 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1036 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1038 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1040 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1042 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1044 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1045 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1046 case ARMISD::VCGE: return "ARMISD::VCGE";
1047 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1048 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1049 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1050 case ARMISD::VCGT: return "ARMISD::VCGT";
1051 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1052 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1053 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1054 case ARMISD::VTST: return "ARMISD::VTST";
1056 case ARMISD::VSHL: return "ARMISD::VSHL";
1057 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1058 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1059 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1060 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1061 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1062 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1063 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1064 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1065 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1066 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1067 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1068 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1069 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1070 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1071 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1072 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1073 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1074 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1075 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1076 case ARMISD::VDUP: return "ARMISD::VDUP";
1077 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1078 case ARMISD::VEXT: return "ARMISD::VEXT";
1079 case ARMISD::VREV64: return "ARMISD::VREV64";
1080 case ARMISD::VREV32: return "ARMISD::VREV32";
1081 case ARMISD::VREV16: return "ARMISD::VREV16";
1082 case ARMISD::VZIP: return "ARMISD::VZIP";
1083 case ARMISD::VUZP: return "ARMISD::VUZP";
1084 case ARMISD::VTRN: return "ARMISD::VTRN";
1085 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1086 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1087 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1088 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1089 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1090 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1091 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1092 case ARMISD::FMAX: return "ARMISD::FMAX";
1093 case ARMISD::FMIN: return "ARMISD::FMIN";
1094 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1095 case ARMISD::VMINNM: return "ARMISD::VMIN";
1096 case ARMISD::BFI: return "ARMISD::BFI";
1097 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1098 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1099 case ARMISD::VBSL: return "ARMISD::VBSL";
1100 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1101 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1102 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1103 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1104 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1105 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1106 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1107 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1108 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1109 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1110 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1111 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1112 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1113 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1114 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1115 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1116 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1117 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1118 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1119 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1123 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1124 if (!VT.isVector()) return getPointerTy();
1125 return VT.changeVectorElementTypeToInteger();
1128 /// getRegClassFor - Return the register class that should be used for the
1129 /// specified value type.
1130 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1131 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1132 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1133 // load / store 4 to 8 consecutive D registers.
1134 if (Subtarget->hasNEON()) {
1135 if (VT == MVT::v4i64)
1136 return &ARM::QQPRRegClass;
1137 if (VT == MVT::v8i64)
1138 return &ARM::QQQQPRRegClass;
1140 return TargetLowering::getRegClassFor(VT);
1143 // Create a fast isel object.
1145 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1146 const TargetLibraryInfo *libInfo) const {
1147 return ARM::createFastISel(funcInfo, libInfo);
1150 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1151 /// be used for loads / stores from the global.
1152 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1153 return (Subtarget->isThumb1Only() ? 127 : 4095);
1156 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1157 unsigned NumVals = N->getNumValues();
1159 return Sched::RegPressure;
1161 for (unsigned i = 0; i != NumVals; ++i) {
1162 EVT VT = N->getValueType(i);
1163 if (VT == MVT::Glue || VT == MVT::Other)
1165 if (VT.isFloatingPoint() || VT.isVector())
1169 if (!N->isMachineOpcode())
1170 return Sched::RegPressure;
1172 // Load are scheduled for latency even if there instruction itinerary
1173 // is not available.
1174 const TargetInstrInfo *TII =
1175 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1176 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1178 if (MCID.getNumDefs() == 0)
1179 return Sched::RegPressure;
1180 if (!Itins->isEmpty() &&
1181 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1184 return Sched::RegPressure;
1187 //===----------------------------------------------------------------------===//
1189 //===----------------------------------------------------------------------===//
1191 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1192 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1194 default: llvm_unreachable("Unknown condition code!");
1195 case ISD::SETNE: return ARMCC::NE;
1196 case ISD::SETEQ: return ARMCC::EQ;
1197 case ISD::SETGT: return ARMCC::GT;
1198 case ISD::SETGE: return ARMCC::GE;
1199 case ISD::SETLT: return ARMCC::LT;
1200 case ISD::SETLE: return ARMCC::LE;
1201 case ISD::SETUGT: return ARMCC::HI;
1202 case ISD::SETUGE: return ARMCC::HS;
1203 case ISD::SETULT: return ARMCC::LO;
1204 case ISD::SETULE: return ARMCC::LS;
1208 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1209 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1210 ARMCC::CondCodes &CondCode2) {
1211 CondCode2 = ARMCC::AL;
1213 default: llvm_unreachable("Unknown FP condition!");
1215 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1217 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1219 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1220 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1221 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1222 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1223 case ISD::SETO: CondCode = ARMCC::VC; break;
1224 case ISD::SETUO: CondCode = ARMCC::VS; break;
1225 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1226 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1227 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1229 case ISD::SETULT: CondCode = ARMCC::LT; break;
1231 case ISD::SETULE: CondCode = ARMCC::LE; break;
1233 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1237 //===----------------------------------------------------------------------===//
1238 // Calling Convention Implementation
1239 //===----------------------------------------------------------------------===//
1241 #include "ARMGenCallingConv.inc"
1243 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1244 /// account presence of floating point hardware and calling convention
1245 /// limitations, such as support for variadic functions.
1247 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1248 bool isVarArg) const {
1251 llvm_unreachable("Unsupported calling convention");
1252 case CallingConv::ARM_AAPCS:
1253 case CallingConv::ARM_APCS:
1254 case CallingConv::GHC:
1256 case CallingConv::ARM_AAPCS_VFP:
1257 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1258 case CallingConv::C:
1259 if (!Subtarget->isAAPCS_ABI())
1260 return CallingConv::ARM_APCS;
1261 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1262 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1264 return CallingConv::ARM_AAPCS_VFP;
1266 return CallingConv::ARM_AAPCS;
1267 case CallingConv::Fast:
1268 if (!Subtarget->isAAPCS_ABI()) {
1269 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1270 return CallingConv::Fast;
1271 return CallingConv::ARM_APCS;
1272 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1273 return CallingConv::ARM_AAPCS_VFP;
1275 return CallingConv::ARM_AAPCS;
1279 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1280 /// CallingConvention.
1281 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1283 bool isVarArg) const {
1284 switch (getEffectiveCallingConv(CC, isVarArg)) {
1286 llvm_unreachable("Unsupported calling convention");
1287 case CallingConv::ARM_APCS:
1288 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289 case CallingConv::ARM_AAPCS:
1290 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291 case CallingConv::ARM_AAPCS_VFP:
1292 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293 case CallingConv::Fast:
1294 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1295 case CallingConv::GHC:
1296 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300 /// LowerCallResult - Lower the result values of a call into the
1301 /// appropriate copies out of appropriate physical registers.
1303 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1304 CallingConv::ID CallConv, bool isVarArg,
1305 const SmallVectorImpl<ISD::InputArg> &Ins,
1306 SDLoc dl, SelectionDAG &DAG,
1307 SmallVectorImpl<SDValue> &InVals,
1308 bool isThisReturn, SDValue ThisVal) const {
1310 // Assign locations to each value returned by this call.
1311 SmallVector<CCValAssign, 16> RVLocs;
1312 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1313 *DAG.getContext(), Call);
1314 CCInfo.AnalyzeCallResult(Ins,
1315 CCAssignFnForNode(CallConv, /* Return*/ true,
1318 // Copy all of the result registers out of their specified physreg.
1319 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1320 CCValAssign VA = RVLocs[i];
1322 // Pass 'this' value directly from the argument to return value, to avoid
1323 // reg unit interference
1324 if (i == 0 && isThisReturn) {
1325 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1326 "unexpected return calling convention register assignment");
1327 InVals.push_back(ThisVal);
1332 if (VA.needsCustom()) {
1333 // Handle f64 or half of a v2f64.
1334 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1336 Chain = Lo.getValue(1);
1337 InFlag = Lo.getValue(2);
1338 VA = RVLocs[++i]; // skip ahead to next loc
1339 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1341 Chain = Hi.getValue(1);
1342 InFlag = Hi.getValue(2);
1343 if (!Subtarget->isLittle())
1345 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347 if (VA.getLocVT() == MVT::v2f64) {
1348 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350 DAG.getConstant(0, MVT::i32));
1352 VA = RVLocs[++i]; // skip ahead to next loc
1353 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354 Chain = Lo.getValue(1);
1355 InFlag = Lo.getValue(2);
1356 VA = RVLocs[++i]; // skip ahead to next loc
1357 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358 Chain = Hi.getValue(1);
1359 InFlag = Hi.getValue(2);
1360 if (!Subtarget->isLittle())
1362 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364 DAG.getConstant(1, MVT::i32));
1367 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1369 Chain = Val.getValue(1);
1370 InFlag = Val.getValue(2);
1373 switch (VA.getLocInfo()) {
1374 default: llvm_unreachable("Unknown loc info!");
1375 case CCValAssign::Full: break;
1376 case CCValAssign::BCvt:
1377 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1381 InVals.push_back(Val);
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390 SDValue StackPtr, SDValue Arg,
1391 SDLoc dl, SelectionDAG &DAG,
1392 const CCValAssign &VA,
1393 ISD::ArgFlagsTy Flags) const {
1394 unsigned LocMemOffset = VA.getLocMemOffset();
1395 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397 return DAG.getStore(Chain, dl, Arg, PtrOff,
1398 MachinePointerInfo::getStack(LocMemOffset),
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403 SDValue Chain, SDValue &Arg,
1404 RegsToPassVector &RegsToPass,
1405 CCValAssign &VA, CCValAssign &NextVA,
1407 SmallVectorImpl<SDValue> &MemOpChains,
1408 ISD::ArgFlagsTy Flags) const {
1410 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412 unsigned id = Subtarget->isLittle() ? 0 : 1;
1413 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1415 if (NextVA.isRegLoc())
1416 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1418 assert(NextVA.isMemLoc());
1419 if (!StackPtr.getNode())
1420 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1422 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433 SmallVectorImpl<SDValue> &InVals) const {
1434 SelectionDAG &DAG = CLI.DAG;
1436 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1438 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1439 SDValue Chain = CLI.Chain;
1440 SDValue Callee = CLI.Callee;
1441 bool &isTailCall = CLI.IsTailCall;
1442 CallingConv::ID CallConv = CLI.CallConv;
1443 bool doesNotRet = CLI.DoesNotReturn;
1444 bool isVarArg = CLI.IsVarArg;
1446 MachineFunction &MF = DAG.getMachineFunction();
1447 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448 bool isThisReturn = false;
1449 bool isSibCall = false;
1451 // Disable tail calls if they're not supported.
1452 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1456 // Check if it's really possible to do a tail call.
1457 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459 Outs, OutVals, Ins, DAG);
1460 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1461 report_fatal_error("failed to perform tail call elimination on a call "
1462 "site marked musttail");
1463 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1464 // detected sibcalls.
1471 // Analyze operands of the call, assigning locations to each operand.
1472 SmallVector<CCValAssign, 16> ArgLocs;
1473 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1474 *DAG.getContext(), Call);
1475 CCInfo.AnalyzeCallOperands(Outs,
1476 CCAssignFnForNode(CallConv, /* Return*/ false,
1479 // Get a count of how many bytes are to be pushed on the stack.
1480 unsigned NumBytes = CCInfo.getNextStackOffset();
1482 // For tail calls, memory operands are available in our caller's stack.
1486 // Adjust the stack pointer for the new arguments...
1487 // These operations are automatically eliminated by the prolog/epilog pass
1489 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1492 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1494 RegsToPassVector RegsToPass;
1495 SmallVector<SDValue, 8> MemOpChains;
1497 // Walk the register/memloc assignments, inserting copies/loads. In the case
1498 // of tail call optimization, arguments are handled later.
1499 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1501 ++i, ++realArgIdx) {
1502 CCValAssign &VA = ArgLocs[i];
1503 SDValue Arg = OutVals[realArgIdx];
1504 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1505 bool isByVal = Flags.isByVal();
1507 // Promote the value if needed.
1508 switch (VA.getLocInfo()) {
1509 default: llvm_unreachable("Unknown loc info!");
1510 case CCValAssign::Full: break;
1511 case CCValAssign::SExt:
1512 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1514 case CCValAssign::ZExt:
1515 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1517 case CCValAssign::AExt:
1518 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1520 case CCValAssign::BCvt:
1521 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1525 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1526 if (VA.needsCustom()) {
1527 if (VA.getLocVT() == MVT::v2f64) {
1528 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529 DAG.getConstant(0, MVT::i32));
1530 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1531 DAG.getConstant(1, MVT::i32));
1533 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1534 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1536 VA = ArgLocs[++i]; // skip ahead to next loc
1537 if (VA.isRegLoc()) {
1538 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1539 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1541 assert(VA.isMemLoc());
1543 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1544 dl, DAG, VA, Flags));
1547 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1548 StackPtr, MemOpChains, Flags);
1550 } else if (VA.isRegLoc()) {
1551 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1552 assert(VA.getLocVT() == MVT::i32 &&
1553 "unexpected calling convention register assignment");
1554 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1555 "unexpected use of 'returned'");
1556 isThisReturn = true;
1558 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1559 } else if (isByVal) {
1560 assert(VA.isMemLoc());
1561 unsigned offset = 0;
1563 // True if this byval aggregate will be split between registers
1565 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1566 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1568 if (CurByValIdx < ByValArgsCount) {
1570 unsigned RegBegin, RegEnd;
1571 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1573 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1575 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1576 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1577 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1578 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1579 MachinePointerInfo(),
1580 false, false, false,
1581 DAG.InferPtrAlignment(AddArg));
1582 MemOpChains.push_back(Load.getValue(1));
1583 RegsToPass.push_back(std::make_pair(j, Load));
1586 // If parameter size outsides register area, "offset" value
1587 // helps us to calculate stack slot for remained part properly.
1588 offset = RegEnd - RegBegin;
1590 CCInfo.nextInRegsParam();
1593 if (Flags.getByValSize() > 4*offset) {
1594 unsigned LocMemOffset = VA.getLocMemOffset();
1595 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1596 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1598 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1599 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1600 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1602 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1604 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1605 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1606 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1609 } else if (!isSibCall) {
1610 assert(VA.isMemLoc());
1612 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1613 dl, DAG, VA, Flags));
1617 if (!MemOpChains.empty())
1618 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1620 // Build a sequence of copy-to-reg nodes chained together with token chain
1621 // and flag operands which copy the outgoing args into the appropriate regs.
1623 // Tail call byval lowering might overwrite argument registers so in case of
1624 // tail call optimization the copies to registers are lowered later.
1626 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1628 RegsToPass[i].second, InFlag);
1629 InFlag = Chain.getValue(1);
1632 // For tail calls lower the arguments to the 'real' stack slot.
1634 // Force all the incoming stack arguments to be loaded from the stack
1635 // before any new outgoing arguments are stored to the stack, because the
1636 // outgoing stack slots may alias the incoming argument stack slots, and
1637 // the alias isn't otherwise explicit. This is slightly more conservative
1638 // than necessary, because it means that each store effectively depends
1639 // on every argument instead of just those arguments it would clobber.
1641 // Do not flag preceding copytoreg stuff together with the following stuff.
1643 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645 RegsToPass[i].second, InFlag);
1646 InFlag = Chain.getValue(1);
1651 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1652 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1653 // node so that legalize doesn't hack it.
1654 bool isDirect = false;
1655 bool isARMFunc = false;
1656 bool isLocalARMFunc = false;
1657 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1659 if (EnableARMLongCalls) {
1660 assert((Subtarget->isTargetWindows() ||
1661 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1662 "long-calls with non-static relocation model!");
1663 // Handle a global address or an external symbol. If it's not one of
1664 // those, the target's already in a register, so we don't need to do
1666 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1667 const GlobalValue *GV = G->getGlobal();
1668 // Create a constant pool entry for the callee address
1669 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1670 ARMConstantPoolValue *CPV =
1671 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1673 // Get the address of the callee into a register
1674 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1675 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1676 Callee = DAG.getLoad(getPointerTy(), dl,
1677 DAG.getEntryNode(), CPAddr,
1678 MachinePointerInfo::getConstantPool(),
1679 false, false, false, 0);
1680 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1681 const char *Sym = S->getSymbol();
1683 // Create a constant pool entry for the callee address
1684 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1685 ARMConstantPoolValue *CPV =
1686 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1687 ARMPCLabelIndex, 0);
1688 // Get the address of the callee into a register
1689 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1690 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1691 Callee = DAG.getLoad(getPointerTy(), dl,
1692 DAG.getEntryNode(), CPAddr,
1693 MachinePointerInfo::getConstantPool(),
1694 false, false, false, 0);
1696 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1697 const GlobalValue *GV = G->getGlobal();
1699 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1700 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1701 getTargetMachine().getRelocationModel() != Reloc::Static;
1702 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1703 // ARM call to a local ARM function is predicable.
1704 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1705 // tBX takes a register source operand.
1706 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1707 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1708 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1709 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1710 0, ARMII::MO_NONLAZY));
1711 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1712 MachinePointerInfo::getGOT(), false, false, true, 0);
1713 } else if (Subtarget->isTargetCOFF()) {
1714 assert(Subtarget->isTargetWindows() &&
1715 "Windows is the only supported COFF target");
1716 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1717 ? ARMII::MO_DLLIMPORT
1718 : ARMII::MO_NO_FLAG;
1719 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1721 if (GV->hasDLLImportStorageClass())
1722 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1723 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1724 Callee), MachinePointerInfo::getGOT(),
1725 false, false, false, 0);
1727 // On ELF targets for PIC code, direct calls should go through the PLT
1728 unsigned OpFlags = 0;
1729 if (Subtarget->isTargetELF() &&
1730 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1731 OpFlags = ARMII::MO_PLT;
1732 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1734 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1736 bool isStub = Subtarget->isTargetMachO() &&
1737 getTargetMachine().getRelocationModel() != Reloc::Static;
1738 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1739 // tBX takes a register source operand.
1740 const char *Sym = S->getSymbol();
1741 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1742 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1743 ARMConstantPoolValue *CPV =
1744 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1745 ARMPCLabelIndex, 4);
1746 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1747 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1748 Callee = DAG.getLoad(getPointerTy(), dl,
1749 DAG.getEntryNode(), CPAddr,
1750 MachinePointerInfo::getConstantPool(),
1751 false, false, false, 0);
1752 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1753 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1754 getPointerTy(), Callee, PICLabel);
1756 unsigned OpFlags = 0;
1757 // On ELF targets for PIC code, direct calls should go through the PLT
1758 if (Subtarget->isTargetELF() &&
1759 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1760 OpFlags = ARMII::MO_PLT;
1761 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1765 // FIXME: handle tail calls differently.
1767 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1768 AttributeSet::FunctionIndex, Attribute::MinSize);
1769 if (Subtarget->isThumb()) {
1770 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1771 CallOpc = ARMISD::CALL_NOLINK;
1773 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1775 if (!isDirect && !Subtarget->hasV5TOps())
1776 CallOpc = ARMISD::CALL_NOLINK;
1777 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1778 // Emit regular call when code size is the priority
1780 // "mov lr, pc; b _foo" to avoid confusing the RSP
1781 CallOpc = ARMISD::CALL_NOLINK;
1783 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1786 std::vector<SDValue> Ops;
1787 Ops.push_back(Chain);
1788 Ops.push_back(Callee);
1790 // Add argument registers to the end of the list so that they are known live
1792 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1793 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1794 RegsToPass[i].second.getValueType()));
1796 // Add a register mask operand representing the call-preserved registers.
1798 const uint32_t *Mask;
1799 const TargetRegisterInfo *TRI =
1800 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1801 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1803 // For 'this' returns, use the R0-preserving mask if applicable
1804 Mask = ARI->getThisReturnPreservedMask(CallConv);
1806 // Set isThisReturn to false if the calling convention is not one that
1807 // allows 'returned' to be modeled in this way, so LowerCallResult does
1808 // not try to pass 'this' straight through
1809 isThisReturn = false;
1810 Mask = ARI->getCallPreservedMask(CallConv);
1813 Mask = ARI->getCallPreservedMask(CallConv);
1815 assert(Mask && "Missing call preserved mask for calling convention");
1816 Ops.push_back(DAG.getRegisterMask(Mask));
1819 if (InFlag.getNode())
1820 Ops.push_back(InFlag);
1822 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1824 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1826 // Returns a chain and a flag for retval copy to use.
1827 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1828 InFlag = Chain.getValue(1);
1830 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1831 DAG.getIntPtrConstant(0, true), InFlag, dl);
1833 InFlag = Chain.getValue(1);
1835 // Handle result values, copying them out of physregs into vregs that we
1837 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1838 InVals, isThisReturn,
1839 isThisReturn ? OutVals[0] : SDValue());
1842 /// HandleByVal - Every parameter *after* a byval parameter is passed
1843 /// on the stack. Remember the next parameter register to allocate,
1844 /// and then confiscate the rest of the parameter registers to insure
1847 ARMTargetLowering::HandleByVal(
1848 CCState *State, unsigned &size, unsigned Align) const {
1849 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1850 assert((State->getCallOrPrologue() == Prologue ||
1851 State->getCallOrPrologue() == Call) &&
1852 "unhandled ParmContext");
1854 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1855 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1856 unsigned AlignInRegs = Align / 4;
1857 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1858 for (unsigned i = 0; i < Waste; ++i)
1859 reg = State->AllocateReg(GPRArgRegs, 4);
1862 unsigned excess = 4 * (ARM::R4 - reg);
1864 // Special case when NSAA != SP and parameter size greater than size of
1865 // all remained GPR regs. In that case we can't split parameter, we must
1866 // send it to stack. We also must set NCRN to R4, so waste all
1867 // remained registers.
1868 const unsigned NSAAOffset = State->getNextStackOffset();
1869 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1870 while (State->AllocateReg(GPRArgRegs, 4))
1875 // First register for byval parameter is the first register that wasn't
1876 // allocated before this method call, so it would be "reg".
1877 // If parameter is small enough to be saved in range [reg, r4), then
1878 // the end (first after last) register would be reg + param-size-in-regs,
1879 // else parameter would be splitted between registers and stack,
1880 // end register would be r4 in this case.
1881 unsigned ByValRegBegin = reg;
1882 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1883 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1884 // Note, first register is allocated in the beginning of function already,
1885 // allocate remained amount of registers we need.
1886 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1887 State->AllocateReg(GPRArgRegs, 4);
1888 // A byval parameter that is split between registers and memory needs its
1889 // size truncated here.
1890 // In the case where the entire structure fits in registers, we set the
1891 // size in memory to zero.
1900 /// MatchingStackOffset - Return true if the given stack call argument is
1901 /// already available in the same position (relatively) of the caller's
1902 /// incoming argument stack.
1904 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1905 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1906 const TargetInstrInfo *TII) {
1907 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1909 if (Arg.getOpcode() == ISD::CopyFromReg) {
1910 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1911 if (!TargetRegisterInfo::isVirtualRegister(VR))
1913 MachineInstr *Def = MRI->getVRegDef(VR);
1916 if (!Flags.isByVal()) {
1917 if (!TII->isLoadFromStackSlot(Def, FI))
1922 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1923 if (Flags.isByVal())
1924 // ByVal argument is passed in as a pointer but it's now being
1925 // dereferenced. e.g.
1926 // define @foo(%struct.X* %A) {
1927 // tail call @bar(%struct.X* byval %A)
1930 SDValue Ptr = Ld->getBasePtr();
1931 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1934 FI = FINode->getIndex();
1938 assert(FI != INT_MAX);
1939 if (!MFI->isFixedObjectIndex(FI))
1941 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1944 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1945 /// for tail call optimization. Targets which want to do tail call
1946 /// optimization should implement this function.
1948 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1949 CallingConv::ID CalleeCC,
1951 bool isCalleeStructRet,
1952 bool isCallerStructRet,
1953 const SmallVectorImpl<ISD::OutputArg> &Outs,
1954 const SmallVectorImpl<SDValue> &OutVals,
1955 const SmallVectorImpl<ISD::InputArg> &Ins,
1956 SelectionDAG& DAG) const {
1957 const Function *CallerF = DAG.getMachineFunction().getFunction();
1958 CallingConv::ID CallerCC = CallerF->getCallingConv();
1959 bool CCMatch = CallerCC == CalleeCC;
1961 // Look for obvious safe cases to perform tail call optimization that do not
1962 // require ABI changes. This is what gcc calls sibcall.
1964 // Do not sibcall optimize vararg calls unless the call site is not passing
1966 if (isVarArg && !Outs.empty())
1969 // Exception-handling functions need a special set of instructions to indicate
1970 // a return to the hardware. Tail-calling another function would probably
1972 if (CallerF->hasFnAttribute("interrupt"))
1975 // Also avoid sibcall optimization if either caller or callee uses struct
1976 // return semantics.
1977 if (isCalleeStructRet || isCallerStructRet)
1980 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1981 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1982 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1983 // support in the assembler and linker to be used. This would need to be
1984 // fixed to fully support tail calls in Thumb1.
1986 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1987 // LR. This means if we need to reload LR, it takes an extra instructions,
1988 // which outweighs the value of the tail call; but here we don't know yet
1989 // whether LR is going to be used. Probably the right approach is to
1990 // generate the tail call here and turn it back into CALL/RET in
1991 // emitEpilogue if LR is used.
1993 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1994 // but we need to make sure there are enough registers; the only valid
1995 // registers are the 4 used for parameters. We don't currently do this
1997 if (Subtarget->isThumb1Only())
2000 // Externally-defined functions with weak linkage should not be
2001 // tail-called on ARM when the OS does not support dynamic
2002 // pre-emption of symbols, as the AAELF spec requires normal calls
2003 // to undefined weak functions to be replaced with a NOP or jump to the
2004 // next instruction. The behaviour of branch instructions in this
2005 // situation (as used for tail calls) is implementation-defined, so we
2006 // cannot rely on the linker replacing the tail call with a return.
2007 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2008 const GlobalValue *GV = G->getGlobal();
2009 if (GV->hasExternalWeakLinkage())
2013 // If the calling conventions do not match, then we'd better make sure the
2014 // results are returned in the same way as what the caller expects.
2016 SmallVector<CCValAssign, 16> RVLocs1;
2017 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2018 *DAG.getContext(), Call);
2019 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2021 SmallVector<CCValAssign, 16> RVLocs2;
2022 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2023 *DAG.getContext(), Call);
2024 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2026 if (RVLocs1.size() != RVLocs2.size())
2028 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2029 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2031 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2033 if (RVLocs1[i].isRegLoc()) {
2034 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2037 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2043 // If Caller's vararg or byval argument has been split between registers and
2044 // stack, do not perform tail call, since part of the argument is in caller's
2046 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2047 getInfo<ARMFunctionInfo>();
2048 if (AFI_Caller->getArgRegsSaveSize())
2051 // If the callee takes no arguments then go on to check the results of the
2053 if (!Outs.empty()) {
2054 // Check if stack adjustment is needed. For now, do not do this if any
2055 // argument is passed on the stack.
2056 SmallVector<CCValAssign, 16> ArgLocs;
2057 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2058 *DAG.getContext(), Call);
2059 CCInfo.AnalyzeCallOperands(Outs,
2060 CCAssignFnForNode(CalleeCC, false, isVarArg));
2061 if (CCInfo.getNextStackOffset()) {
2062 MachineFunction &MF = DAG.getMachineFunction();
2064 // Check if the arguments are already laid out in the right way as
2065 // the caller's fixed stack objects.
2066 MachineFrameInfo *MFI = MF.getFrameInfo();
2067 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2068 const TargetInstrInfo *TII =
2069 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2070 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2072 ++i, ++realArgIdx) {
2073 CCValAssign &VA = ArgLocs[i];
2074 EVT RegVT = VA.getLocVT();
2075 SDValue Arg = OutVals[realArgIdx];
2076 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2077 if (VA.getLocInfo() == CCValAssign::Indirect)
2079 if (VA.needsCustom()) {
2080 // f64 and vector types are split into multiple registers or
2081 // register/stack-slot combinations. The types will not match
2082 // the registers; give up on memory f64 refs until we figure
2083 // out what to do about this.
2086 if (!ArgLocs[++i].isRegLoc())
2088 if (RegVT == MVT::v2f64) {
2089 if (!ArgLocs[++i].isRegLoc())
2091 if (!ArgLocs[++i].isRegLoc())
2094 } else if (!VA.isRegLoc()) {
2095 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2107 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2108 MachineFunction &MF, bool isVarArg,
2109 const SmallVectorImpl<ISD::OutputArg> &Outs,
2110 LLVMContext &Context) const {
2111 SmallVector<CCValAssign, 16> RVLocs;
2112 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2113 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2117 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2118 SDLoc DL, SelectionDAG &DAG) {
2119 const MachineFunction &MF = DAG.getMachineFunction();
2120 const Function *F = MF.getFunction();
2122 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2124 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2125 // version of the "preferred return address". These offsets affect the return
2126 // instruction if this is a return from PL1 without hypervisor extensions.
2127 // IRQ/FIQ: +4 "subs pc, lr, #4"
2128 // SWI: 0 "subs pc, lr, #0"
2129 // ABORT: +4 "subs pc, lr, #4"
2130 // UNDEF: +4/+2 "subs pc, lr, #0"
2131 // UNDEF varies depending on where the exception came from ARM or Thumb
2132 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2135 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2138 else if (IntKind == "SWI" || IntKind == "UNDEF")
2141 report_fatal_error("Unsupported interrupt attribute. If present, value "
2142 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2144 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2146 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2150 ARMTargetLowering::LowerReturn(SDValue Chain,
2151 CallingConv::ID CallConv, bool isVarArg,
2152 const SmallVectorImpl<ISD::OutputArg> &Outs,
2153 const SmallVectorImpl<SDValue> &OutVals,
2154 SDLoc dl, SelectionDAG &DAG) const {
2156 // CCValAssign - represent the assignment of the return value to a location.
2157 SmallVector<CCValAssign, 16> RVLocs;
2159 // CCState - Info about the registers and stack slots.
2160 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2161 *DAG.getContext(), Call);
2163 // Analyze outgoing return values.
2164 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2168 SmallVector<SDValue, 4> RetOps;
2169 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2170 bool isLittleEndian = Subtarget->isLittle();
2172 MachineFunction &MF = DAG.getMachineFunction();
2173 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2174 AFI->setReturnRegsCount(RVLocs.size());
2176 // Copy the result values into the output registers.
2177 for (unsigned i = 0, realRVLocIdx = 0;
2179 ++i, ++realRVLocIdx) {
2180 CCValAssign &VA = RVLocs[i];
2181 assert(VA.isRegLoc() && "Can only return in registers!");
2183 SDValue Arg = OutVals[realRVLocIdx];
2185 switch (VA.getLocInfo()) {
2186 default: llvm_unreachable("Unknown loc info!");
2187 case CCValAssign::Full: break;
2188 case CCValAssign::BCvt:
2189 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2193 if (VA.needsCustom()) {
2194 if (VA.getLocVT() == MVT::v2f64) {
2195 // Extract the first half and return it in two registers.
2196 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2197 DAG.getConstant(0, MVT::i32));
2198 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2199 DAG.getVTList(MVT::i32, MVT::i32), Half);
2201 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2202 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2204 Flag = Chain.getValue(1);
2205 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2206 VA = RVLocs[++i]; // skip ahead to next loc
2207 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2208 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2210 Flag = Chain.getValue(1);
2211 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2212 VA = RVLocs[++i]; // skip ahead to next loc
2214 // Extract the 2nd half and fall through to handle it as an f64 value.
2215 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2216 DAG.getConstant(1, MVT::i32));
2218 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2220 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2221 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2222 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223 fmrrd.getValue(isLittleEndian ? 0 : 1),
2225 Flag = Chain.getValue(1);
2226 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227 VA = RVLocs[++i]; // skip ahead to next loc
2228 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229 fmrrd.getValue(isLittleEndian ? 1 : 0),
2232 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2234 // Guarantee that all emitted copies are
2235 // stuck together, avoiding something bad.
2236 Flag = Chain.getValue(1);
2237 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2240 // Update chain and glue.
2243 RetOps.push_back(Flag);
2245 // CPUs which aren't M-class use a special sequence to return from
2246 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2247 // though we use "subs pc, lr, #N").
2249 // M-class CPUs actually use a normal return sequence with a special
2250 // (hardware-provided) value in LR, so the normal code path works.
2251 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2252 !Subtarget->isMClass()) {
2253 if (Subtarget->isThumb1Only())
2254 report_fatal_error("interrupt attribute is not supported in Thumb1");
2255 return LowerInterruptReturn(RetOps, dl, DAG);
2258 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2261 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2262 if (N->getNumValues() != 1)
2264 if (!N->hasNUsesOfValue(1, 0))
2267 SDValue TCChain = Chain;
2268 SDNode *Copy = *N->use_begin();
2269 if (Copy->getOpcode() == ISD::CopyToReg) {
2270 // If the copy has a glue operand, we conservatively assume it isn't safe to
2271 // perform a tail call.
2272 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2274 TCChain = Copy->getOperand(0);
2275 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2276 SDNode *VMov = Copy;
2277 // f64 returned in a pair of GPRs.
2278 SmallPtrSet<SDNode*, 2> Copies;
2279 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2281 if (UI->getOpcode() != ISD::CopyToReg)
2285 if (Copies.size() > 2)
2288 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2290 SDValue UseChain = UI->getOperand(0);
2291 if (Copies.count(UseChain.getNode()))
2298 } else if (Copy->getOpcode() == ISD::BITCAST) {
2299 // f32 returned in a single GPR.
2300 if (!Copy->hasOneUse())
2302 Copy = *Copy->use_begin();
2303 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2305 TCChain = Copy->getOperand(0);
2310 bool HasRet = false;
2311 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2313 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2314 UI->getOpcode() != ARMISD::INTRET_FLAG)
2326 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2327 if (!Subtarget->supportsTailCall())
2330 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2333 return !Subtarget->isThumb1Only();
2336 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2337 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2338 // one of the above mentioned nodes. It has to be wrapped because otherwise
2339 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2340 // be used to form addressing mode. These wrapped nodes will be selected
2342 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2343 EVT PtrVT = Op.getValueType();
2344 // FIXME there is no actual debug info here
2346 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2348 if (CP->isMachineConstantPoolEntry())
2349 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2350 CP->getAlignment());
2352 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2353 CP->getAlignment());
2354 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2357 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2358 return MachineJumpTableInfo::EK_Inline;
2361 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2362 SelectionDAG &DAG) const {
2363 MachineFunction &MF = DAG.getMachineFunction();
2364 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2365 unsigned ARMPCLabelIndex = 0;
2367 EVT PtrVT = getPointerTy();
2368 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2369 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2371 if (RelocM == Reloc::Static) {
2372 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2374 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2375 ARMPCLabelIndex = AFI->createPICLabelUId();
2376 ARMConstantPoolValue *CPV =
2377 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2378 ARMCP::CPBlockAddress, PCAdj);
2379 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2381 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2382 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2383 MachinePointerInfo::getConstantPool(),
2384 false, false, false, 0);
2385 if (RelocM == Reloc::Static)
2387 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2388 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2391 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2393 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2394 SelectionDAG &DAG) const {
2396 EVT PtrVT = getPointerTy();
2397 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2398 MachineFunction &MF = DAG.getMachineFunction();
2399 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2400 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2401 ARMConstantPoolValue *CPV =
2402 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2403 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2404 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2405 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2406 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2407 MachinePointerInfo::getConstantPool(),
2408 false, false, false, 0);
2409 SDValue Chain = Argument.getValue(1);
2411 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2412 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2414 // call __tls_get_addr.
2417 Entry.Node = Argument;
2418 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2419 Args.push_back(Entry);
2421 // FIXME: is there useful debug info available here?
2422 TargetLowering::CallLoweringInfo CLI(DAG);
2423 CLI.setDebugLoc(dl).setChain(Chain)
2424 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2425 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2428 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2429 return CallResult.first;
2432 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2433 // "local exec" model.
2435 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2437 TLSModel::Model model) const {
2438 const GlobalValue *GV = GA->getGlobal();
2441 SDValue Chain = DAG.getEntryNode();
2442 EVT PtrVT = getPointerTy();
2443 // Get the Thread Pointer
2444 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2446 if (model == TLSModel::InitialExec) {
2447 MachineFunction &MF = DAG.getMachineFunction();
2448 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2449 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2450 // Initial exec model.
2451 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2452 ARMConstantPoolValue *CPV =
2453 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2454 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2456 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2457 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2458 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2459 MachinePointerInfo::getConstantPool(),
2460 false, false, false, 0);
2461 Chain = Offset.getValue(1);
2463 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2464 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2466 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2467 MachinePointerInfo::getConstantPool(),
2468 false, false, false, 0);
2471 assert(model == TLSModel::LocalExec);
2472 ARMConstantPoolValue *CPV =
2473 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2474 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2475 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2476 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2477 MachinePointerInfo::getConstantPool(),
2478 false, false, false, 0);
2481 // The address of the thread local variable is the add of the thread
2482 // pointer with the offset of the variable.
2483 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2487 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2488 // TODO: implement the "local dynamic" model
2489 assert(Subtarget->isTargetELF() &&
2490 "TLS not implemented for non-ELF targets");
2491 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2493 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2496 case TLSModel::GeneralDynamic:
2497 case TLSModel::LocalDynamic:
2498 return LowerToTLSGeneralDynamicModel(GA, DAG);
2499 case TLSModel::InitialExec:
2500 case TLSModel::LocalExec:
2501 return LowerToTLSExecModels(GA, DAG, model);
2503 llvm_unreachable("bogus TLS model");
2506 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2507 SelectionDAG &DAG) const {
2508 EVT PtrVT = getPointerTy();
2510 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2511 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2512 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2513 ARMConstantPoolValue *CPV =
2514 ARMConstantPoolConstant::Create(GV,
2515 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2516 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2517 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2518 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2520 MachinePointerInfo::getConstantPool(),
2521 false, false, false, 0);
2522 SDValue Chain = Result.getValue(1);
2523 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2524 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2526 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2527 MachinePointerInfo::getGOT(),
2528 false, false, false, 0);
2532 // If we have T2 ops, we can materialize the address directly via movt/movw
2533 // pair. This is always cheaper.
2534 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2536 // FIXME: Once remat is capable of dealing with instructions with register
2537 // operands, expand this into two nodes.
2538 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2539 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2541 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2542 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2543 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2544 MachinePointerInfo::getConstantPool(),
2545 false, false, false, 0);
2549 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2550 SelectionDAG &DAG) const {
2551 EVT PtrVT = getPointerTy();
2553 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2554 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2556 if (Subtarget->useMovt(DAG.getMachineFunction()))
2559 // FIXME: Once remat is capable of dealing with instructions with register
2560 // operands, expand this into multiple nodes
2562 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2564 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2565 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2567 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2568 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2569 MachinePointerInfo::getGOT(), false, false, false, 0);
2573 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2574 SelectionDAG &DAG) const {
2575 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2576 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2577 "Windows on ARM expects to use movw/movt");
2579 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2580 const ARMII::TOF TargetFlags =
2581 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2582 EVT PtrVT = getPointerTy();
2588 // FIXME: Once remat is capable of dealing with instructions with register
2589 // operands, expand this into two nodes.
2590 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2591 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2593 if (GV->hasDLLImportStorageClass())
2594 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2595 MachinePointerInfo::getGOT(), false, false, false, 0);
2599 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2600 SelectionDAG &DAG) const {
2601 assert(Subtarget->isTargetELF() &&
2602 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2603 MachineFunction &MF = DAG.getMachineFunction();
2604 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2605 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2606 EVT PtrVT = getPointerTy();
2608 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2609 ARMConstantPoolValue *CPV =
2610 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2611 ARMPCLabelIndex, PCAdj);
2612 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2613 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2614 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2615 MachinePointerInfo::getConstantPool(),
2616 false, false, false, 0);
2617 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2618 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2622 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2624 SDValue Val = DAG.getConstant(0, MVT::i32);
2625 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2626 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2627 Op.getOperand(1), Val);
2631 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2633 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2634 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2638 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2639 const ARMSubtarget *Subtarget) const {
2640 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2643 default: return SDValue(); // Don't custom lower most intrinsics.
2644 case Intrinsic::arm_rbit: {
2645 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2646 "RBIT intrinsic must have i32 type!");
2647 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2649 case Intrinsic::arm_thread_pointer: {
2650 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2651 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2653 case Intrinsic::eh_sjlj_lsda: {
2654 MachineFunction &MF = DAG.getMachineFunction();
2655 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2656 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2657 EVT PtrVT = getPointerTy();
2658 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2660 unsigned PCAdj = (RelocM != Reloc::PIC_)
2661 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2662 ARMConstantPoolValue *CPV =
2663 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2664 ARMCP::CPLSDA, PCAdj);
2665 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2666 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2668 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2669 MachinePointerInfo::getConstantPool(),
2670 false, false, false, 0);
2672 if (RelocM == Reloc::PIC_) {
2673 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2674 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2678 case Intrinsic::arm_neon_vmulls:
2679 case Intrinsic::arm_neon_vmullu: {
2680 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2681 ? ARMISD::VMULLs : ARMISD::VMULLu;
2682 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2683 Op.getOperand(1), Op.getOperand(2));
2688 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2689 const ARMSubtarget *Subtarget) {
2690 // FIXME: handle "fence singlethread" more efficiently.
2692 if (!Subtarget->hasDataBarrier()) {
2693 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2694 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2696 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2697 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2698 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2699 DAG.getConstant(0, MVT::i32));
2702 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2703 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2704 unsigned Domain = ARM_MB::ISH;
2705 if (Subtarget->isMClass()) {
2706 // Only a full system barrier exists in the M-class architectures.
2707 Domain = ARM_MB::SY;
2708 } else if (Subtarget->isSwift() && Ord == Release) {
2709 // Swift happens to implement ISHST barriers in a way that's compatible with
2710 // Release semantics but weaker than ISH so we'd be fools not to use
2711 // it. Beware: other processors probably don't!
2712 Domain = ARM_MB::ISHST;
2715 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2716 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2717 DAG.getConstant(Domain, MVT::i32));
2720 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2721 const ARMSubtarget *Subtarget) {
2722 // ARM pre v5TE and Thumb1 does not have preload instructions.
2723 if (!(Subtarget->isThumb2() ||
2724 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2725 // Just preserve the chain.
2726 return Op.getOperand(0);
2729 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2731 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2732 // ARMv7 with MP extension has PLDW.
2733 return Op.getOperand(0);
2735 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2736 if (Subtarget->isThumb()) {
2738 isRead = ~isRead & 1;
2739 isData = ~isData & 1;
2742 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2743 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2744 DAG.getConstant(isData, MVT::i32));
2747 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2748 MachineFunction &MF = DAG.getMachineFunction();
2749 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2751 // vastart just stores the address of the VarArgsFrameIndex slot into the
2752 // memory location argument.
2754 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2755 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2756 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2757 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2758 MachinePointerInfo(SV), false, false, 0);
2762 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2763 SDValue &Root, SelectionDAG &DAG,
2765 MachineFunction &MF = DAG.getMachineFunction();
2766 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2768 const TargetRegisterClass *RC;
2769 if (AFI->isThumb1OnlyFunction())
2770 RC = &ARM::tGPRRegClass;
2772 RC = &ARM::GPRRegClass;
2774 // Transform the arguments stored in physical registers into virtual ones.
2775 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2776 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2779 if (NextVA.isMemLoc()) {
2780 MachineFrameInfo *MFI = MF.getFrameInfo();
2781 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2783 // Create load node to retrieve arguments from the stack.
2784 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2785 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2786 MachinePointerInfo::getFixedStack(FI),
2787 false, false, false, 0);
2789 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2790 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2792 if (!Subtarget->isLittle())
2793 std::swap (ArgValue, ArgValue2);
2794 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2798 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2799 unsigned InRegsParamRecordIdx,
2801 unsigned &ArgRegsSize,
2802 unsigned &ArgRegsSaveSize)
2805 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2806 unsigned RBegin, REnd;
2807 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2808 NumGPRs = REnd - RBegin;
2810 unsigned int firstUnalloced;
2811 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2812 sizeof(GPRArgRegs) /
2813 sizeof(GPRArgRegs[0]));
2814 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2817 unsigned Align = MF.getTarget()
2819 ->getFrameLowering()
2820 ->getStackAlignment();
2821 ArgRegsSize = NumGPRs * 4;
2823 // If parameter is split between stack and GPRs...
2824 if (NumGPRs && Align > 4 &&
2825 (ArgRegsSize < ArgSize ||
2826 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2827 // Add padding for part of param recovered from GPRs. For example,
2828 // if Align == 8, its last byte must be at address K*8 - 1.
2829 // We need to do it, since remained (stack) part of parameter has
2830 // stack alignment, and we need to "attach" "GPRs head" without gaps
2833 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2834 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2836 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2838 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2839 ArgRegsSaveSize = ArgRegsSize + Padding;
2841 // We don't need to extend regs save size for byval parameters if they
2842 // are passed via GPRs only.
2843 ArgRegsSaveSize = ArgRegsSize;
2846 // The remaining GPRs hold either the beginning of variable-argument
2847 // data, or the beginning of an aggregate passed by value (usually
2848 // byval). Either way, we allocate stack slots adjacent to the data
2849 // provided by our caller, and store the unallocated registers there.
2850 // If this is a variadic function, the va_list pointer will begin with
2851 // these values; otherwise, this reassembles a (byval) structure that
2852 // was split between registers and memory.
2853 // Return: The frame index registers were stored into.
2855 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2856 SDLoc dl, SDValue &Chain,
2857 const Value *OrigArg,
2858 unsigned InRegsParamRecordIdx,
2859 unsigned OffsetFromOrigArg,
2863 unsigned ByValStoreOffset,
2864 unsigned TotalArgRegsSaveSize) const {
2866 // Currently, two use-cases possible:
2867 // Case #1. Non-var-args function, and we meet first byval parameter.
2868 // Setup first unallocated register as first byval register;
2869 // eat all remained registers
2870 // (these two actions are performed by HandleByVal method).
2871 // Then, here, we initialize stack frame with
2872 // "store-reg" instructions.
2873 // Case #2. Var-args function, that doesn't contain byval parameters.
2874 // The same: eat all remained unallocated registers,
2875 // initialize stack frame.
2877 MachineFunction &MF = DAG.getMachineFunction();
2878 MachineFrameInfo *MFI = MF.getFrameInfo();
2879 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2881 unsigned RBegin, REnd;
2882 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2883 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2884 firstRegToSaveIndex = RBegin - ARM::R0;
2885 lastRegToSaveIndex = REnd - ARM::R0;
2887 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2888 (GPRArgRegs, array_lengthof(GPRArgRegs));
2889 lastRegToSaveIndex = 4;
2892 unsigned ArgRegsSize, ArgRegsSaveSize;
2893 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2894 ArgRegsSize, ArgRegsSaveSize);
2896 // Store any by-val regs to their spots on the stack so that they may be
2897 // loaded by deferencing the result of formal parameter pointer or va_next.
2898 // Note: once stack area for byval/varargs registers
2899 // was initialized, it can't be initialized again.
2900 if (ArgRegsSaveSize) {
2901 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2904 assert(AFI->getStoredByValParamsPadding() == 0 &&
2905 "The only parameter may be padded.");
2906 AFI->setStoredByValParamsPadding(Padding);
2909 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2912 (int64_t)TotalArgRegsSaveSize,
2914 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2916 MFI->CreateFixedObject(Padding,
2917 ArgOffset + ByValStoreOffset -
2918 (int64_t)ArgRegsSaveSize,
2922 SmallVector<SDValue, 4> MemOps;
2923 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2924 ++firstRegToSaveIndex, ++i) {
2925 const TargetRegisterClass *RC;
2926 if (AFI->isThumb1OnlyFunction())
2927 RC = &ARM::tGPRRegClass;
2929 RC = &ARM::GPRRegClass;
2931 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2932 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2934 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2935 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2937 MemOps.push_back(Store);
2938 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2939 DAG.getConstant(4, getPointerTy()));
2942 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2944 if (!MemOps.empty())
2945 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2949 // We cannot allocate a zero-byte object for the first variadic argument,
2950 // so just make up a size.
2953 // This will point to the next argument passed via stack.
2954 return MFI->CreateFixedObject(
2955 ArgSize, ArgOffset, !ForceMutable);
2959 // Setup stack frame, the va_list pointer will start from.
2961 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2962 SDLoc dl, SDValue &Chain,
2964 unsigned TotalArgRegsSaveSize,
2965 bool ForceMutable) const {
2966 MachineFunction &MF = DAG.getMachineFunction();
2967 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2969 // Try to store any remaining integer argument regs
2970 // to their spots on the stack so that they may be loaded by deferencing
2971 // the result of va_next.
2972 // If there is no regs to be stored, just point address after last
2973 // argument passed via stack.
2975 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2976 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2977 0, TotalArgRegsSaveSize);
2979 AFI->setVarArgsFrameIndex(FrameIndex);
2983 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2984 CallingConv::ID CallConv, bool isVarArg,
2985 const SmallVectorImpl<ISD::InputArg>
2987 SDLoc dl, SelectionDAG &DAG,
2988 SmallVectorImpl<SDValue> &InVals)
2990 MachineFunction &MF = DAG.getMachineFunction();
2991 MachineFrameInfo *MFI = MF.getFrameInfo();
2993 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2995 // Assign locations to all of the incoming arguments.
2996 SmallVector<CCValAssign, 16> ArgLocs;
2997 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2998 *DAG.getContext(), Prologue);
2999 CCInfo.AnalyzeFormalArguments(Ins,
3000 CCAssignFnForNode(CallConv, /* Return*/ false,
3003 SmallVector<SDValue, 16> ArgValues;
3004 int lastInsIndex = -1;
3006 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3007 unsigned CurArgIdx = 0;
3009 // Initially ArgRegsSaveSize is zero.
3010 // Then we increase this value each time we meet byval parameter.
3011 // We also increase this value in case of varargs function.
3012 AFI->setArgRegsSaveSize(0);
3014 unsigned ByValStoreOffset = 0;
3015 unsigned TotalArgRegsSaveSize = 0;
3016 unsigned ArgRegsSaveSizeMaxAlign = 4;
3018 // Calculate the amount of stack space that we need to allocate to store
3019 // byval and variadic arguments that are passed in registers.
3020 // We need to know this before we allocate the first byval or variadic
3021 // argument, as they will be allocated a stack slot below the CFA (Canonical
3022 // Frame Address, the stack pointer at entry to the function).
3023 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3024 CCValAssign &VA = ArgLocs[i];
3025 if (VA.isMemLoc()) {
3026 int index = VA.getValNo();
3027 if (index != lastInsIndex) {
3028 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3029 if (Flags.isByVal()) {
3030 unsigned ExtraArgRegsSize;
3031 unsigned ExtraArgRegsSaveSize;
3032 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3033 Flags.getByValSize(),
3034 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3036 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3037 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3038 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3039 CCInfo.nextInRegsParam();
3041 lastInsIndex = index;
3045 CCInfo.rewindByValRegsInfo();
3048 unsigned ExtraArgRegsSize;
3049 unsigned ExtraArgRegsSaveSize;
3050 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3051 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3052 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3054 // If the arg regs save area contains N-byte aligned values, the
3055 // bottom of it must be at least N-byte aligned.
3056 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3057 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3059 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3060 CCValAssign &VA = ArgLocs[i];
3061 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3062 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3063 // Arguments stored in registers.
3064 if (VA.isRegLoc()) {
3065 EVT RegVT = VA.getLocVT();
3067 if (VA.needsCustom()) {
3068 // f64 and vector types are split up into multiple registers or
3069 // combinations of registers and stack slots.
3070 if (VA.getLocVT() == MVT::v2f64) {
3071 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3073 VA = ArgLocs[++i]; // skip ahead to next loc
3075 if (VA.isMemLoc()) {
3076 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3077 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3078 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3079 MachinePointerInfo::getFixedStack(FI),
3080 false, false, false, 0);
3082 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3085 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3086 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3087 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3088 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3089 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3091 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3094 const TargetRegisterClass *RC;
3096 if (RegVT == MVT::f32)
3097 RC = &ARM::SPRRegClass;
3098 else if (RegVT == MVT::f64)
3099 RC = &ARM::DPRRegClass;
3100 else if (RegVT == MVT::v2f64)
3101 RC = &ARM::QPRRegClass;
3102 else if (RegVT == MVT::i32)
3103 RC = AFI->isThumb1OnlyFunction() ?
3104 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3105 (const TargetRegisterClass*)&ARM::GPRRegClass;
3107 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3109 // Transform the arguments in physical registers into virtual ones.
3110 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3111 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3114 // If this is an 8 or 16-bit value, it is really passed promoted
3115 // to 32 bits. Insert an assert[sz]ext to capture this, then
3116 // truncate to the right size.
3117 switch (VA.getLocInfo()) {
3118 default: llvm_unreachable("Unknown loc info!");
3119 case CCValAssign::Full: break;
3120 case CCValAssign::BCvt:
3121 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3123 case CCValAssign::SExt:
3124 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3125 DAG.getValueType(VA.getValVT()));
3126 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3128 case CCValAssign::ZExt:
3129 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3130 DAG.getValueType(VA.getValVT()));
3131 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3135 InVals.push_back(ArgValue);
3137 } else { // VA.isRegLoc()
3140 assert(VA.isMemLoc());
3141 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3143 int index = ArgLocs[i].getValNo();
3145 // Some Ins[] entries become multiple ArgLoc[] entries.
3146 // Process them only once.
3147 if (index != lastInsIndex)
3149 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3150 // FIXME: For now, all byval parameter objects are marked mutable.
3151 // This can be changed with more analysis.
3152 // In case of tail call optimization mark all arguments mutable.
3153 // Since they could be overwritten by lowering of arguments in case of
3155 if (Flags.isByVal()) {
3156 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3158 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3159 int FrameIndex = StoreByValRegs(
3160 CCInfo, DAG, dl, Chain, CurOrigArg,
3162 Ins[VA.getValNo()].PartOffset,
3163 VA.getLocMemOffset(),
3164 Flags.getByValSize(),
3165 true /*force mutable frames*/,
3167 TotalArgRegsSaveSize);
3168 ByValStoreOffset += Flags.getByValSize();
3169 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3170 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3171 CCInfo.nextInRegsParam();
3173 unsigned FIOffset = VA.getLocMemOffset();
3174 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3177 // Create load nodes to retrieve arguments from the stack.
3178 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3179 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3180 MachinePointerInfo::getFixedStack(FI),
3181 false, false, false, 0));
3183 lastInsIndex = index;
3190 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3191 CCInfo.getNextStackOffset(),
3192 TotalArgRegsSaveSize);
3194 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3199 /// isFloatingPointZero - Return true if this is +0.0.
3200 static bool isFloatingPointZero(SDValue Op) {
3201 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3202 return CFP->getValueAPF().isPosZero();
3203 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3204 // Maybe this has already been legalized into the constant pool?
3205 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3206 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3207 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3208 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3209 return CFP->getValueAPF().isPosZero();
3215 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3216 /// the given operands.
3218 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3219 SDValue &ARMcc, SelectionDAG &DAG,
3221 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3222 unsigned C = RHSC->getZExtValue();
3223 if (!isLegalICmpImmediate(C)) {
3224 // Constant does not fit, try adjusting it by one?
3229 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3230 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3231 RHS = DAG.getConstant(C-1, MVT::i32);
3236 if (C != 0 && isLegalICmpImmediate(C-1)) {
3237 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3238 RHS = DAG.getConstant(C-1, MVT::i32);
3243 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3244 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3245 RHS = DAG.getConstant(C+1, MVT::i32);
3250 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3251 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3252 RHS = DAG.getConstant(C+1, MVT::i32);
3259 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3260 ARMISD::NodeType CompareType;
3263 CompareType = ARMISD::CMP;
3268 CompareType = ARMISD::CMPZ;
3271 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3272 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3275 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3277 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3280 if (!isFloatingPointZero(RHS))
3281 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3283 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3284 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3287 /// duplicateCmp - Glue values can have only one use, so this function
3288 /// duplicates a comparison node.
3290 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3291 unsigned Opc = Cmp.getOpcode();
3293 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3294 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3296 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3297 Cmp = Cmp.getOperand(0);
3298 Opc = Cmp.getOpcode();
3299 if (Opc == ARMISD::CMPFP)
3300 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3302 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3303 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3305 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3308 std::pair<SDValue, SDValue>
3309 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3310 SDValue &ARMcc) const {
3311 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3313 SDValue Value, OverflowCmp;
3314 SDValue LHS = Op.getOperand(0);
3315 SDValue RHS = Op.getOperand(1);
3318 // FIXME: We are currently always generating CMPs because we don't support
3319 // generating CMN through the backend. This is not as good as the natural
3320 // CMP case because it causes a register dependency and cannot be folded
3323 switch (Op.getOpcode()) {
3325 llvm_unreachable("Unknown overflow instruction!");
3327 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3328 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3329 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3332 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3333 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3334 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3337 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3338 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3339 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3342 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3343 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3344 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3348 return std::make_pair(Value, OverflowCmp);
3353 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3354 // Let legalize expand this if it isn't a legal type yet.
3355 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3358 SDValue Value, OverflowCmp;
3360 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3361 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3362 // We use 0 and 1 as false and true values.
3363 SDValue TVal = DAG.getConstant(1, MVT::i32);
3364 SDValue FVal = DAG.getConstant(0, MVT::i32);
3365 EVT VT = Op.getValueType();
3367 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3368 ARMcc, CCR, OverflowCmp);
3370 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3371 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3375 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3376 SDValue Cond = Op.getOperand(0);
3377 SDValue SelectTrue = Op.getOperand(1);
3378 SDValue SelectFalse = Op.getOperand(2);
3380 unsigned Opc = Cond.getOpcode();
3382 if (Cond.getResNo() == 1 &&
3383 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3384 Opc == ISD::USUBO)) {
3385 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3388 SDValue Value, OverflowCmp;
3390 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3391 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3392 EVT VT = Op.getValueType();
3394 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3395 ARMcc, CCR, OverflowCmp);
3401 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3402 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3404 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3405 const ConstantSDNode *CMOVTrue =
3406 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3407 const ConstantSDNode *CMOVFalse =
3408 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3410 if (CMOVTrue && CMOVFalse) {
3411 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3412 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3416 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3418 False = SelectFalse;
3419 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3424 if (True.getNode() && False.getNode()) {
3425 EVT VT = Op.getValueType();
3426 SDValue ARMcc = Cond.getOperand(2);
3427 SDValue CCR = Cond.getOperand(3);
3428 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3429 assert(True.getValueType() == VT);
3430 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3435 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3436 // undefined bits before doing a full-word comparison with zero.
3437 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3438 DAG.getConstant(1, Cond.getValueType()));
3440 return DAG.getSelectCC(dl, Cond,
3441 DAG.getConstant(0, Cond.getValueType()),
3442 SelectTrue, SelectFalse, ISD::SETNE);
3445 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3446 if (CC == ISD::SETNE)
3448 return ISD::getSetCCInverse(CC, true);
3451 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3452 bool &swpCmpOps, bool &swpVselOps) {
3453 // Start by selecting the GE condition code for opcodes that return true for
3455 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3457 CondCode = ARMCC::GE;
3459 // and GT for opcodes that return false for 'equality'.
3460 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3462 CondCode = ARMCC::GT;
3464 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3465 // to swap the compare operands.
3466 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3470 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3471 // If we have an unordered opcode, we need to swap the operands to the VSEL
3472 // instruction (effectively negating the condition).
3474 // This also has the effect of swapping which one of 'less' or 'greater'
3475 // returns true, so we also swap the compare operands. It also switches
3476 // whether we return true for 'equality', so we compensate by picking the
3477 // opposite condition code to our original choice.
3478 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3479 CC == ISD::SETUGT) {
3480 swpCmpOps = !swpCmpOps;
3481 swpVselOps = !swpVselOps;
3482 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3485 // 'ordered' is 'anything but unordered', so use the VS condition code and
3486 // swap the VSEL operands.
3487 if (CC == ISD::SETO) {
3488 CondCode = ARMCC::VS;
3492 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3493 // code and swap the VSEL operands.
3494 if (CC == ISD::SETUNE) {
3495 CondCode = ARMCC::EQ;
3500 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3501 EVT VT = Op.getValueType();
3502 SDValue LHS = Op.getOperand(0);
3503 SDValue RHS = Op.getOperand(1);
3504 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3505 SDValue TrueVal = Op.getOperand(2);
3506 SDValue FalseVal = Op.getOperand(3);
3509 if (LHS.getValueType() == MVT::i32) {
3510 // Try to generate VSEL on ARMv8.
3511 // The VSEL instruction can't use all the usual ARM condition
3512 // codes: it only has two bits to select the condition code, so it's
3513 // constrained to use only GE, GT, VS and EQ.
3515 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3516 // swap the operands of the previous compare instruction (effectively
3517 // inverting the compare condition, swapping 'less' and 'greater') and
3518 // sometimes need to swap the operands to the VSEL (which inverts the
3519 // condition in the sense of firing whenever the previous condition didn't)
3520 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3521 TrueVal.getValueType() == MVT::f64)) {
3522 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3523 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3524 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3525 CC = getInverseCCForVSEL(CC);
3526 std::swap(TrueVal, FalseVal);
3531 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3532 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3533 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3537 ARMCC::CondCodes CondCode, CondCode2;
3538 FPCCToARMCC(CC, CondCode, CondCode2);
3540 // Try to generate VSEL on ARMv8.
3541 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3542 TrueVal.getValueType() == MVT::f64)) {
3543 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3544 // same operands, as follows:
3545 // c = fcmp [ogt, olt, ugt, ult] a, b
3547 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3548 // handled differently than the original code sequence.
3549 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3551 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3552 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3553 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3554 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3557 bool swpCmpOps = false;
3558 bool swpVselOps = false;
3559 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3561 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3562 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3564 std::swap(LHS, RHS);
3566 std::swap(TrueVal, FalseVal);
3570 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3571 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3572 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3573 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3575 if (CondCode2 != ARMCC::AL) {
3576 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3577 // FIXME: Needs another CMP because flag can have but one use.
3578 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3579 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3580 Result, TrueVal, ARMcc2, CCR, Cmp2);
3585 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3586 /// to morph to an integer compare sequence.
3587 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3588 const ARMSubtarget *Subtarget) {
3589 SDNode *N = Op.getNode();
3590 if (!N->hasOneUse())
3591 // Otherwise it requires moving the value from fp to integer registers.
3593 if (!N->getNumValues())
3595 EVT VT = Op.getValueType();
3596 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3597 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3598 // vmrs are very slow, e.g. cortex-a8.
3601 if (isFloatingPointZero(Op)) {
3605 return ISD::isNormalLoad(N);
3608 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3609 if (isFloatingPointZero(Op))
3610 return DAG.getConstant(0, MVT::i32);
3612 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3613 return DAG.getLoad(MVT::i32, SDLoc(Op),
3614 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3615 Ld->isVolatile(), Ld->isNonTemporal(),
3616 Ld->isInvariant(), Ld->getAlignment());
3618 llvm_unreachable("Unknown VFP cmp argument!");
3621 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3622 SDValue &RetVal1, SDValue &RetVal2) {
3623 if (isFloatingPointZero(Op)) {
3624 RetVal1 = DAG.getConstant(0, MVT::i32);
3625 RetVal2 = DAG.getConstant(0, MVT::i32);
3629 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3630 SDValue Ptr = Ld->getBasePtr();
3631 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3632 Ld->getChain(), Ptr,
3633 Ld->getPointerInfo(),
3634 Ld->isVolatile(), Ld->isNonTemporal(),
3635 Ld->isInvariant(), Ld->getAlignment());
3637 EVT PtrType = Ptr.getValueType();
3638 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3639 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3640 PtrType, Ptr, DAG.getConstant(4, PtrType));
3641 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3642 Ld->getChain(), NewPtr,
3643 Ld->getPointerInfo().getWithOffset(4),
3644 Ld->isVolatile(), Ld->isNonTemporal(),
3645 Ld->isInvariant(), NewAlign);
3649 llvm_unreachable("Unknown VFP cmp argument!");
3652 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3653 /// f32 and even f64 comparisons to integer ones.
3655 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3656 SDValue Chain = Op.getOperand(0);
3657 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3658 SDValue LHS = Op.getOperand(2);
3659 SDValue RHS = Op.getOperand(3);
3660 SDValue Dest = Op.getOperand(4);
3663 bool LHSSeenZero = false;
3664 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3665 bool RHSSeenZero = false;
3666 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3667 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3668 // If unsafe fp math optimization is enabled and there are no other uses of
3669 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3670 // to an integer comparison.
3671 if (CC == ISD::SETOEQ)
3673 else if (CC == ISD::SETUNE)
3676 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3678 if (LHS.getValueType() == MVT::f32) {
3679 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3680 bitcastf32Toi32(LHS, DAG), Mask);
3681 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3682 bitcastf32Toi32(RHS, DAG), Mask);
3683 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3684 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3685 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3686 Chain, Dest, ARMcc, CCR, Cmp);
3691 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3692 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3693 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3694 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3695 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3696 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3697 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3698 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3699 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3705 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3706 SDValue Chain = Op.getOperand(0);
3707 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3708 SDValue LHS = Op.getOperand(2);
3709 SDValue RHS = Op.getOperand(3);
3710 SDValue Dest = Op.getOperand(4);
3713 if (LHS.getValueType() == MVT::i32) {
3715 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3716 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3717 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3718 Chain, Dest, ARMcc, CCR, Cmp);
3721 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3723 if (getTargetMachine().Options.UnsafeFPMath &&
3724 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3725 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3726 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3727 if (Result.getNode())
3731 ARMCC::CondCodes CondCode, CondCode2;
3732 FPCCToARMCC(CC, CondCode, CondCode2);
3734 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3735 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3736 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3737 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3738 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3739 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3740 if (CondCode2 != ARMCC::AL) {
3741 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3742 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3743 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3748 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3749 SDValue Chain = Op.getOperand(0);
3750 SDValue Table = Op.getOperand(1);
3751 SDValue Index = Op.getOperand(2);
3754 EVT PTy = getPointerTy();
3755 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3756 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3757 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3758 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3759 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3760 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3761 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3762 if (Subtarget->isThumb2()) {
3763 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3764 // which does another jump to the destination. This also makes it easier
3765 // to translate it to TBB / TBH later.
3766 // FIXME: This might not work if the function is extremely large.
3767 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3768 Addr, Op.getOperand(2), JTI, UId);
3770 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3771 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3772 MachinePointerInfo::getJumpTable(),
3773 false, false, false, 0);
3774 Chain = Addr.getValue(1);
3775 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3776 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3778 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3779 MachinePointerInfo::getJumpTable(),
3780 false, false, false, 0);
3781 Chain = Addr.getValue(1);
3782 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3786 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3787 EVT VT = Op.getValueType();
3790 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3791 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3793 return DAG.UnrollVectorOp(Op.getNode());
3796 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3797 "Invalid type for custom lowering!");
3798 if (VT != MVT::v4i16)
3799 return DAG.UnrollVectorOp(Op.getNode());
3801 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3802 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3805 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3806 EVT VT = Op.getValueType();
3808 return LowerVectorFP_TO_INT(Op, DAG);
3813 switch (Op.getOpcode()) {
3814 default: llvm_unreachable("Invalid opcode!");
3815 case ISD::FP_TO_SINT:
3816 Opc = ARMISD::FTOSI;
3818 case ISD::FP_TO_UINT:
3819 Opc = ARMISD::FTOUI;
3822 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3823 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3826 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3827 EVT VT = Op.getValueType();
3830 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3831 if (VT.getVectorElementType() == MVT::f32)
3833 return DAG.UnrollVectorOp(Op.getNode());
3836 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3837 "Invalid type for custom lowering!");
3838 if (VT != MVT::v4f32)
3839 return DAG.UnrollVectorOp(Op.getNode());
3843 switch (Op.getOpcode()) {
3844 default: llvm_unreachable("Invalid opcode!");
3845 case ISD::SINT_TO_FP:
3846 CastOpc = ISD::SIGN_EXTEND;
3847 Opc = ISD::SINT_TO_FP;
3849 case ISD::UINT_TO_FP:
3850 CastOpc = ISD::ZERO_EXTEND;
3851 Opc = ISD::UINT_TO_FP;
3855 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3856 return DAG.getNode(Opc, dl, VT, Op);
3859 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3860 EVT VT = Op.getValueType();
3862 return LowerVectorINT_TO_FP(Op, DAG);
3867 switch (Op.getOpcode()) {
3868 default: llvm_unreachable("Invalid opcode!");
3869 case ISD::SINT_TO_FP:
3870 Opc = ARMISD::SITOF;
3872 case ISD::UINT_TO_FP:
3873 Opc = ARMISD::UITOF;
3877 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3878 return DAG.getNode(Opc, dl, VT, Op);
3881 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3882 // Implement fcopysign with a fabs and a conditional fneg.
3883 SDValue Tmp0 = Op.getOperand(0);
3884 SDValue Tmp1 = Op.getOperand(1);
3886 EVT VT = Op.getValueType();
3887 EVT SrcVT = Tmp1.getValueType();
3888 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3889 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3890 bool UseNEON = !InGPR && Subtarget->hasNEON();
3893 // Use VBSL to copy the sign bit.
3894 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3895 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3896 DAG.getTargetConstant(EncodedVal, MVT::i32));
3897 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3899 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3900 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3901 DAG.getConstant(32, MVT::i32));
3902 else /*if (VT == MVT::f32)*/
3903 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3904 if (SrcVT == MVT::f32) {
3905 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3907 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3908 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3909 DAG.getConstant(32, MVT::i32));
3910 } else if (VT == MVT::f32)
3911 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3912 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3913 DAG.getConstant(32, MVT::i32));
3914 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3915 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3917 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3919 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3920 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3921 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3923 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3924 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3925 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3926 if (VT == MVT::f32) {
3927 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3928 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3929 DAG.getConstant(0, MVT::i32));
3931 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3937 // Bitcast operand 1 to i32.
3938 if (SrcVT == MVT::f64)
3939 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3941 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3943 // Or in the signbit with integer operations.
3944 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3945 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3946 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3947 if (VT == MVT::f32) {
3948 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3949 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3950 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3951 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3954 // f64: Or the high part with signbit and then combine two parts.
3955 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3957 SDValue Lo = Tmp0.getValue(0);
3958 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3959 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3960 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3963 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3964 MachineFunction &MF = DAG.getMachineFunction();
3965 MachineFrameInfo *MFI = MF.getFrameInfo();
3966 MFI->setReturnAddressIsTaken(true);
3968 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3971 EVT VT = Op.getValueType();
3973 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3975 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3976 SDValue Offset = DAG.getConstant(4, MVT::i32);
3977 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3978 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3979 MachinePointerInfo(), false, false, false, 0);
3982 // Return LR, which contains the return address. Mark it an implicit live-in.
3983 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3984 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3987 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3988 const ARMBaseRegisterInfo &ARI =
3989 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3990 MachineFunction &MF = DAG.getMachineFunction();
3991 MachineFrameInfo *MFI = MF.getFrameInfo();
3992 MFI->setFrameAddressIsTaken(true);
3994 EVT VT = Op.getValueType();
3995 SDLoc dl(Op); // FIXME probably not meaningful
3996 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3997 unsigned FrameReg = ARI.getFrameRegister(MF);
3998 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4000 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4001 MachinePointerInfo(),
4002 false, false, false, 0);
4006 // FIXME? Maybe this could be a TableGen attribute on some registers and
4007 // this table could be generated automatically from RegInfo.
4008 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4010 unsigned Reg = StringSwitch<unsigned>(RegName)
4011 .Case("sp", ARM::SP)
4015 report_fatal_error("Invalid register name global variable");
4018 /// ExpandBITCAST - If the target supports VFP, this function is called to
4019 /// expand a bit convert where either the source or destination type is i64 to
4020 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4021 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4022 /// vectors), since the legalizer won't know what to do with that.
4023 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4024 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4026 SDValue Op = N->getOperand(0);
4028 // This function is only supposed to be called for i64 types, either as the
4029 // source or destination of the bit convert.
4030 EVT SrcVT = Op.getValueType();
4031 EVT DstVT = N->getValueType(0);
4032 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4033 "ExpandBITCAST called for non-i64 type");
4035 // Turn i64->f64 into VMOVDRR.
4036 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4037 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4038 DAG.getConstant(0, MVT::i32));
4039 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4040 DAG.getConstant(1, MVT::i32));
4041 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4042 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4045 // Turn f64->i64 into VMOVRRD.
4046 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4048 if (TLI.isBigEndian() && SrcVT.isVector() &&
4049 SrcVT.getVectorNumElements() > 1)
4050 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4051 DAG.getVTList(MVT::i32, MVT::i32),
4052 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4054 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4055 DAG.getVTList(MVT::i32, MVT::i32), Op);
4056 // Merge the pieces into a single i64 value.
4057 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4063 /// getZeroVector - Returns a vector of specified type with all zero elements.
4064 /// Zero vectors are used to represent vector negation and in those cases
4065 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4066 /// not support i64 elements, so sometimes the zero vectors will need to be
4067 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4069 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4070 assert(VT.isVector() && "Expected a vector type");
4071 // The canonical modified immediate encoding of a zero vector is....0!
4072 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4073 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4074 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4075 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4078 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4079 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4080 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4081 SelectionDAG &DAG) const {
4082 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4083 EVT VT = Op.getValueType();
4084 unsigned VTBits = VT.getSizeInBits();
4086 SDValue ShOpLo = Op.getOperand(0);
4087 SDValue ShOpHi = Op.getOperand(1);
4088 SDValue ShAmt = Op.getOperand(2);
4090 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4092 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4094 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4095 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4096 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4097 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4098 DAG.getConstant(VTBits, MVT::i32));
4099 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4100 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4101 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4103 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4104 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4106 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4107 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4110 SDValue Ops[2] = { Lo, Hi };
4111 return DAG.getMergeValues(Ops, dl);
4114 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4115 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4116 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4117 SelectionDAG &DAG) const {
4118 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4119 EVT VT = Op.getValueType();
4120 unsigned VTBits = VT.getSizeInBits();
4122 SDValue ShOpLo = Op.getOperand(0);
4123 SDValue ShOpHi = Op.getOperand(1);
4124 SDValue ShAmt = Op.getOperand(2);
4127 assert(Op.getOpcode() == ISD::SHL_PARTS);
4128 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4129 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4130 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4131 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4132 DAG.getConstant(VTBits, MVT::i32));
4133 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4134 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4136 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4137 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4138 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4140 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4141 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4144 SDValue Ops[2] = { Lo, Hi };
4145 return DAG.getMergeValues(Ops, dl);
4148 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4149 SelectionDAG &DAG) const {
4150 // The rounding mode is in bits 23:22 of the FPSCR.
4151 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4152 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4153 // so that the shift + and get folded into a bitfield extract.
4155 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4156 DAG.getConstant(Intrinsic::arm_get_fpscr,
4158 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4159 DAG.getConstant(1U << 22, MVT::i32));
4160 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4161 DAG.getConstant(22, MVT::i32));
4162 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4163 DAG.getConstant(3, MVT::i32));
4166 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4167 const ARMSubtarget *ST) {
4168 EVT VT = N->getValueType(0);
4171 if (!ST->hasV6T2Ops())
4174 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4175 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4178 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4179 /// for each 16-bit element from operand, repeated. The basic idea is to
4180 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4182 /// Trace for v4i16:
4183 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4184 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4185 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4186 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4187 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4188 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4189 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4190 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4191 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4192 EVT VT = N->getValueType(0);
4195 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4196 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4197 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4198 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4199 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4200 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4203 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4204 /// bit-count for each 16-bit element from the operand. We need slightly
4205 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4206 /// 64/128-bit registers.
4208 /// Trace for v4i16:
4209 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4210 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4211 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4212 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4213 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4214 EVT VT = N->getValueType(0);
4217 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4218 if (VT.is64BitVector()) {
4219 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4220 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4221 DAG.getIntPtrConstant(0));
4223 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4224 BitCounts, DAG.getIntPtrConstant(0));
4225 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4229 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4230 /// bit-count for each 32-bit element from the operand. The idea here is
4231 /// to split the vector into 16-bit elements, leverage the 16-bit count
4232 /// routine, and then combine the results.
4234 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4235 /// input = [v0 v1 ] (vi: 32-bit elements)
4236 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4237 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4238 /// vrev: N0 = [k1 k0 k3 k2 ]
4240 /// N1 =+[k1 k0 k3 k2 ]
4242 /// N2 =+[k1 k3 k0 k2 ]
4244 /// Extended =+[k1 k3 k0 k2 ]
4246 /// Extracted=+[k1 k3 ]
4248 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4249 EVT VT = N->getValueType(0);
4252 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4254 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4255 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4256 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4257 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4258 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4260 if (VT.is64BitVector()) {
4261 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4262 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4263 DAG.getIntPtrConstant(0));
4265 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4266 DAG.getIntPtrConstant(0));
4267 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4271 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4272 const ARMSubtarget *ST) {
4273 EVT VT = N->getValueType(0);
4275 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4276 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4277 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4278 "Unexpected type for custom ctpop lowering");
4280 if (VT.getVectorElementType() == MVT::i32)
4281 return lowerCTPOP32BitElements(N, DAG);
4283 return lowerCTPOP16BitElements(N, DAG);
4286 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4287 const ARMSubtarget *ST) {
4288 EVT VT = N->getValueType(0);
4294 // Lower vector shifts on NEON to use VSHL.
4295 assert(ST->hasNEON() && "unexpected vector shift");
4297 // Left shifts translate directly to the vshiftu intrinsic.
4298 if (N->getOpcode() == ISD::SHL)
4299 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4300 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4301 N->getOperand(0), N->getOperand(1));
4303 assert((N->getOpcode() == ISD::SRA ||
4304 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4306 // NEON uses the same intrinsics for both left and right shifts. For
4307 // right shifts, the shift amounts are negative, so negate the vector of
4309 EVT ShiftVT = N->getOperand(1).getValueType();
4310 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4311 getZeroVector(ShiftVT, DAG, dl),
4313 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4314 Intrinsic::arm_neon_vshifts :
4315 Intrinsic::arm_neon_vshiftu);
4316 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4317 DAG.getConstant(vshiftInt, MVT::i32),
4318 N->getOperand(0), NegatedCount);
4321 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4322 const ARMSubtarget *ST) {
4323 EVT VT = N->getValueType(0);
4326 // We can get here for a node like i32 = ISD::SHL i32, i64
4330 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4331 "Unknown shift to lower!");
4333 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4334 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4335 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4338 // If we are in thumb mode, we don't have RRX.
4339 if (ST->isThumb1Only()) return SDValue();
4341 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4342 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4343 DAG.getConstant(0, MVT::i32));
4344 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4345 DAG.getConstant(1, MVT::i32));
4347 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4348 // captures the result into a carry flag.
4349 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4350 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4352 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4353 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4355 // Merge the pieces into a single i64 value.
4356 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4359 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4360 SDValue TmpOp0, TmpOp1;
4361 bool Invert = false;
4365 SDValue Op0 = Op.getOperand(0);
4366 SDValue Op1 = Op.getOperand(1);
4367 SDValue CC = Op.getOperand(2);
4368 EVT VT = Op.getValueType();
4369 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4372 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4373 switch (SetCCOpcode) {
4374 default: llvm_unreachable("Illegal FP comparison");
4376 case ISD::SETNE: Invert = true; // Fallthrough
4378 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4380 case ISD::SETLT: Swap = true; // Fallthrough
4382 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4384 case ISD::SETLE: Swap = true; // Fallthrough
4386 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4387 case ISD::SETUGE: Swap = true; // Fallthrough
4388 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4389 case ISD::SETUGT: Swap = true; // Fallthrough
4390 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4391 case ISD::SETUEQ: Invert = true; // Fallthrough
4393 // Expand this to (OLT | OGT).
4397 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4398 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4400 case ISD::SETUO: Invert = true; // Fallthrough
4402 // Expand this to (OLT | OGE).
4406 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4407 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4411 // Integer comparisons.
4412 switch (SetCCOpcode) {
4413 default: llvm_unreachable("Illegal integer comparison");
4414 case ISD::SETNE: Invert = true;
4415 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4416 case ISD::SETLT: Swap = true;
4417 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4418 case ISD::SETLE: Swap = true;
4419 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4420 case ISD::SETULT: Swap = true;
4421 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4422 case ISD::SETULE: Swap = true;
4423 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4426 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4427 if (Opc == ARMISD::VCEQ) {
4430 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4432 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4435 // Ignore bitconvert.
4436 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4437 AndOp = AndOp.getOperand(0);
4439 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4441 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4442 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4449 std::swap(Op0, Op1);
4451 // If one of the operands is a constant vector zero, attempt to fold the
4452 // comparison to a specialized compare-against-zero form.
4454 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4456 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4457 if (Opc == ARMISD::VCGE)
4458 Opc = ARMISD::VCLEZ;
4459 else if (Opc == ARMISD::VCGT)
4460 Opc = ARMISD::VCLTZ;
4465 if (SingleOp.getNode()) {
4468 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4470 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4472 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4474 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4476 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4478 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4481 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4485 Result = DAG.getNOT(dl, Result, VT);
4490 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4491 /// valid vector constant for a NEON instruction with a "modified immediate"
4492 /// operand (e.g., VMOV). If so, return the encoded value.
4493 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4494 unsigned SplatBitSize, SelectionDAG &DAG,
4495 EVT &VT, bool is128Bits, NEONModImmType type) {
4496 unsigned OpCmode, Imm;
4498 // SplatBitSize is set to the smallest size that splats the vector, so a
4499 // zero vector will always have SplatBitSize == 8. However, NEON modified
4500 // immediate instructions others than VMOV do not support the 8-bit encoding
4501 // of a zero vector, and the default encoding of zero is supposed to be the
4506 switch (SplatBitSize) {
4508 if (type != VMOVModImm)
4510 // Any 1-byte value is OK. Op=0, Cmode=1110.
4511 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4514 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4518 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4519 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4520 if ((SplatBits & ~0xff) == 0) {
4521 // Value = 0x00nn: Op=x, Cmode=100x.
4526 if ((SplatBits & ~0xff00) == 0) {
4527 // Value = 0xnn00: Op=x, Cmode=101x.
4529 Imm = SplatBits >> 8;
4535 // NEON's 32-bit VMOV supports splat values where:
4536 // * only one byte is nonzero, or
4537 // * the least significant byte is 0xff and the second byte is nonzero, or
4538 // * the least significant 2 bytes are 0xff and the third is nonzero.
4539 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4540 if ((SplatBits & ~0xff) == 0) {
4541 // Value = 0x000000nn: Op=x, Cmode=000x.
4546 if ((SplatBits & ~0xff00) == 0) {
4547 // Value = 0x0000nn00: Op=x, Cmode=001x.
4549 Imm = SplatBits >> 8;
4552 if ((SplatBits & ~0xff0000) == 0) {
4553 // Value = 0x00nn0000: Op=x, Cmode=010x.
4555 Imm = SplatBits >> 16;
4558 if ((SplatBits & ~0xff000000) == 0) {
4559 // Value = 0xnn000000: Op=x, Cmode=011x.
4561 Imm = SplatBits >> 24;
4565 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4566 if (type == OtherModImm) return SDValue();
4568 if ((SplatBits & ~0xffff) == 0 &&
4569 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4570 // Value = 0x0000nnff: Op=x, Cmode=1100.
4572 Imm = SplatBits >> 8;
4576 if ((SplatBits & ~0xffffff) == 0 &&
4577 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4578 // Value = 0x00nnffff: Op=x, Cmode=1101.
4580 Imm = SplatBits >> 16;
4584 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4585 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4586 // VMOV.I32. A (very) minor optimization would be to replicate the value
4587 // and fall through here to test for a valid 64-bit splat. But, then the
4588 // caller would also need to check and handle the change in size.
4592 if (type != VMOVModImm)
4594 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4595 uint64_t BitMask = 0xff;
4597 unsigned ImmMask = 1;
4599 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4600 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4603 } else if ((SplatBits & BitMask) != 0) {
4610 if (DAG.getTargetLoweringInfo().isBigEndian())
4611 // swap higher and lower 32 bit word
4612 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4614 // Op=1, Cmode=1110.
4616 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4621 llvm_unreachable("unexpected size for isNEONModifiedImm");
4624 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4625 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4628 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4629 const ARMSubtarget *ST) const {
4633 bool IsDouble = Op.getValueType() == MVT::f64;
4634 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4636 // Try splatting with a VMOV.f32...
4637 APFloat FPVal = CFP->getValueAPF();
4638 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4641 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4642 // We have code in place to select a valid ConstantFP already, no need to
4647 // It's a float and we are trying to use NEON operations where
4648 // possible. Lower it to a splat followed by an extract.
4650 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4651 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4653 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4654 DAG.getConstant(0, MVT::i32));
4657 // The rest of our options are NEON only, make sure that's allowed before
4659 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4663 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4665 // It wouldn't really be worth bothering for doubles except for one very
4666 // important value, which does happen to match: 0.0. So make sure we don't do
4668 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4671 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4672 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4674 if (NewVal != SDValue()) {
4676 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4679 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4681 // It's a float: cast and extract a vector element.
4682 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4684 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4685 DAG.getConstant(0, MVT::i32));
4688 // Finally, try a VMVN.i32
4689 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4691 if (NewVal != SDValue()) {
4693 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4696 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4698 // It's a float: cast and extract a vector element.
4699 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4701 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4702 DAG.getConstant(0, MVT::i32));
4708 // check if an VEXT instruction can handle the shuffle mask when the
4709 // vector sources of the shuffle are the same.
4710 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4711 unsigned NumElts = VT.getVectorNumElements();
4713 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4719 // If this is a VEXT shuffle, the immediate value is the index of the first
4720 // element. The other shuffle indices must be the successive elements after
4722 unsigned ExpectedElt = Imm;
4723 for (unsigned i = 1; i < NumElts; ++i) {
4724 // Increment the expected index. If it wraps around, just follow it
4725 // back to index zero and keep going.
4727 if (ExpectedElt == NumElts)
4730 if (M[i] < 0) continue; // ignore UNDEF indices
4731 if (ExpectedElt != static_cast<unsigned>(M[i]))
4739 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4740 bool &ReverseVEXT, unsigned &Imm) {
4741 unsigned NumElts = VT.getVectorNumElements();
4742 ReverseVEXT = false;
4744 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4750 // If this is a VEXT shuffle, the immediate value is the index of the first
4751 // element. The other shuffle indices must be the successive elements after
4753 unsigned ExpectedElt = Imm;
4754 for (unsigned i = 1; i < NumElts; ++i) {
4755 // Increment the expected index. If it wraps around, it may still be
4756 // a VEXT but the source vectors must be swapped.
4758 if (ExpectedElt == NumElts * 2) {
4763 if (M[i] < 0) continue; // ignore UNDEF indices
4764 if (ExpectedElt != static_cast<unsigned>(M[i]))
4768 // Adjust the index value if the source operands will be swapped.
4775 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4776 /// instruction with the specified blocksize. (The order of the elements
4777 /// within each block of the vector is reversed.)
4778 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4779 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4780 "Only possible block sizes for VREV are: 16, 32, 64");
4782 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4786 unsigned NumElts = VT.getVectorNumElements();
4787 unsigned BlockElts = M[0] + 1;
4788 // If the first shuffle index is UNDEF, be optimistic.
4790 BlockElts = BlockSize / EltSz;
4792 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4795 for (unsigned i = 0; i < NumElts; ++i) {
4796 if (M[i] < 0) continue; // ignore UNDEF indices
4797 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4804 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4805 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4806 // range, then 0 is placed into the resulting vector. So pretty much any mask
4807 // of 8 elements can work here.
4808 return VT == MVT::v8i8 && M.size() == 8;
4811 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4812 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4816 unsigned NumElts = VT.getVectorNumElements();
4817 WhichResult = (M[0] == 0 ? 0 : 1);
4818 for (unsigned i = 0; i < NumElts; i += 2) {
4819 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4820 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4826 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4827 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4828 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4829 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4830 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4834 unsigned NumElts = VT.getVectorNumElements();
4835 WhichResult = (M[0] == 0 ? 0 : 1);
4836 for (unsigned i = 0; i < NumElts; i += 2) {
4837 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4838 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4844 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4845 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4849 unsigned NumElts = VT.getVectorNumElements();
4850 WhichResult = (M[0] == 0 ? 0 : 1);
4851 for (unsigned i = 0; i != NumElts; ++i) {
4852 if (M[i] < 0) continue; // ignore UNDEF indices
4853 if ((unsigned) M[i] != 2 * i + WhichResult)
4857 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4858 if (VT.is64BitVector() && EltSz == 32)
4864 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4865 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4866 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4867 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4868 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4872 unsigned Half = VT.getVectorNumElements() / 2;
4873 WhichResult = (M[0] == 0 ? 0 : 1);
4874 for (unsigned j = 0; j != 2; ++j) {
4875 unsigned Idx = WhichResult;
4876 for (unsigned i = 0; i != Half; ++i) {
4877 int MIdx = M[i + j * Half];
4878 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4884 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4885 if (VT.is64BitVector() && EltSz == 32)
4891 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4892 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4896 unsigned NumElts = VT.getVectorNumElements();
4897 WhichResult = (M[0] == 0 ? 0 : 1);
4898 unsigned Idx = WhichResult * NumElts / 2;
4899 for (unsigned i = 0; i != NumElts; i += 2) {
4900 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4901 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4906 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4907 if (VT.is64BitVector() && EltSz == 32)
4913 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4914 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4915 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4916 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4917 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4921 unsigned NumElts = VT.getVectorNumElements();
4922 WhichResult = (M[0] == 0 ? 0 : 1);
4923 unsigned Idx = WhichResult * NumElts / 2;
4924 for (unsigned i = 0; i != NumElts; i += 2) {
4925 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4926 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4931 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4932 if (VT.is64BitVector() && EltSz == 32)
4938 /// \return true if this is a reverse operation on an vector.
4939 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4940 unsigned NumElts = VT.getVectorNumElements();
4941 // Make sure the mask has the right size.
4942 if (NumElts != M.size())
4945 // Look for <15, ..., 3, -1, 1, 0>.
4946 for (unsigned i = 0; i != NumElts; ++i)
4947 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4953 // If N is an integer constant that can be moved into a register in one
4954 // instruction, return an SDValue of such a constant (will become a MOV
4955 // instruction). Otherwise return null.
4956 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4957 const ARMSubtarget *ST, SDLoc dl) {
4959 if (!isa<ConstantSDNode>(N))
4961 Val = cast<ConstantSDNode>(N)->getZExtValue();
4963 if (ST->isThumb1Only()) {
4964 if (Val <= 255 || ~Val <= 255)
4965 return DAG.getConstant(Val, MVT::i32);
4967 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4968 return DAG.getConstant(Val, MVT::i32);
4973 // If this is a case we can't handle, return null and let the default
4974 // expansion code take care of it.
4975 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4976 const ARMSubtarget *ST) const {
4977 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4979 EVT VT = Op.getValueType();
4981 APInt SplatBits, SplatUndef;
4982 unsigned SplatBitSize;
4984 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4985 if (SplatBitSize <= 64) {
4986 // Check if an immediate VMOV works.
4988 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4989 SplatUndef.getZExtValue(), SplatBitSize,
4990 DAG, VmovVT, VT.is128BitVector(),
4992 if (Val.getNode()) {
4993 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4994 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4997 // Try an immediate VMVN.
4998 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4999 Val = isNEONModifiedImm(NegatedImm,
5000 SplatUndef.getZExtValue(), SplatBitSize,
5001 DAG, VmovVT, VT.is128BitVector(),
5003 if (Val.getNode()) {
5004 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5005 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5008 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5009 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5010 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5012 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5013 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5019 // Scan through the operands to see if only one value is used.
5021 // As an optimisation, even if more than one value is used it may be more
5022 // profitable to splat with one value then change some lanes.
5024 // Heuristically we decide to do this if the vector has a "dominant" value,
5025 // defined as splatted to more than half of the lanes.
5026 unsigned NumElts = VT.getVectorNumElements();
5027 bool isOnlyLowElement = true;
5028 bool usesOnlyOneValue = true;
5029 bool hasDominantValue = false;
5030 bool isConstant = true;
5032 // Map of the number of times a particular SDValue appears in the
5034 DenseMap<SDValue, unsigned> ValueCounts;
5036 for (unsigned i = 0; i < NumElts; ++i) {
5037 SDValue V = Op.getOperand(i);
5038 if (V.getOpcode() == ISD::UNDEF)
5041 isOnlyLowElement = false;
5042 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5045 ValueCounts.insert(std::make_pair(V, 0));
5046 unsigned &Count = ValueCounts[V];
5048 // Is this value dominant? (takes up more than half of the lanes)
5049 if (++Count > (NumElts / 2)) {
5050 hasDominantValue = true;
5054 if (ValueCounts.size() != 1)
5055 usesOnlyOneValue = false;
5056 if (!Value.getNode() && ValueCounts.size() > 0)
5057 Value = ValueCounts.begin()->first;
5059 if (ValueCounts.size() == 0)
5060 return DAG.getUNDEF(VT);
5062 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5063 // Keep going if we are hitting this case.
5064 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5065 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5067 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5069 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5070 // i32 and try again.
5071 if (hasDominantValue && EltSize <= 32) {
5075 // If we are VDUPing a value that comes directly from a vector, that will
5076 // cause an unnecessary move to and from a GPR, where instead we could
5077 // just use VDUPLANE. We can only do this if the lane being extracted
5078 // is at a constant index, as the VDUP from lane instructions only have
5079 // constant-index forms.
5080 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5081 isa<ConstantSDNode>(Value->getOperand(1))) {
5082 // We need to create a new undef vector to use for the VDUPLANE if the
5083 // size of the vector from which we get the value is different than the
5084 // size of the vector that we need to create. We will insert the element
5085 // such that the register coalescer will remove unnecessary copies.
5086 if (VT != Value->getOperand(0).getValueType()) {
5087 ConstantSDNode *constIndex;
5088 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5089 assert(constIndex && "The index is not a constant!");
5090 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5091 VT.getVectorNumElements();
5092 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5093 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5094 Value, DAG.getConstant(index, MVT::i32)),
5095 DAG.getConstant(index, MVT::i32));
5097 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5098 Value->getOperand(0), Value->getOperand(1));
5100 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5102 if (!usesOnlyOneValue) {
5103 // The dominant value was splatted as 'N', but we now have to insert
5104 // all differing elements.
5105 for (unsigned I = 0; I < NumElts; ++I) {
5106 if (Op.getOperand(I) == Value)
5108 SmallVector<SDValue, 3> Ops;
5110 Ops.push_back(Op.getOperand(I));
5111 Ops.push_back(DAG.getConstant(I, MVT::i32));
5112 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5117 if (VT.getVectorElementType().isFloatingPoint()) {
5118 SmallVector<SDValue, 8> Ops;
5119 for (unsigned i = 0; i < NumElts; ++i)
5120 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5122 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5123 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5124 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5126 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5128 if (usesOnlyOneValue) {
5129 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5130 if (isConstant && Val.getNode())
5131 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5135 // If all elements are constants and the case above didn't get hit, fall back
5136 // to the default expansion, which will generate a load from the constant
5141 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5143 SDValue shuffle = ReconstructShuffle(Op, DAG);
5144 if (shuffle != SDValue())
5148 // Vectors with 32- or 64-bit elements can be built by directly assigning
5149 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5150 // will be legalized.
5151 if (EltSize >= 32) {
5152 // Do the expansion with floating-point types, since that is what the VFP
5153 // registers are defined to use, and since i64 is not legal.
5154 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5155 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5156 SmallVector<SDValue, 8> Ops;
5157 for (unsigned i = 0; i < NumElts; ++i)
5158 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5159 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5160 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5163 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5164 // know the default expansion would otherwise fall back on something even
5165 // worse. For a vector with one or two non-undef values, that's
5166 // scalar_to_vector for the elements followed by a shuffle (provided the
5167 // shuffle is valid for the target) and materialization element by element
5168 // on the stack followed by a load for everything else.
5169 if (!isConstant && !usesOnlyOneValue) {
5170 SDValue Vec = DAG.getUNDEF(VT);
5171 for (unsigned i = 0 ; i < NumElts; ++i) {
5172 SDValue V = Op.getOperand(i);
5173 if (V.getOpcode() == ISD::UNDEF)
5175 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5176 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5184 // Gather data to see if the operation can be modelled as a
5185 // shuffle in combination with VEXTs.
5186 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5187 SelectionDAG &DAG) const {
5189 EVT VT = Op.getValueType();
5190 unsigned NumElts = VT.getVectorNumElements();
5192 SmallVector<SDValue, 2> SourceVecs;
5193 SmallVector<unsigned, 2> MinElts;
5194 SmallVector<unsigned, 2> MaxElts;
5196 for (unsigned i = 0; i < NumElts; ++i) {
5197 SDValue V = Op.getOperand(i);
5198 if (V.getOpcode() == ISD::UNDEF)
5200 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5201 // A shuffle can only come from building a vector from various
5202 // elements of other vectors.
5204 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5205 VT.getVectorElementType()) {
5206 // This code doesn't know how to handle shuffles where the vector
5207 // element types do not match (this happens because type legalization
5208 // promotes the return type of EXTRACT_VECTOR_ELT).
5209 // FIXME: It might be appropriate to extend this code to handle
5210 // mismatched types.
5214 // Record this extraction against the appropriate vector if possible...
5215 SDValue SourceVec = V.getOperand(0);
5216 // If the element number isn't a constant, we can't effectively
5217 // analyze what's going on.
5218 if (!isa<ConstantSDNode>(V.getOperand(1)))
5220 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5221 bool FoundSource = false;
5222 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5223 if (SourceVecs[j] == SourceVec) {
5224 if (MinElts[j] > EltNo)
5226 if (MaxElts[j] < EltNo)
5233 // Or record a new source if not...
5235 SourceVecs.push_back(SourceVec);
5236 MinElts.push_back(EltNo);
5237 MaxElts.push_back(EltNo);
5241 // Currently only do something sane when at most two source vectors
5243 if (SourceVecs.size() > 2)
5246 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5247 int VEXTOffsets[2] = {0, 0};
5249 // This loop extracts the usage patterns of the source vectors
5250 // and prepares appropriate SDValues for a shuffle if possible.
5251 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5252 if (SourceVecs[i].getValueType() == VT) {
5253 // No VEXT necessary
5254 ShuffleSrcs[i] = SourceVecs[i];
5257 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5258 // It probably isn't worth padding out a smaller vector just to
5259 // break it down again in a shuffle.
5263 // Since only 64-bit and 128-bit vectors are legal on ARM and
5264 // we've eliminated the other cases...
5265 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5266 "unexpected vector sizes in ReconstructShuffle");
5268 if (MaxElts[i] - MinElts[i] >= NumElts) {
5269 // Span too large for a VEXT to cope
5273 if (MinElts[i] >= NumElts) {
5274 // The extraction can just take the second half
5275 VEXTOffsets[i] = NumElts;
5276 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5278 DAG.getIntPtrConstant(NumElts));
5279 } else if (MaxElts[i] < NumElts) {
5280 // The extraction can just take the first half
5282 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5284 DAG.getIntPtrConstant(0));
5286 // An actual VEXT is needed
5287 VEXTOffsets[i] = MinElts[i];
5288 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5290 DAG.getIntPtrConstant(0));
5291 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5293 DAG.getIntPtrConstant(NumElts));
5294 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5295 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5299 SmallVector<int, 8> Mask;
5301 for (unsigned i = 0; i < NumElts; ++i) {
5302 SDValue Entry = Op.getOperand(i);
5303 if (Entry.getOpcode() == ISD::UNDEF) {
5308 SDValue ExtractVec = Entry.getOperand(0);
5309 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5310 .getOperand(1))->getSExtValue();
5311 if (ExtractVec == SourceVecs[0]) {
5312 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5314 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5318 // Final check before we try to produce nonsense...
5319 if (isShuffleMaskLegal(Mask, VT))
5320 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5326 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5327 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5328 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5329 /// are assumed to be legal.
5331 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5333 if (VT.getVectorNumElements() == 4 &&
5334 (VT.is128BitVector() || VT.is64BitVector())) {
5335 unsigned PFIndexes[4];
5336 for (unsigned i = 0; i != 4; ++i) {
5340 PFIndexes[i] = M[i];
5343 // Compute the index in the perfect shuffle table.
5344 unsigned PFTableIndex =
5345 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5346 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5347 unsigned Cost = (PFEntry >> 30);
5354 unsigned Imm, WhichResult;
5356 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5357 return (EltSize >= 32 ||
5358 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5359 isVREVMask(M, VT, 64) ||
5360 isVREVMask(M, VT, 32) ||
5361 isVREVMask(M, VT, 16) ||
5362 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5363 isVTBLMask(M, VT) ||
5364 isVTRNMask(M, VT, WhichResult) ||
5365 isVUZPMask(M, VT, WhichResult) ||
5366 isVZIPMask(M, VT, WhichResult) ||
5367 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5368 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5369 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5370 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5373 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5374 /// the specified operations to build the shuffle.
5375 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5376 SDValue RHS, SelectionDAG &DAG,
5378 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5379 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5380 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5383 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5392 OP_VUZPL, // VUZP, left result
5393 OP_VUZPR, // VUZP, right result
5394 OP_VZIPL, // VZIP, left result
5395 OP_VZIPR, // VZIP, right result
5396 OP_VTRNL, // VTRN, left result
5397 OP_VTRNR // VTRN, right result
5400 if (OpNum == OP_COPY) {
5401 if (LHSID == (1*9+2)*9+3) return LHS;
5402 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5406 SDValue OpLHS, OpRHS;
5407 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5408 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5409 EVT VT = OpLHS.getValueType();
5412 default: llvm_unreachable("Unknown shuffle opcode!");
5414 // VREV divides the vector in half and swaps within the half.
5415 if (VT.getVectorElementType() == MVT::i32 ||
5416 VT.getVectorElementType() == MVT::f32)
5417 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5418 // vrev <4 x i16> -> VREV32
5419 if (VT.getVectorElementType() == MVT::i16)
5420 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5421 // vrev <4 x i8> -> VREV16
5422 assert(VT.getVectorElementType() == MVT::i8);
5423 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5428 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5429 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5433 return DAG.getNode(ARMISD::VEXT, dl, VT,
5435 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5438 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5439 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5442 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5443 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5446 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5447 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5451 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5452 ArrayRef<int> ShuffleMask,
5453 SelectionDAG &DAG) {
5454 // Check to see if we can use the VTBL instruction.
5455 SDValue V1 = Op.getOperand(0);
5456 SDValue V2 = Op.getOperand(1);
5459 SmallVector<SDValue, 8> VTBLMask;
5460 for (ArrayRef<int>::iterator
5461 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5462 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5464 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5465 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5466 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5468 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5469 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5472 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5473 SelectionDAG &DAG) {
5475 SDValue OpLHS = Op.getOperand(0);
5476 EVT VT = OpLHS.getValueType();
5478 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5479 "Expect an v8i16/v16i8 type");
5480 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5481 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5482 // extract the first 8 bytes into the top double word and the last 8 bytes
5483 // into the bottom double word. The v8i16 case is similar.
5484 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5485 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5486 DAG.getConstant(ExtractNum, MVT::i32));
5489 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5490 SDValue V1 = Op.getOperand(0);
5491 SDValue V2 = Op.getOperand(1);
5493 EVT VT = Op.getValueType();
5494 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5496 // Convert shuffles that are directly supported on NEON to target-specific
5497 // DAG nodes, instead of keeping them as shuffles and matching them again
5498 // during code selection. This is more efficient and avoids the possibility
5499 // of inconsistencies between legalization and selection.
5500 // FIXME: floating-point vectors should be canonicalized to integer vectors
5501 // of the same time so that they get CSEd properly.
5502 ArrayRef<int> ShuffleMask = SVN->getMask();
5504 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5505 if (EltSize <= 32) {
5506 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5507 int Lane = SVN->getSplatIndex();
5508 // If this is undef splat, generate it via "just" vdup, if possible.
5509 if (Lane == -1) Lane = 0;
5511 // Test if V1 is a SCALAR_TO_VECTOR.
5512 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5513 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5515 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5516 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5518 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5519 !isa<ConstantSDNode>(V1.getOperand(0))) {
5520 bool IsScalarToVector = true;
5521 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5522 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5523 IsScalarToVector = false;
5526 if (IsScalarToVector)
5527 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5529 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5530 DAG.getConstant(Lane, MVT::i32));
5535 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5538 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5539 DAG.getConstant(Imm, MVT::i32));
5542 if (isVREVMask(ShuffleMask, VT, 64))
5543 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5544 if (isVREVMask(ShuffleMask, VT, 32))
5545 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5546 if (isVREVMask(ShuffleMask, VT, 16))
5547 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5549 if (V2->getOpcode() == ISD::UNDEF &&
5550 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5551 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5552 DAG.getConstant(Imm, MVT::i32));
5555 // Check for Neon shuffles that modify both input vectors in place.
5556 // If both results are used, i.e., if there are two shuffles with the same
5557 // source operands and with masks corresponding to both results of one of
5558 // these operations, DAG memoization will ensure that a single node is
5559 // used for both shuffles.
5560 unsigned WhichResult;
5561 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5562 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5563 V1, V2).getValue(WhichResult);
5564 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5565 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5566 V1, V2).getValue(WhichResult);
5567 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5568 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5569 V1, V2).getValue(WhichResult);
5571 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5572 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5573 V1, V1).getValue(WhichResult);
5574 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5575 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5576 V1, V1).getValue(WhichResult);
5577 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5578 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5579 V1, V1).getValue(WhichResult);
5582 // If the shuffle is not directly supported and it has 4 elements, use
5583 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5584 unsigned NumElts = VT.getVectorNumElements();
5586 unsigned PFIndexes[4];
5587 for (unsigned i = 0; i != 4; ++i) {
5588 if (ShuffleMask[i] < 0)
5591 PFIndexes[i] = ShuffleMask[i];
5594 // Compute the index in the perfect shuffle table.
5595 unsigned PFTableIndex =
5596 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5597 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5598 unsigned Cost = (PFEntry >> 30);
5601 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5604 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5605 if (EltSize >= 32) {
5606 // Do the expansion with floating-point types, since that is what the VFP
5607 // registers are defined to use, and since i64 is not legal.
5608 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5609 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5610 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5611 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5612 SmallVector<SDValue, 8> Ops;
5613 for (unsigned i = 0; i < NumElts; ++i) {
5614 if (ShuffleMask[i] < 0)
5615 Ops.push_back(DAG.getUNDEF(EltVT));
5617 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5618 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5619 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5622 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5623 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5626 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5627 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5629 if (VT == MVT::v8i8) {
5630 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5631 if (NewOp.getNode())
5638 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5639 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5640 SDValue Lane = Op.getOperand(2);
5641 if (!isa<ConstantSDNode>(Lane))
5647 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5648 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5649 SDValue Lane = Op.getOperand(1);
5650 if (!isa<ConstantSDNode>(Lane))
5653 SDValue Vec = Op.getOperand(0);
5654 if (Op.getValueType() == MVT::i32 &&
5655 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5657 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5663 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5664 // The only time a CONCAT_VECTORS operation can have legal types is when
5665 // two 64-bit vectors are concatenated to a 128-bit vector.
5666 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5667 "unexpected CONCAT_VECTORS");
5669 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5670 SDValue Op0 = Op.getOperand(0);
5671 SDValue Op1 = Op.getOperand(1);
5672 if (Op0.getOpcode() != ISD::UNDEF)
5673 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5674 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5675 DAG.getIntPtrConstant(0));
5676 if (Op1.getOpcode() != ISD::UNDEF)
5677 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5678 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5679 DAG.getIntPtrConstant(1));
5680 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5683 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5684 /// element has been zero/sign-extended, depending on the isSigned parameter,
5685 /// from an integer type half its size.
5686 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5688 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5689 EVT VT = N->getValueType(0);
5690 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5691 SDNode *BVN = N->getOperand(0).getNode();
5692 if (BVN->getValueType(0) != MVT::v4i32 ||
5693 BVN->getOpcode() != ISD::BUILD_VECTOR)
5695 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5696 unsigned HiElt = 1 - LoElt;
5697 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5698 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5699 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5700 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5701 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5704 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5705 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5708 if (Hi0->isNullValue() && Hi1->isNullValue())
5714 if (N->getOpcode() != ISD::BUILD_VECTOR)
5717 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5718 SDNode *Elt = N->getOperand(i).getNode();
5719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5720 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5721 unsigned HalfSize = EltSize / 2;
5723 if (!isIntN(HalfSize, C->getSExtValue()))
5726 if (!isUIntN(HalfSize, C->getZExtValue()))
5737 /// isSignExtended - Check if a node is a vector value that is sign-extended
5738 /// or a constant BUILD_VECTOR with sign-extended elements.
5739 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5740 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5742 if (isExtendedBUILD_VECTOR(N, DAG, true))
5747 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5748 /// or a constant BUILD_VECTOR with zero-extended elements.
5749 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5750 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5752 if (isExtendedBUILD_VECTOR(N, DAG, false))
5757 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5758 if (OrigVT.getSizeInBits() >= 64)
5761 assert(OrigVT.isSimple() && "Expecting a simple value type");
5763 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5764 switch (OrigSimpleTy) {
5765 default: llvm_unreachable("Unexpected Vector Type");
5774 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5775 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5776 /// We insert the required extension here to get the vector to fill a D register.
5777 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5780 unsigned ExtOpcode) {
5781 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5782 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5783 // 64-bits we need to insert a new extension so that it will be 64-bits.
5784 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5785 if (OrigTy.getSizeInBits() >= 64)
5788 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5789 EVT NewVT = getExtensionTo64Bits(OrigTy);
5791 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5794 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5795 /// does not do any sign/zero extension. If the original vector is less
5796 /// than 64 bits, an appropriate extension will be added after the load to
5797 /// reach a total size of 64 bits. We have to add the extension separately
5798 /// because ARM does not have a sign/zero extending load for vectors.
5799 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5800 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5802 // The load already has the right type.
5803 if (ExtendedTy == LD->getMemoryVT())
5804 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5805 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5806 LD->isNonTemporal(), LD->isInvariant(),
5807 LD->getAlignment());
5809 // We need to create a zextload/sextload. We cannot just create a load
5810 // followed by a zext/zext node because LowerMUL is also run during normal
5811 // operation legalization where we can't create illegal types.
5812 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5813 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5814 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5815 LD->isNonTemporal(), LD->getAlignment());
5818 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5819 /// extending load, or BUILD_VECTOR with extended elements, return the
5820 /// unextended value. The unextended vector should be 64 bits so that it can
5821 /// be used as an operand to a VMULL instruction. If the original vector size
5822 /// before extension is less than 64 bits we add a an extension to resize
5823 /// the vector to 64 bits.
5824 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5825 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5826 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5827 N->getOperand(0)->getValueType(0),
5831 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5832 return SkipLoadExtensionForVMULL(LD, DAG);
5834 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5835 // have been legalized as a BITCAST from v4i32.
5836 if (N->getOpcode() == ISD::BITCAST) {
5837 SDNode *BVN = N->getOperand(0).getNode();
5838 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5839 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5840 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5841 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5842 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5844 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5845 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5846 EVT VT = N->getValueType(0);
5847 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5848 unsigned NumElts = VT.getVectorNumElements();
5849 MVT TruncVT = MVT::getIntegerVT(EltSize);
5850 SmallVector<SDValue, 8> Ops;
5851 for (unsigned i = 0; i != NumElts; ++i) {
5852 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5853 const APInt &CInt = C->getAPIntValue();
5854 // Element types smaller than 32 bits are not legal, so use i32 elements.
5855 // The values are implicitly truncated so sext vs. zext doesn't matter.
5856 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5858 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5859 MVT::getVectorVT(TruncVT, NumElts), Ops);
5862 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5863 unsigned Opcode = N->getOpcode();
5864 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5865 SDNode *N0 = N->getOperand(0).getNode();
5866 SDNode *N1 = N->getOperand(1).getNode();
5867 return N0->hasOneUse() && N1->hasOneUse() &&
5868 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5873 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5874 unsigned Opcode = N->getOpcode();
5875 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5876 SDNode *N0 = N->getOperand(0).getNode();
5877 SDNode *N1 = N->getOperand(1).getNode();
5878 return N0->hasOneUse() && N1->hasOneUse() &&
5879 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5884 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5885 // Multiplications are only custom-lowered for 128-bit vectors so that
5886 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5887 EVT VT = Op.getValueType();
5888 assert(VT.is128BitVector() && VT.isInteger() &&
5889 "unexpected type for custom-lowering ISD::MUL");
5890 SDNode *N0 = Op.getOperand(0).getNode();
5891 SDNode *N1 = Op.getOperand(1).getNode();
5892 unsigned NewOpc = 0;
5894 bool isN0SExt = isSignExtended(N0, DAG);
5895 bool isN1SExt = isSignExtended(N1, DAG);
5896 if (isN0SExt && isN1SExt)
5897 NewOpc = ARMISD::VMULLs;
5899 bool isN0ZExt = isZeroExtended(N0, DAG);
5900 bool isN1ZExt = isZeroExtended(N1, DAG);
5901 if (isN0ZExt && isN1ZExt)
5902 NewOpc = ARMISD::VMULLu;
5903 else if (isN1SExt || isN1ZExt) {
5904 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5905 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5906 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5907 NewOpc = ARMISD::VMULLs;
5909 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5910 NewOpc = ARMISD::VMULLu;
5912 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5914 NewOpc = ARMISD::VMULLu;
5920 if (VT == MVT::v2i64)
5921 // Fall through to expand this. It is not legal.
5924 // Other vector multiplications are legal.
5929 // Legalize to a VMULL instruction.
5932 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5934 Op0 = SkipExtensionForVMULL(N0, DAG);
5935 assert(Op0.getValueType().is64BitVector() &&
5936 Op1.getValueType().is64BitVector() &&
5937 "unexpected types for extended operands to VMULL");
5938 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5941 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5942 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5949 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5950 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5951 EVT Op1VT = Op1.getValueType();
5952 return DAG.getNode(N0->getOpcode(), DL, VT,
5953 DAG.getNode(NewOpc, DL, VT,
5954 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5955 DAG.getNode(NewOpc, DL, VT,
5956 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5960 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5962 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5963 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5964 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5965 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5966 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5967 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5968 // Get reciprocal estimate.
5969 // float4 recip = vrecpeq_f32(yf);
5970 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5971 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5972 // Because char has a smaller range than uchar, we can actually get away
5973 // without any newton steps. This requires that we use a weird bias
5974 // of 0xb000, however (again, this has been exhaustively tested).
5975 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5976 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5977 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5978 Y = DAG.getConstant(0xb000, MVT::i32);
5979 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5980 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5981 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5982 // Convert back to short.
5983 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5984 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5989 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5991 // Convert to float.
5992 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5993 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5994 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5995 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5996 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5997 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5999 // Use reciprocal estimate and one refinement step.
6000 // float4 recip = vrecpeq_f32(yf);
6001 // recip *= vrecpsq_f32(yf, recip);
6002 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6003 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6004 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6005 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6007 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6008 // Because short has a smaller range than ushort, we can actually get away
6009 // with only a single newton step. This requires that we use a weird bias
6010 // of 89, however (again, this has been exhaustively tested).
6011 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6012 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6013 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6014 N1 = DAG.getConstant(0x89, MVT::i32);
6015 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6016 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6017 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6018 // Convert back to integer and return.
6019 // return vmovn_s32(vcvt_s32_f32(result));
6020 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6021 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6025 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6026 EVT VT = Op.getValueType();
6027 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6028 "unexpected type for custom-lowering ISD::SDIV");
6031 SDValue N0 = Op.getOperand(0);
6032 SDValue N1 = Op.getOperand(1);
6035 if (VT == MVT::v8i8) {
6036 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6037 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6039 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6040 DAG.getIntPtrConstant(4));
6041 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6042 DAG.getIntPtrConstant(4));
6043 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6044 DAG.getIntPtrConstant(0));
6045 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6046 DAG.getIntPtrConstant(0));
6048 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6049 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6051 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6052 N0 = LowerCONCAT_VECTORS(N0, DAG);
6054 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6057 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6060 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6061 EVT VT = Op.getValueType();
6062 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6063 "unexpected type for custom-lowering ISD::UDIV");
6066 SDValue N0 = Op.getOperand(0);
6067 SDValue N1 = Op.getOperand(1);
6070 if (VT == MVT::v8i8) {
6071 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6072 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6074 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6075 DAG.getIntPtrConstant(4));
6076 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6077 DAG.getIntPtrConstant(4));
6078 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6079 DAG.getIntPtrConstant(0));
6080 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6081 DAG.getIntPtrConstant(0));
6083 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6084 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6086 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6087 N0 = LowerCONCAT_VECTORS(N0, DAG);
6089 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6090 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6095 // v4i16 sdiv ... Convert to float.
6096 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6097 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6098 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6099 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6100 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6101 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6103 // Use reciprocal estimate and two refinement steps.
6104 // float4 recip = vrecpeq_f32(yf);
6105 // recip *= vrecpsq_f32(yf, recip);
6106 // recip *= vrecpsq_f32(yf, recip);
6107 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6108 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6109 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6110 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6112 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6113 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6114 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6116 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6117 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6118 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6119 // and that it will never cause us to return an answer too large).
6120 // float4 result = as_float4(as_int4(xf*recip) + 2);
6121 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6122 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6123 N1 = DAG.getConstant(2, MVT::i32);
6124 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6125 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6126 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6127 // Convert back to integer and return.
6128 // return vmovn_u32(vcvt_s32_f32(result));
6129 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6130 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6134 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6135 EVT VT = Op.getNode()->getValueType(0);
6136 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6139 bool ExtraOp = false;
6140 switch (Op.getOpcode()) {
6141 default: llvm_unreachable("Invalid code");
6142 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6143 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6144 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6145 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6149 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6151 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6152 Op.getOperand(1), Op.getOperand(2));
6155 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6156 assert(Subtarget->isTargetDarwin());
6158 // For iOS, we want to call an alternative entry point: __sincos_stret,
6159 // return values are passed via sret.
6161 SDValue Arg = Op.getOperand(0);
6162 EVT ArgVT = Arg.getValueType();
6163 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6165 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6168 // Pair of floats / doubles used to pass the result.
6169 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6171 // Create stack object for sret.
6172 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6173 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6174 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6175 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6181 Entry.Ty = RetTy->getPointerTo();
6182 Entry.isSExt = false;
6183 Entry.isZExt = false;
6184 Entry.isSRet = true;
6185 Args.push_back(Entry);
6189 Entry.isSExt = false;
6190 Entry.isZExt = false;
6191 Args.push_back(Entry);
6193 const char *LibcallName = (ArgVT == MVT::f64)
6194 ? "__sincos_stret" : "__sincosf_stret";
6195 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6197 TargetLowering::CallLoweringInfo CLI(DAG);
6198 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6199 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6201 .setDiscardResult();
6203 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6205 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6206 MachinePointerInfo(), false, false, false, 0);
6208 // Address of cos field.
6209 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6210 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6211 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6212 MachinePointerInfo(), false, false, false, 0);
6214 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6215 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6216 LoadSin.getValue(0), LoadCos.getValue(0));
6219 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6220 // Monotonic load/store is legal for all targets
6221 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6224 // Acquire/Release load/store is not legal for targets without a
6225 // dmb or equivalent available.
6229 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6230 SmallVectorImpl<SDValue> &Results,
6232 const ARMSubtarget *Subtarget) {
6234 SDValue Cycles32, OutChain;
6236 if (Subtarget->hasPerfMon()) {
6237 // Under Power Management extensions, the cycle-count is:
6238 // mrc p15, #0, <Rt>, c9, c13, #0
6239 SDValue Ops[] = { N->getOperand(0), // Chain
6240 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6241 DAG.getConstant(15, MVT::i32),
6242 DAG.getConstant(0, MVT::i32),
6243 DAG.getConstant(9, MVT::i32),
6244 DAG.getConstant(13, MVT::i32),
6245 DAG.getConstant(0, MVT::i32)
6248 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6249 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6250 OutChain = Cycles32.getValue(1);
6252 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6253 // there are older ARM CPUs that have implementation-specific ways of
6254 // obtaining this information (FIXME!).
6255 Cycles32 = DAG.getConstant(0, MVT::i32);
6256 OutChain = DAG.getEntryNode();
6260 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6261 Cycles32, DAG.getConstant(0, MVT::i32));
6262 Results.push_back(Cycles64);
6263 Results.push_back(OutChain);
6266 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6267 switch (Op.getOpcode()) {
6268 default: llvm_unreachable("Don't know how to custom lower this!");
6269 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6270 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6271 case ISD::GlobalAddress:
6272 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6273 default: llvm_unreachable("unknown object format");
6275 return LowerGlobalAddressWindows(Op, DAG);
6277 return LowerGlobalAddressELF(Op, DAG);
6279 return LowerGlobalAddressDarwin(Op, DAG);
6281 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6282 case ISD::SELECT: return LowerSELECT(Op, DAG);
6283 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6284 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6285 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6286 case ISD::VASTART: return LowerVASTART(Op, DAG);
6287 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6288 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6289 case ISD::SINT_TO_FP:
6290 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6291 case ISD::FP_TO_SINT:
6292 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6293 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6294 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6295 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6296 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6297 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6298 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6299 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6301 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6304 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6305 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6306 case ISD::SRL_PARTS:
6307 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6308 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6309 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6310 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6311 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6312 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6313 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6314 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6315 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6316 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6317 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6318 case ISD::MUL: return LowerMUL(Op, DAG);
6319 case ISD::SDIV: return LowerSDIV(Op, DAG);
6320 case ISD::UDIV: return LowerUDIV(Op, DAG);
6324 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6329 return LowerXALUO(Op, DAG);
6330 case ISD::ATOMIC_LOAD:
6331 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6332 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6334 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6335 case ISD::DYNAMIC_STACKALLOC:
6336 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6337 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6338 llvm_unreachable("Don't know how to custom lower this!");
6342 /// ReplaceNodeResults - Replace the results of node with an illegal result
6343 /// type with new values built out of custom code.
6344 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6345 SmallVectorImpl<SDValue>&Results,
6346 SelectionDAG &DAG) const {
6348 switch (N->getOpcode()) {
6350 llvm_unreachable("Don't know how to custom expand this!");
6352 Res = ExpandBITCAST(N, DAG);
6356 Res = Expand64BitShift(N, DAG, Subtarget);
6358 case ISD::READCYCLECOUNTER:
6359 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6363 Results.push_back(Res);
6366 //===----------------------------------------------------------------------===//
6367 // ARM Scheduler Hooks
6368 //===----------------------------------------------------------------------===//
6370 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6371 /// registers the function context.
6372 void ARMTargetLowering::
6373 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6374 MachineBasicBlock *DispatchBB, int FI) const {
6375 const TargetInstrInfo *TII =
6376 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6377 DebugLoc dl = MI->getDebugLoc();
6378 MachineFunction *MF = MBB->getParent();
6379 MachineRegisterInfo *MRI = &MF->getRegInfo();
6380 MachineConstantPool *MCP = MF->getConstantPool();
6381 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6382 const Function *F = MF->getFunction();
6384 bool isThumb = Subtarget->isThumb();
6385 bool isThumb2 = Subtarget->isThumb2();
6387 unsigned PCLabelId = AFI->createPICLabelUId();
6388 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6389 ARMConstantPoolValue *CPV =
6390 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6391 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6393 const TargetRegisterClass *TRC = isThumb ?
6394 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6395 (const TargetRegisterClass*)&ARM::GPRRegClass;
6397 // Grab constant pool and fixed stack memory operands.
6398 MachineMemOperand *CPMMO =
6399 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6400 MachineMemOperand::MOLoad, 4, 4);
6402 MachineMemOperand *FIMMOSt =
6403 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6404 MachineMemOperand::MOStore, 4, 4);
6406 // Load the address of the dispatch MBB into the jump buffer.
6408 // Incoming value: jbuf
6409 // ldr.n r5, LCPI1_1
6412 // str r5, [$jbuf, #+4] ; &jbuf[1]
6413 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6414 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6415 .addConstantPoolIndex(CPI)
6416 .addMemOperand(CPMMO));
6417 // Set the low bit because of thumb mode.
6418 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6420 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6421 .addReg(NewVReg1, RegState::Kill)
6423 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6424 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6425 .addReg(NewVReg2, RegState::Kill)
6427 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6428 .addReg(NewVReg3, RegState::Kill)
6430 .addImm(36) // &jbuf[1] :: pc
6431 .addMemOperand(FIMMOSt));
6432 } else if (isThumb) {
6433 // Incoming value: jbuf
6434 // ldr.n r1, LCPI1_4
6438 // add r2, $jbuf, #+4 ; &jbuf[1]
6440 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6441 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6442 .addConstantPoolIndex(CPI)
6443 .addMemOperand(CPMMO));
6444 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6445 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6446 .addReg(NewVReg1, RegState::Kill)
6448 // Set the low bit because of thumb mode.
6449 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6450 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6451 .addReg(ARM::CPSR, RegState::Define)
6453 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6454 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6455 .addReg(ARM::CPSR, RegState::Define)
6456 .addReg(NewVReg2, RegState::Kill)
6457 .addReg(NewVReg3, RegState::Kill));
6458 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6459 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6461 .addImm(36)); // &jbuf[1] :: pc
6462 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6463 .addReg(NewVReg4, RegState::Kill)
6464 .addReg(NewVReg5, RegState::Kill)
6466 .addMemOperand(FIMMOSt));
6468 // Incoming value: jbuf
6471 // str r1, [$jbuf, #+4] ; &jbuf[1]
6472 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6473 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6474 .addConstantPoolIndex(CPI)
6476 .addMemOperand(CPMMO));
6477 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6478 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6479 .addReg(NewVReg1, RegState::Kill)
6480 .addImm(PCLabelId));
6481 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6482 .addReg(NewVReg2, RegState::Kill)
6484 .addImm(36) // &jbuf[1] :: pc
6485 .addMemOperand(FIMMOSt));
6489 MachineBasicBlock *ARMTargetLowering::
6490 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6491 const TargetInstrInfo *TII =
6492 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6493 DebugLoc dl = MI->getDebugLoc();
6494 MachineFunction *MF = MBB->getParent();
6495 MachineRegisterInfo *MRI = &MF->getRegInfo();
6496 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6497 MachineFrameInfo *MFI = MF->getFrameInfo();
6498 int FI = MFI->getFunctionContextIndex();
6500 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6501 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6502 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6504 // Get a mapping of the call site numbers to all of the landing pads they're
6506 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6507 unsigned MaxCSNum = 0;
6508 MachineModuleInfo &MMI = MF->getMMI();
6509 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6511 if (!BB->isLandingPad()) continue;
6513 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6515 for (MachineBasicBlock::iterator
6516 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6517 if (!II->isEHLabel()) continue;
6519 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6520 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6522 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6523 for (SmallVectorImpl<unsigned>::iterator
6524 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6525 CSI != CSE; ++CSI) {
6526 CallSiteNumToLPad[*CSI].push_back(BB);
6527 MaxCSNum = std::max(MaxCSNum, *CSI);
6533 // Get an ordered list of the machine basic blocks for the jump table.
6534 std::vector<MachineBasicBlock*> LPadList;
6535 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6536 LPadList.reserve(CallSiteNumToLPad.size());
6537 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6538 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6539 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6540 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6541 LPadList.push_back(*II);
6542 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6546 assert(!LPadList.empty() &&
6547 "No landing pad destinations for the dispatch jump table!");
6549 // Create the jump table and associated information.
6550 MachineJumpTableInfo *JTI =
6551 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6552 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6553 unsigned UId = AFI->createJumpTableUId();
6554 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6556 // Create the MBBs for the dispatch code.
6558 // Shove the dispatch's address into the return slot in the function context.
6559 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6560 DispatchBB->setIsLandingPad();
6562 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6563 unsigned trap_opcode;
6564 if (Subtarget->isThumb())
6565 trap_opcode = ARM::tTRAP;
6567 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6569 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6570 DispatchBB->addSuccessor(TrapBB);
6572 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6573 DispatchBB->addSuccessor(DispContBB);
6576 MF->insert(MF->end(), DispatchBB);
6577 MF->insert(MF->end(), DispContBB);
6578 MF->insert(MF->end(), TrapBB);
6580 // Insert code into the entry block that creates and registers the function
6582 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6584 MachineMemOperand *FIMMOLd =
6585 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6586 MachineMemOperand::MOLoad |
6587 MachineMemOperand::MOVolatile, 4, 4);
6589 MachineInstrBuilder MIB;
6590 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6592 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6593 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6595 // Add a register mask with no preserved registers. This results in all
6596 // registers being marked as clobbered.
6597 MIB.addRegMask(RI.getNoPreservedMask());
6599 unsigned NumLPads = LPadList.size();
6600 if (Subtarget->isThumb2()) {
6601 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6602 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6605 .addMemOperand(FIMMOLd));
6607 if (NumLPads < 256) {
6608 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6610 .addImm(LPadList.size()));
6612 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6613 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6614 .addImm(NumLPads & 0xFFFF));
6616 unsigned VReg2 = VReg1;
6617 if ((NumLPads & 0xFFFF0000) != 0) {
6618 VReg2 = MRI->createVirtualRegister(TRC);
6619 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6621 .addImm(NumLPads >> 16));
6624 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6629 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6634 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6635 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6636 .addJumpTableIndex(MJTI)
6639 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6642 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6643 .addReg(NewVReg3, RegState::Kill)
6645 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6647 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6648 .addReg(NewVReg4, RegState::Kill)
6650 .addJumpTableIndex(MJTI)
6652 } else if (Subtarget->isThumb()) {
6653 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6654 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6657 .addMemOperand(FIMMOLd));
6659 if (NumLPads < 256) {
6660 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6664 MachineConstantPool *ConstantPool = MF->getConstantPool();
6665 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6666 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6668 // MachineConstantPool wants an explicit alignment.
6669 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6671 Align = getDataLayout()->getTypeAllocSize(C->getType());
6672 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6674 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6675 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6676 .addReg(VReg1, RegState::Define)
6677 .addConstantPoolIndex(Idx));
6678 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6683 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6688 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6689 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6690 .addReg(ARM::CPSR, RegState::Define)
6694 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6695 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6696 .addJumpTableIndex(MJTI)
6699 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6700 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6701 .addReg(ARM::CPSR, RegState::Define)
6702 .addReg(NewVReg2, RegState::Kill)
6705 MachineMemOperand *JTMMOLd =
6706 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6707 MachineMemOperand::MOLoad, 4, 4);
6709 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6710 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6711 .addReg(NewVReg4, RegState::Kill)
6713 .addMemOperand(JTMMOLd));
6715 unsigned NewVReg6 = NewVReg5;
6716 if (RelocM == Reloc::PIC_) {
6717 NewVReg6 = MRI->createVirtualRegister(TRC);
6718 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6719 .addReg(ARM::CPSR, RegState::Define)
6720 .addReg(NewVReg5, RegState::Kill)
6724 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6725 .addReg(NewVReg6, RegState::Kill)
6726 .addJumpTableIndex(MJTI)
6729 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6730 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6733 .addMemOperand(FIMMOLd));
6735 if (NumLPads < 256) {
6736 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6739 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6740 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6741 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6742 .addImm(NumLPads & 0xFFFF));
6744 unsigned VReg2 = VReg1;
6745 if ((NumLPads & 0xFFFF0000) != 0) {
6746 VReg2 = MRI->createVirtualRegister(TRC);
6747 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6749 .addImm(NumLPads >> 16));
6752 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6756 MachineConstantPool *ConstantPool = MF->getConstantPool();
6757 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6758 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6760 // MachineConstantPool wants an explicit alignment.
6761 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6763 Align = getDataLayout()->getTypeAllocSize(C->getType());
6764 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6766 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6767 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6768 .addReg(VReg1, RegState::Define)
6769 .addConstantPoolIndex(Idx)
6771 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6773 .addReg(VReg1, RegState::Kill));
6776 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6781 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6783 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6785 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6786 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6787 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6788 .addJumpTableIndex(MJTI)
6791 MachineMemOperand *JTMMOLd =
6792 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6793 MachineMemOperand::MOLoad, 4, 4);
6794 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6796 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6797 .addReg(NewVReg3, RegState::Kill)
6800 .addMemOperand(JTMMOLd));
6802 if (RelocM == Reloc::PIC_) {
6803 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6804 .addReg(NewVReg5, RegState::Kill)
6806 .addJumpTableIndex(MJTI)
6809 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6810 .addReg(NewVReg5, RegState::Kill)
6811 .addJumpTableIndex(MJTI)
6816 // Add the jump table entries as successors to the MBB.
6817 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6818 for (std::vector<MachineBasicBlock*>::iterator
6819 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6820 MachineBasicBlock *CurMBB = *I;
6821 if (SeenMBBs.insert(CurMBB))
6822 DispContBB->addSuccessor(CurMBB);
6825 // N.B. the order the invoke BBs are processed in doesn't matter here.
6826 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6827 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6828 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6829 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6830 MachineBasicBlock *BB = *I;
6832 // Remove the landing pad successor from the invoke block and replace it
6833 // with the new dispatch block.
6834 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6836 while (!Successors.empty()) {
6837 MachineBasicBlock *SMBB = Successors.pop_back_val();
6838 if (SMBB->isLandingPad()) {
6839 BB->removeSuccessor(SMBB);
6840 MBBLPads.push_back(SMBB);
6844 BB->addSuccessor(DispatchBB);
6846 // Find the invoke call and mark all of the callee-saved registers as
6847 // 'implicit defined' so that they're spilled. This prevents code from
6848 // moving instructions to before the EH block, where they will never be
6850 for (MachineBasicBlock::reverse_iterator
6851 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6852 if (!II->isCall()) continue;
6854 DenseMap<unsigned, bool> DefRegs;
6855 for (MachineInstr::mop_iterator
6856 OI = II->operands_begin(), OE = II->operands_end();
6858 if (!OI->isReg()) continue;
6859 DefRegs[OI->getReg()] = true;
6862 MachineInstrBuilder MIB(*MF, &*II);
6864 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6865 unsigned Reg = SavedRegs[i];
6866 if (Subtarget->isThumb2() &&
6867 !ARM::tGPRRegClass.contains(Reg) &&
6868 !ARM::hGPRRegClass.contains(Reg))
6870 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6872 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6875 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6882 // Mark all former landing pads as non-landing pads. The dispatch is the only
6884 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6885 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6886 (*I)->setIsLandingPad(false);
6888 // The instruction is gone now.
6889 MI->eraseFromParent();
6895 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6896 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6897 E = MBB->succ_end(); I != E; ++I)
6900 llvm_unreachable("Expecting a BB with two successors!");
6903 /// Return the load opcode for a given load size. If load size >= 8,
6904 /// neon opcode will be returned.
6905 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6907 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6908 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6910 return LdSize == 4 ? ARM::tLDRi
6911 : LdSize == 2 ? ARM::tLDRHi
6912 : LdSize == 1 ? ARM::tLDRBi : 0;
6914 return LdSize == 4 ? ARM::t2LDR_POST
6915 : LdSize == 2 ? ARM::t2LDRH_POST
6916 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6917 return LdSize == 4 ? ARM::LDR_POST_IMM
6918 : LdSize == 2 ? ARM::LDRH_POST
6919 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6922 /// Return the store opcode for a given store size. If store size >= 8,
6923 /// neon opcode will be returned.
6924 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6926 return StSize == 16 ? ARM::VST1q32wb_fixed
6927 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6929 return StSize == 4 ? ARM::tSTRi
6930 : StSize == 2 ? ARM::tSTRHi
6931 : StSize == 1 ? ARM::tSTRBi : 0;
6933 return StSize == 4 ? ARM::t2STR_POST
6934 : StSize == 2 ? ARM::t2STRH_POST
6935 : StSize == 1 ? ARM::t2STRB_POST : 0;
6936 return StSize == 4 ? ARM::STR_POST_IMM
6937 : StSize == 2 ? ARM::STRH_POST
6938 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6941 /// Emit a post-increment load operation with given size. The instructions
6942 /// will be added to BB at Pos.
6943 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6944 const TargetInstrInfo *TII, DebugLoc dl,
6945 unsigned LdSize, unsigned Data, unsigned AddrIn,
6946 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6947 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6948 assert(LdOpc != 0 && "Should have a load opcode");
6950 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6951 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6953 } else if (IsThumb1) {
6954 // load + update AddrIn
6955 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6956 .addReg(AddrIn).addImm(0));
6957 MachineInstrBuilder MIB =
6958 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6959 MIB = AddDefaultT1CC(MIB);
6960 MIB.addReg(AddrIn).addImm(LdSize);
6961 AddDefaultPred(MIB);
6962 } else if (IsThumb2) {
6963 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6964 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6967 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6968 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6969 .addReg(0).addImm(LdSize));
6973 /// Emit a post-increment store operation with given size. The instructions
6974 /// will be added to BB at Pos.
6975 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6976 const TargetInstrInfo *TII, DebugLoc dl,
6977 unsigned StSize, unsigned Data, unsigned AddrIn,
6978 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6979 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6980 assert(StOpc != 0 && "Should have a store opcode");
6982 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6983 .addReg(AddrIn).addImm(0).addReg(Data));
6984 } else if (IsThumb1) {
6985 // store + update AddrIn
6986 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6987 .addReg(AddrIn).addImm(0));
6988 MachineInstrBuilder MIB =
6989 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6990 MIB = AddDefaultT1CC(MIB);
6991 MIB.addReg(AddrIn).addImm(StSize);
6992 AddDefaultPred(MIB);
6993 } else if (IsThumb2) {
6994 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6995 .addReg(Data).addReg(AddrIn).addImm(StSize));
6997 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6998 .addReg(Data).addReg(AddrIn).addReg(0)
7004 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7005 MachineBasicBlock *BB) const {
7006 // This pseudo instruction has 3 operands: dst, src, size
7007 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7008 // Otherwise, we will generate unrolled scalar copies.
7009 const TargetInstrInfo *TII =
7010 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7011 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7012 MachineFunction::iterator It = BB;
7015 unsigned dest = MI->getOperand(0).getReg();
7016 unsigned src = MI->getOperand(1).getReg();
7017 unsigned SizeVal = MI->getOperand(2).getImm();
7018 unsigned Align = MI->getOperand(3).getImm();
7019 DebugLoc dl = MI->getDebugLoc();
7021 MachineFunction *MF = BB->getParent();
7022 MachineRegisterInfo &MRI = MF->getRegInfo();
7023 unsigned UnitSize = 0;
7024 const TargetRegisterClass *TRC = nullptr;
7025 const TargetRegisterClass *VecTRC = nullptr;
7027 bool IsThumb1 = Subtarget->isThumb1Only();
7028 bool IsThumb2 = Subtarget->isThumb2();
7032 } else if (Align & 2) {
7035 // Check whether we can use NEON instructions.
7036 if (!MF->getFunction()->getAttributes().
7037 hasAttribute(AttributeSet::FunctionIndex,
7038 Attribute::NoImplicitFloat) &&
7039 Subtarget->hasNEON()) {
7040 if ((Align % 16 == 0) && SizeVal >= 16)
7042 else if ((Align % 8 == 0) && SizeVal >= 8)
7045 // Can't use NEON instructions.
7050 // Select the correct opcode and register class for unit size load/store
7051 bool IsNeon = UnitSize >= 8;
7052 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7053 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7055 VecTRC = UnitSize == 16
7056 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7058 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7061 unsigned BytesLeft = SizeVal % UnitSize;
7062 unsigned LoopSize = SizeVal - BytesLeft;
7064 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7065 // Use LDR and STR to copy.
7066 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7067 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7068 unsigned srcIn = src;
7069 unsigned destIn = dest;
7070 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7071 unsigned srcOut = MRI.createVirtualRegister(TRC);
7072 unsigned destOut = MRI.createVirtualRegister(TRC);
7073 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7074 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7075 IsThumb1, IsThumb2);
7076 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7077 IsThumb1, IsThumb2);
7082 // Handle the leftover bytes with LDRB and STRB.
7083 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7084 // [destOut] = STRB_POST(scratch, destIn, 1)
7085 for (unsigned i = 0; i < BytesLeft; i++) {
7086 unsigned srcOut = MRI.createVirtualRegister(TRC);
7087 unsigned destOut = MRI.createVirtualRegister(TRC);
7088 unsigned scratch = MRI.createVirtualRegister(TRC);
7089 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7090 IsThumb1, IsThumb2);
7091 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7092 IsThumb1, IsThumb2);
7096 MI->eraseFromParent(); // The instruction is gone now.
7100 // Expand the pseudo op to a loop.
7103 // movw varEnd, # --> with thumb2
7105 // ldrcp varEnd, idx --> without thumb2
7106 // fallthrough --> loopMBB
7108 // PHI varPhi, varEnd, varLoop
7109 // PHI srcPhi, src, srcLoop
7110 // PHI destPhi, dst, destLoop
7111 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7112 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7113 // subs varLoop, varPhi, #UnitSize
7115 // fallthrough --> exitMBB
7117 // epilogue to handle left-over bytes
7118 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7119 // [destOut] = STRB_POST(scratch, destLoop, 1)
7120 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7121 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7122 MF->insert(It, loopMBB);
7123 MF->insert(It, exitMBB);
7125 // Transfer the remainder of BB and its successor edges to exitMBB.
7126 exitMBB->splice(exitMBB->begin(), BB,
7127 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7128 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7130 // Load an immediate to varEnd.
7131 unsigned varEnd = MRI.createVirtualRegister(TRC);
7133 unsigned Vtmp = varEnd;
7134 if ((LoopSize & 0xFFFF0000) != 0)
7135 Vtmp = MRI.createVirtualRegister(TRC);
7136 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7137 .addImm(LoopSize & 0xFFFF));
7139 if ((LoopSize & 0xFFFF0000) != 0)
7140 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7141 .addReg(Vtmp).addImm(LoopSize >> 16));
7143 MachineConstantPool *ConstantPool = MF->getConstantPool();
7144 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7145 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7147 // MachineConstantPool wants an explicit alignment.
7148 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7150 Align = getDataLayout()->getTypeAllocSize(C->getType());
7151 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7154 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7155 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7157 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7158 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7160 BB->addSuccessor(loopMBB);
7162 // Generate the loop body:
7163 // varPhi = PHI(varLoop, varEnd)
7164 // srcPhi = PHI(srcLoop, src)
7165 // destPhi = PHI(destLoop, dst)
7166 MachineBasicBlock *entryBB = BB;
7168 unsigned varLoop = MRI.createVirtualRegister(TRC);
7169 unsigned varPhi = MRI.createVirtualRegister(TRC);
7170 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7171 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7172 unsigned destLoop = MRI.createVirtualRegister(TRC);
7173 unsigned destPhi = MRI.createVirtualRegister(TRC);
7175 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7176 .addReg(varLoop).addMBB(loopMBB)
7177 .addReg(varEnd).addMBB(entryBB);
7178 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7179 .addReg(srcLoop).addMBB(loopMBB)
7180 .addReg(src).addMBB(entryBB);
7181 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7182 .addReg(destLoop).addMBB(loopMBB)
7183 .addReg(dest).addMBB(entryBB);
7185 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7186 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7187 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7188 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7189 IsThumb1, IsThumb2);
7190 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7191 IsThumb1, IsThumb2);
7193 // Decrement loop variable by UnitSize.
7195 MachineInstrBuilder MIB =
7196 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7197 MIB = AddDefaultT1CC(MIB);
7198 MIB.addReg(varPhi).addImm(UnitSize);
7199 AddDefaultPred(MIB);
7201 MachineInstrBuilder MIB =
7202 BuildMI(*BB, BB->end(), dl,
7203 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7204 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7205 MIB->getOperand(5).setReg(ARM::CPSR);
7206 MIB->getOperand(5).setIsDef(true);
7208 BuildMI(*BB, BB->end(), dl,
7209 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7210 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7212 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7213 BB->addSuccessor(loopMBB);
7214 BB->addSuccessor(exitMBB);
7216 // Add epilogue to handle BytesLeft.
7218 MachineInstr *StartOfExit = exitMBB->begin();
7220 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7221 // [destOut] = STRB_POST(scratch, destLoop, 1)
7222 unsigned srcIn = srcLoop;
7223 unsigned destIn = destLoop;
7224 for (unsigned i = 0; i < BytesLeft; i++) {
7225 unsigned srcOut = MRI.createVirtualRegister(TRC);
7226 unsigned destOut = MRI.createVirtualRegister(TRC);
7227 unsigned scratch = MRI.createVirtualRegister(TRC);
7228 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7229 IsThumb1, IsThumb2);
7230 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7231 IsThumb1, IsThumb2);
7236 MI->eraseFromParent(); // The instruction is gone now.
7241 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7242 MachineBasicBlock *MBB) const {
7243 const TargetMachine &TM = getTargetMachine();
7244 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7245 DebugLoc DL = MI->getDebugLoc();
7247 assert(Subtarget->isTargetWindows() &&
7248 "__chkstk is only supported on Windows");
7249 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7251 // __chkstk takes the number of words to allocate on the stack in R4, and
7252 // returns the stack adjustment in number of bytes in R4. This will not
7253 // clober any other registers (other than the obvious lr).
7255 // Although, technically, IP should be considered a register which may be
7256 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7257 // thumb-2 environment, so there is no interworking required. As a result, we
7258 // do not expect a veneer to be emitted by the linker, clobbering IP.
7260 // Each module receives its own copy of __chkstk, so no import thunk is
7261 // required, again, ensuring that IP is not clobbered.
7263 // Finally, although some linkers may theoretically provide a trampoline for
7264 // out of range calls (which is quite common due to a 32M range limitation of
7265 // branches for Thumb), we can generate the long-call version via
7266 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7269 switch (TM.getCodeModel()) {
7270 case CodeModel::Small:
7271 case CodeModel::Medium:
7272 case CodeModel::Default:
7273 case CodeModel::Kernel:
7274 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7275 .addImm((unsigned)ARMCC::AL).addReg(0)
7276 .addExternalSymbol("__chkstk")
7277 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7278 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7279 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7281 case CodeModel::Large:
7282 case CodeModel::JITDefault: {
7283 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7284 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7286 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7287 .addExternalSymbol("__chkstk");
7288 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7289 .addImm((unsigned)ARMCC::AL).addReg(0)
7290 .addReg(Reg, RegState::Kill)
7291 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7292 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7293 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7298 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7300 .addReg(ARM::SP).addReg(ARM::R4)));
7302 MI->eraseFromParent();
7307 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7308 MachineBasicBlock *BB) const {
7309 const TargetInstrInfo *TII =
7310 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7311 DebugLoc dl = MI->getDebugLoc();
7312 bool isThumb2 = Subtarget->isThumb2();
7313 switch (MI->getOpcode()) {
7316 llvm_unreachable("Unexpected instr type to insert");
7318 // The Thumb2 pre-indexed stores have the same MI operands, they just
7319 // define them differently in the .td files from the isel patterns, so
7320 // they need pseudos.
7321 case ARM::t2STR_preidx:
7322 MI->setDesc(TII->get(ARM::t2STR_PRE));
7324 case ARM::t2STRB_preidx:
7325 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7327 case ARM::t2STRH_preidx:
7328 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7331 case ARM::STRi_preidx:
7332 case ARM::STRBi_preidx: {
7333 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7334 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7335 // Decode the offset.
7336 unsigned Offset = MI->getOperand(4).getImm();
7337 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7338 Offset = ARM_AM::getAM2Offset(Offset);
7342 MachineMemOperand *MMO = *MI->memoperands_begin();
7343 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7344 .addOperand(MI->getOperand(0)) // Rn_wb
7345 .addOperand(MI->getOperand(1)) // Rt
7346 .addOperand(MI->getOperand(2)) // Rn
7347 .addImm(Offset) // offset (skip GPR==zero_reg)
7348 .addOperand(MI->getOperand(5)) // pred
7349 .addOperand(MI->getOperand(6))
7350 .addMemOperand(MMO);
7351 MI->eraseFromParent();
7354 case ARM::STRr_preidx:
7355 case ARM::STRBr_preidx:
7356 case ARM::STRH_preidx: {
7358 switch (MI->getOpcode()) {
7359 default: llvm_unreachable("unexpected opcode!");
7360 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7361 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7362 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7364 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7365 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7366 MIB.addOperand(MI->getOperand(i));
7367 MI->eraseFromParent();
7371 case ARM::tMOVCCr_pseudo: {
7372 // To "insert" a SELECT_CC instruction, we actually have to insert the
7373 // diamond control-flow pattern. The incoming instruction knows the
7374 // destination vreg to set, the condition code register to branch on, the
7375 // true/false values to select between, and a branch opcode to use.
7376 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7377 MachineFunction::iterator It = BB;
7383 // cmpTY ccX, r1, r2
7385 // fallthrough --> copy0MBB
7386 MachineBasicBlock *thisMBB = BB;
7387 MachineFunction *F = BB->getParent();
7388 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7389 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7390 F->insert(It, copy0MBB);
7391 F->insert(It, sinkMBB);
7393 // Transfer the remainder of BB and its successor edges to sinkMBB.
7394 sinkMBB->splice(sinkMBB->begin(), BB,
7395 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7396 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7398 BB->addSuccessor(copy0MBB);
7399 BB->addSuccessor(sinkMBB);
7401 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7402 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7405 // %FalseValue = ...
7406 // # fallthrough to sinkMBB
7409 // Update machine-CFG edges
7410 BB->addSuccessor(sinkMBB);
7413 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7416 BuildMI(*BB, BB->begin(), dl,
7417 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7418 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7419 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7421 MI->eraseFromParent(); // The pseudo instruction is gone now.
7426 case ARM::BCCZi64: {
7427 // If there is an unconditional branch to the other successor, remove it.
7428 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7430 // Compare both parts that make up the double comparison separately for
7432 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7434 unsigned LHS1 = MI->getOperand(1).getReg();
7435 unsigned LHS2 = MI->getOperand(2).getReg();
7437 AddDefaultPred(BuildMI(BB, dl,
7438 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7439 .addReg(LHS1).addImm(0));
7440 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7441 .addReg(LHS2).addImm(0)
7442 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7444 unsigned RHS1 = MI->getOperand(3).getReg();
7445 unsigned RHS2 = MI->getOperand(4).getReg();
7446 AddDefaultPred(BuildMI(BB, dl,
7447 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7448 .addReg(LHS1).addReg(RHS1));
7449 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7450 .addReg(LHS2).addReg(RHS2)
7451 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7454 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7455 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7456 if (MI->getOperand(0).getImm() == ARMCC::NE)
7457 std::swap(destMBB, exitMBB);
7459 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7460 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7462 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7464 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7466 MI->eraseFromParent(); // The pseudo instruction is gone now.
7470 case ARM::Int_eh_sjlj_setjmp:
7471 case ARM::Int_eh_sjlj_setjmp_nofp:
7472 case ARM::tInt_eh_sjlj_setjmp:
7473 case ARM::t2Int_eh_sjlj_setjmp:
7474 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7475 EmitSjLjDispatchBlock(MI, BB);
7480 // To insert an ABS instruction, we have to insert the
7481 // diamond control-flow pattern. The incoming instruction knows the
7482 // source vreg to test against 0, the destination vreg to set,
7483 // the condition code register to branch on, the
7484 // true/false values to select between, and a branch opcode to use.
7489 // BCC (branch to SinkBB if V0 >= 0)
7490 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7491 // SinkBB: V1 = PHI(V2, V3)
7492 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7493 MachineFunction::iterator BBI = BB;
7495 MachineFunction *Fn = BB->getParent();
7496 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7497 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7498 Fn->insert(BBI, RSBBB);
7499 Fn->insert(BBI, SinkBB);
7501 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7502 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7503 bool isThumb2 = Subtarget->isThumb2();
7504 MachineRegisterInfo &MRI = Fn->getRegInfo();
7505 // In Thumb mode S must not be specified if source register is the SP or
7506 // PC and if destination register is the SP, so restrict register class
7507 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7508 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7509 (const TargetRegisterClass*)&ARM::GPRRegClass);
7511 // Transfer the remainder of BB and its successor edges to sinkMBB.
7512 SinkBB->splice(SinkBB->begin(), BB,
7513 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7514 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7516 BB->addSuccessor(RSBBB);
7517 BB->addSuccessor(SinkBB);
7519 // fall through to SinkMBB
7520 RSBBB->addSuccessor(SinkBB);
7522 // insert a cmp at the end of BB
7523 AddDefaultPred(BuildMI(BB, dl,
7524 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7525 .addReg(ABSSrcReg).addImm(0));
7527 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7529 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7530 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7532 // insert rsbri in RSBBB
7533 // Note: BCC and rsbri will be converted into predicated rsbmi
7534 // by if-conversion pass
7535 BuildMI(*RSBBB, RSBBB->begin(), dl,
7536 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7537 .addReg(ABSSrcReg, RegState::Kill)
7538 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7540 // insert PHI in SinkBB,
7541 // reuse ABSDstReg to not change uses of ABS instruction
7542 BuildMI(*SinkBB, SinkBB->begin(), dl,
7543 TII->get(ARM::PHI), ABSDstReg)
7544 .addReg(NewRsbDstReg).addMBB(RSBBB)
7545 .addReg(ABSSrcReg).addMBB(BB);
7547 // remove ABS instruction
7548 MI->eraseFromParent();
7550 // return last added BB
7553 case ARM::COPY_STRUCT_BYVAL_I32:
7555 return EmitStructByval(MI, BB);
7556 case ARM::WIN__CHKSTK:
7557 return EmitLowered__chkstk(MI, BB);
7561 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7562 SDNode *Node) const {
7563 if (!MI->hasPostISelHook()) {
7564 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7565 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7569 const MCInstrDesc *MCID = &MI->getDesc();
7570 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7571 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7572 // operand is still set to noreg. If needed, set the optional operand's
7573 // register to CPSR, and remove the redundant implicit def.
7575 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7577 // Rename pseudo opcodes.
7578 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7580 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7581 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7582 MCID = &TII->get(NewOpc);
7584 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7585 "converted opcode should be the same except for cc_out");
7589 // Add the optional cc_out operand
7590 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7592 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7594 // Any ARM instruction that sets the 's' bit should specify an optional
7595 // "cc_out" operand in the last operand position.
7596 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7597 assert(!NewOpc && "Optional cc_out operand required");
7600 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7601 // since we already have an optional CPSR def.
7602 bool definesCPSR = false;
7603 bool deadCPSR = false;
7604 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7606 const MachineOperand &MO = MI->getOperand(i);
7607 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7611 MI->RemoveOperand(i);
7616 assert(!NewOpc && "Optional cc_out operand required");
7619 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7621 assert(!MI->getOperand(ccOutIdx).getReg() &&
7622 "expect uninitialized optional cc_out operand");
7626 // If this instruction was defined with an optional CPSR def and its dag node
7627 // had a live implicit CPSR def, then activate the optional CPSR def.
7628 MachineOperand &MO = MI->getOperand(ccOutIdx);
7629 MO.setReg(ARM::CPSR);
7633 //===----------------------------------------------------------------------===//
7634 // ARM Optimization Hooks
7635 //===----------------------------------------------------------------------===//
7637 // Helper function that checks if N is a null or all ones constant.
7638 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7639 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7642 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7645 // Return true if N is conditionally 0 or all ones.
7646 // Detects these expressions where cc is an i1 value:
7648 // (select cc 0, y) [AllOnes=0]
7649 // (select cc y, 0) [AllOnes=0]
7650 // (zext cc) [AllOnes=0]
7651 // (sext cc) [AllOnes=0/1]
7652 // (select cc -1, y) [AllOnes=1]
7653 // (select cc y, -1) [AllOnes=1]
7655 // Invert is set when N is the null/all ones constant when CC is false.
7656 // OtherOp is set to the alternative value of N.
7657 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7658 SDValue &CC, bool &Invert,
7660 SelectionDAG &DAG) {
7661 switch (N->getOpcode()) {
7662 default: return false;
7664 CC = N->getOperand(0);
7665 SDValue N1 = N->getOperand(1);
7666 SDValue N2 = N->getOperand(2);
7667 if (isZeroOrAllOnes(N1, AllOnes)) {
7672 if (isZeroOrAllOnes(N2, AllOnes)) {
7679 case ISD::ZERO_EXTEND:
7680 // (zext cc) can never be the all ones value.
7684 case ISD::SIGN_EXTEND: {
7685 EVT VT = N->getValueType(0);
7686 CC = N->getOperand(0);
7687 if (CC.getValueType() != MVT::i1)
7691 // When looking for an AllOnes constant, N is an sext, and the 'other'
7693 OtherOp = DAG.getConstant(0, VT);
7694 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7695 // When looking for a 0 constant, N can be zext or sext.
7696 OtherOp = DAG.getConstant(1, VT);
7698 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7704 // Combine a constant select operand into its use:
7706 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7707 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7708 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7709 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7710 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7712 // The transform is rejected if the select doesn't have a constant operand that
7713 // is null, or all ones when AllOnes is set.
7715 // Also recognize sext/zext from i1:
7717 // (add (zext cc), x) -> (select cc (add x, 1), x)
7718 // (add (sext cc), x) -> (select cc (add x, -1), x)
7720 // These transformations eventually create predicated instructions.
7722 // @param N The node to transform.
7723 // @param Slct The N operand that is a select.
7724 // @param OtherOp The other N operand (x above).
7725 // @param DCI Context.
7726 // @param AllOnes Require the select constant to be all ones instead of null.
7727 // @returns The new node, or SDValue() on failure.
7729 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7730 TargetLowering::DAGCombinerInfo &DCI,
7731 bool AllOnes = false) {
7732 SelectionDAG &DAG = DCI.DAG;
7733 EVT VT = N->getValueType(0);
7734 SDValue NonConstantVal;
7737 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7738 NonConstantVal, DAG))
7741 // Slct is now know to be the desired identity constant when CC is true.
7742 SDValue TrueVal = OtherOp;
7743 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7744 OtherOp, NonConstantVal);
7745 // Unless SwapSelectOps says CC should be false.
7747 std::swap(TrueVal, FalseVal);
7749 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7750 CCOp, TrueVal, FalseVal);
7753 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7755 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7756 TargetLowering::DAGCombinerInfo &DCI) {
7757 SDValue N0 = N->getOperand(0);
7758 SDValue N1 = N->getOperand(1);
7759 if (N0.getNode()->hasOneUse()) {
7760 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7761 if (Result.getNode())
7764 if (N1.getNode()->hasOneUse()) {
7765 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7766 if (Result.getNode())
7772 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7773 // (only after legalization).
7774 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7775 TargetLowering::DAGCombinerInfo &DCI,
7776 const ARMSubtarget *Subtarget) {
7778 // Only perform optimization if after legalize, and if NEON is available. We
7779 // also expected both operands to be BUILD_VECTORs.
7780 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7781 || N0.getOpcode() != ISD::BUILD_VECTOR
7782 || N1.getOpcode() != ISD::BUILD_VECTOR)
7785 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7786 EVT VT = N->getValueType(0);
7787 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7790 // Check that the vector operands are of the right form.
7791 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7792 // operands, where N is the size of the formed vector.
7793 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7794 // index such that we have a pair wise add pattern.
7796 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7797 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7799 SDValue Vec = N0->getOperand(0)->getOperand(0);
7800 SDNode *V = Vec.getNode();
7801 unsigned nextIndex = 0;
7803 // For each operands to the ADD which are BUILD_VECTORs,
7804 // check to see if each of their operands are an EXTRACT_VECTOR with
7805 // the same vector and appropriate index.
7806 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7807 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7808 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7810 SDValue ExtVec0 = N0->getOperand(i);
7811 SDValue ExtVec1 = N1->getOperand(i);
7813 // First operand is the vector, verify its the same.
7814 if (V != ExtVec0->getOperand(0).getNode() ||
7815 V != ExtVec1->getOperand(0).getNode())
7818 // Second is the constant, verify its correct.
7819 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7820 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7822 // For the constant, we want to see all the even or all the odd.
7823 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7824 || C1->getZExtValue() != nextIndex+1)
7833 // Create VPADDL node.
7834 SelectionDAG &DAG = DCI.DAG;
7835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7837 // Build operand list.
7838 SmallVector<SDValue, 8> Ops;
7839 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7840 TLI.getPointerTy()));
7842 // Input is the vector.
7845 // Get widened type and narrowed type.
7847 unsigned numElem = VT.getVectorNumElements();
7849 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7850 switch (inputLaneType.getSimpleVT().SimpleTy) {
7851 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7852 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7853 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7855 llvm_unreachable("Invalid vector element type for padd optimization.");
7858 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7859 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7860 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7863 static SDValue findMUL_LOHI(SDValue V) {
7864 if (V->getOpcode() == ISD::UMUL_LOHI ||
7865 V->getOpcode() == ISD::SMUL_LOHI)
7870 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7871 TargetLowering::DAGCombinerInfo &DCI,
7872 const ARMSubtarget *Subtarget) {
7874 if (Subtarget->isThumb1Only()) return SDValue();
7876 // Only perform the checks after legalize when the pattern is available.
7877 if (DCI.isBeforeLegalize()) return SDValue();
7879 // Look for multiply add opportunities.
7880 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7881 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7882 // a glue link from the first add to the second add.
7883 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7884 // a S/UMLAL instruction.
7887 // \ / \ [no multiline comment]
7893 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7894 SDValue AddcOp0 = AddcNode->getOperand(0);
7895 SDValue AddcOp1 = AddcNode->getOperand(1);
7897 // Check if the two operands are from the same mul_lohi node.
7898 if (AddcOp0.getNode() == AddcOp1.getNode())
7901 assert(AddcNode->getNumValues() == 2 &&
7902 AddcNode->getValueType(0) == MVT::i32 &&
7903 "Expect ADDC with two result values. First: i32");
7905 // Check that we have a glued ADDC node.
7906 if (AddcNode->getValueType(1) != MVT::Glue)
7909 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7910 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7911 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7912 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7913 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7916 // Look for the glued ADDE.
7917 SDNode* AddeNode = AddcNode->getGluedUser();
7921 // Make sure it is really an ADDE.
7922 if (AddeNode->getOpcode() != ISD::ADDE)
7925 assert(AddeNode->getNumOperands() == 3 &&
7926 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7927 "ADDE node has the wrong inputs");
7929 // Check for the triangle shape.
7930 SDValue AddeOp0 = AddeNode->getOperand(0);
7931 SDValue AddeOp1 = AddeNode->getOperand(1);
7933 // Make sure that the ADDE operands are not coming from the same node.
7934 if (AddeOp0.getNode() == AddeOp1.getNode())
7937 // Find the MUL_LOHI node walking up ADDE's operands.
7938 bool IsLeftOperandMUL = false;
7939 SDValue MULOp = findMUL_LOHI(AddeOp0);
7940 if (MULOp == SDValue())
7941 MULOp = findMUL_LOHI(AddeOp1);
7943 IsLeftOperandMUL = true;
7944 if (MULOp == SDValue())
7947 // Figure out the right opcode.
7948 unsigned Opc = MULOp->getOpcode();
7949 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7951 // Figure out the high and low input values to the MLAL node.
7952 SDValue* HiMul = &MULOp;
7953 SDValue* HiAdd = nullptr;
7954 SDValue* LoMul = nullptr;
7955 SDValue* LowAdd = nullptr;
7957 if (IsLeftOperandMUL)
7963 if (AddcOp0->getOpcode() == Opc) {
7967 if (AddcOp1->getOpcode() == Opc) {
7975 if (LoMul->getNode() != HiMul->getNode())
7978 // Create the merged node.
7979 SelectionDAG &DAG = DCI.DAG;
7981 // Build operand list.
7982 SmallVector<SDValue, 8> Ops;
7983 Ops.push_back(LoMul->getOperand(0));
7984 Ops.push_back(LoMul->getOperand(1));
7985 Ops.push_back(*LowAdd);
7986 Ops.push_back(*HiAdd);
7988 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7989 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7991 // Replace the ADDs' nodes uses by the MLA node's values.
7992 SDValue HiMLALResult(MLALNode.getNode(), 1);
7993 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7995 SDValue LoMLALResult(MLALNode.getNode(), 0);
7996 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7998 // Return original node to notify the driver to stop replacing.
7999 SDValue resNode(AddcNode, 0);
8003 /// PerformADDCCombine - Target-specific dag combine transform from
8004 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8005 static SDValue PerformADDCCombine(SDNode *N,
8006 TargetLowering::DAGCombinerInfo &DCI,
8007 const ARMSubtarget *Subtarget) {
8009 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8013 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8014 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8015 /// called with the default operands, and if that fails, with commuted
8017 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8018 TargetLowering::DAGCombinerInfo &DCI,
8019 const ARMSubtarget *Subtarget){
8021 // Attempt to create vpaddl for this add.
8022 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8023 if (Result.getNode())
8026 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8027 if (N0.getNode()->hasOneUse()) {
8028 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8029 if (Result.getNode()) return Result;
8034 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8036 static SDValue PerformADDCombine(SDNode *N,
8037 TargetLowering::DAGCombinerInfo &DCI,
8038 const ARMSubtarget *Subtarget) {
8039 SDValue N0 = N->getOperand(0);
8040 SDValue N1 = N->getOperand(1);
8042 // First try with the default operand order.
8043 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8044 if (Result.getNode())
8047 // If that didn't work, try again with the operands commuted.
8048 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8051 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8053 static SDValue PerformSUBCombine(SDNode *N,
8054 TargetLowering::DAGCombinerInfo &DCI) {
8055 SDValue N0 = N->getOperand(0);
8056 SDValue N1 = N->getOperand(1);
8058 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8059 if (N1.getNode()->hasOneUse()) {
8060 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8061 if (Result.getNode()) return Result;
8067 /// PerformVMULCombine
8068 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8069 /// special multiplier accumulator forwarding.
8075 // However, for (A + B) * (A + B),
8082 static SDValue PerformVMULCombine(SDNode *N,
8083 TargetLowering::DAGCombinerInfo &DCI,
8084 const ARMSubtarget *Subtarget) {
8085 if (!Subtarget->hasVMLxForwarding())
8088 SelectionDAG &DAG = DCI.DAG;
8089 SDValue N0 = N->getOperand(0);
8090 SDValue N1 = N->getOperand(1);
8091 unsigned Opcode = N0.getOpcode();
8092 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8093 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8094 Opcode = N1.getOpcode();
8095 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8096 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8104 EVT VT = N->getValueType(0);
8106 SDValue N00 = N0->getOperand(0);
8107 SDValue N01 = N0->getOperand(1);
8108 return DAG.getNode(Opcode, DL, VT,
8109 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8110 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8113 static SDValue PerformMULCombine(SDNode *N,
8114 TargetLowering::DAGCombinerInfo &DCI,
8115 const ARMSubtarget *Subtarget) {
8116 SelectionDAG &DAG = DCI.DAG;
8118 if (Subtarget->isThumb1Only())
8121 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8124 EVT VT = N->getValueType(0);
8125 if (VT.is64BitVector() || VT.is128BitVector())
8126 return PerformVMULCombine(N, DCI, Subtarget);
8130 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8134 int64_t MulAmt = C->getSExtValue();
8135 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8137 ShiftAmt = ShiftAmt & (32 - 1);
8138 SDValue V = N->getOperand(0);
8142 MulAmt >>= ShiftAmt;
8145 if (isPowerOf2_32(MulAmt - 1)) {
8146 // (mul x, 2^N + 1) => (add (shl x, N), x)
8147 Res = DAG.getNode(ISD::ADD, DL, VT,
8149 DAG.getNode(ISD::SHL, DL, VT,
8151 DAG.getConstant(Log2_32(MulAmt - 1),
8153 } else if (isPowerOf2_32(MulAmt + 1)) {
8154 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8155 Res = DAG.getNode(ISD::SUB, DL, VT,
8156 DAG.getNode(ISD::SHL, DL, VT,
8158 DAG.getConstant(Log2_32(MulAmt + 1),
8164 uint64_t MulAmtAbs = -MulAmt;
8165 if (isPowerOf2_32(MulAmtAbs + 1)) {
8166 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8167 Res = DAG.getNode(ISD::SUB, DL, VT,
8169 DAG.getNode(ISD::SHL, DL, VT,
8171 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8173 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8174 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8175 Res = DAG.getNode(ISD::ADD, DL, VT,
8177 DAG.getNode(ISD::SHL, DL, VT,
8179 DAG.getConstant(Log2_32(MulAmtAbs-1),
8181 Res = DAG.getNode(ISD::SUB, DL, VT,
8182 DAG.getConstant(0, MVT::i32),Res);
8189 Res = DAG.getNode(ISD::SHL, DL, VT,
8190 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8192 // Do not add new nodes to DAG combiner worklist.
8193 DCI.CombineTo(N, Res, false);
8197 static SDValue PerformANDCombine(SDNode *N,
8198 TargetLowering::DAGCombinerInfo &DCI,
8199 const ARMSubtarget *Subtarget) {
8201 // Attempt to use immediate-form VBIC
8202 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8204 EVT VT = N->getValueType(0);
8205 SelectionDAG &DAG = DCI.DAG;
8207 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8210 APInt SplatBits, SplatUndef;
8211 unsigned SplatBitSize;
8214 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8215 if (SplatBitSize <= 64) {
8217 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8218 SplatUndef.getZExtValue(), SplatBitSize,
8219 DAG, VbicVT, VT.is128BitVector(),
8221 if (Val.getNode()) {
8223 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8224 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8225 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8230 if (!Subtarget->isThumb1Only()) {
8231 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8232 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8233 if (Result.getNode())
8240 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8241 static SDValue PerformORCombine(SDNode *N,
8242 TargetLowering::DAGCombinerInfo &DCI,
8243 const ARMSubtarget *Subtarget) {
8244 // Attempt to use immediate-form VORR
8245 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8247 EVT VT = N->getValueType(0);
8248 SelectionDAG &DAG = DCI.DAG;
8250 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8253 APInt SplatBits, SplatUndef;
8254 unsigned SplatBitSize;
8256 if (BVN && Subtarget->hasNEON() &&
8257 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8258 if (SplatBitSize <= 64) {
8260 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8261 SplatUndef.getZExtValue(), SplatBitSize,
8262 DAG, VorrVT, VT.is128BitVector(),
8264 if (Val.getNode()) {
8266 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8267 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8268 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8273 if (!Subtarget->isThumb1Only()) {
8274 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8275 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8276 if (Result.getNode())
8280 // The code below optimizes (or (and X, Y), Z).
8281 // The AND operand needs to have a single user to make these optimizations
8283 SDValue N0 = N->getOperand(0);
8284 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8286 SDValue N1 = N->getOperand(1);
8288 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8289 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8290 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8292 unsigned SplatBitSize;
8295 APInt SplatBits0, SplatBits1;
8296 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8297 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8298 // Ensure that the second operand of both ands are constants
8299 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8300 HasAnyUndefs) && !HasAnyUndefs) {
8301 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8302 HasAnyUndefs) && !HasAnyUndefs) {
8303 // Ensure that the bit width of the constants are the same and that
8304 // the splat arguments are logical inverses as per the pattern we
8305 // are trying to simplify.
8306 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8307 SplatBits0 == ~SplatBits1) {
8308 // Canonicalize the vector type to make instruction selection
8310 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8311 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8315 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8321 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8324 // BFI is only available on V6T2+
8325 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8329 // 1) or (and A, mask), val => ARMbfi A, val, mask
8330 // iff (val & mask) == val
8332 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8333 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8334 // && mask == ~mask2
8335 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8336 // && ~mask == mask2
8337 // (i.e., copy a bitfield value into another bitfield of the same width)
8342 SDValue N00 = N0.getOperand(0);
8344 // The value and the mask need to be constants so we can verify this is
8345 // actually a bitfield set. If the mask is 0xffff, we can do better
8346 // via a movt instruction, so don't use BFI in that case.
8347 SDValue MaskOp = N0.getOperand(1);
8348 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8351 unsigned Mask = MaskC->getZExtValue();
8355 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8356 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8358 unsigned Val = N1C->getZExtValue();
8359 if ((Val & ~Mask) != Val)
8362 if (ARM::isBitFieldInvertedMask(Mask)) {
8363 Val >>= countTrailingZeros(~Mask);
8365 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8366 DAG.getConstant(Val, MVT::i32),
8367 DAG.getConstant(Mask, MVT::i32));
8369 // Do not add new nodes to DAG combiner worklist.
8370 DCI.CombineTo(N, Res, false);
8373 } else if (N1.getOpcode() == ISD::AND) {
8374 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8375 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8378 unsigned Mask2 = N11C->getZExtValue();
8380 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8382 if (ARM::isBitFieldInvertedMask(Mask) &&
8384 // The pack halfword instruction works better for masks that fit it,
8385 // so use that when it's available.
8386 if (Subtarget->hasT2ExtractPack() &&
8387 (Mask == 0xffff || Mask == 0xffff0000))
8390 unsigned amt = countTrailingZeros(Mask2);
8391 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8392 DAG.getConstant(amt, MVT::i32));
8393 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8394 DAG.getConstant(Mask, MVT::i32));
8395 // Do not add new nodes to DAG combiner worklist.
8396 DCI.CombineTo(N, Res, false);
8398 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8400 // The pack halfword instruction works better for masks that fit it,
8401 // so use that when it's available.
8402 if (Subtarget->hasT2ExtractPack() &&
8403 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8406 unsigned lsb = countTrailingZeros(Mask);
8407 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8408 DAG.getConstant(lsb, MVT::i32));
8409 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8410 DAG.getConstant(Mask2, MVT::i32));
8411 // Do not add new nodes to DAG combiner worklist.
8412 DCI.CombineTo(N, Res, false);
8417 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8418 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8419 ARM::isBitFieldInvertedMask(~Mask)) {
8420 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8421 // where lsb(mask) == #shamt and masked bits of B are known zero.
8422 SDValue ShAmt = N00.getOperand(1);
8423 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8424 unsigned LSB = countTrailingZeros(Mask);
8428 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8429 DAG.getConstant(~Mask, MVT::i32));
8431 // Do not add new nodes to DAG combiner worklist.
8432 DCI.CombineTo(N, Res, false);
8438 static SDValue PerformXORCombine(SDNode *N,
8439 TargetLowering::DAGCombinerInfo &DCI,
8440 const ARMSubtarget *Subtarget) {
8441 EVT VT = N->getValueType(0);
8442 SelectionDAG &DAG = DCI.DAG;
8444 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8447 if (!Subtarget->isThumb1Only()) {
8448 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8449 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8450 if (Result.getNode())
8457 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8458 /// the bits being cleared by the AND are not demanded by the BFI.
8459 static SDValue PerformBFICombine(SDNode *N,
8460 TargetLowering::DAGCombinerInfo &DCI) {
8461 SDValue N1 = N->getOperand(1);
8462 if (N1.getOpcode() == ISD::AND) {
8463 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8466 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8467 unsigned LSB = countTrailingZeros(~InvMask);
8468 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8469 unsigned Mask = (1 << Width)-1;
8470 unsigned Mask2 = N11C->getZExtValue();
8471 if ((Mask & (~Mask2)) == 0)
8472 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8473 N->getOperand(0), N1.getOperand(0),
8479 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8480 /// ARMISD::VMOVRRD.
8481 static SDValue PerformVMOVRRDCombine(SDNode *N,
8482 TargetLowering::DAGCombinerInfo &DCI) {
8483 // vmovrrd(vmovdrr x, y) -> x,y
8484 SDValue InDouble = N->getOperand(0);
8485 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8486 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8488 // vmovrrd(load f64) -> (load i32), (load i32)
8489 SDNode *InNode = InDouble.getNode();
8490 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8491 InNode->getValueType(0) == MVT::f64 &&
8492 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8493 !cast<LoadSDNode>(InNode)->isVolatile()) {
8494 // TODO: Should this be done for non-FrameIndex operands?
8495 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8497 SelectionDAG &DAG = DCI.DAG;
8499 SDValue BasePtr = LD->getBasePtr();
8500 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8501 LD->getPointerInfo(), LD->isVolatile(),
8502 LD->isNonTemporal(), LD->isInvariant(),
8503 LD->getAlignment());
8505 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8506 DAG.getConstant(4, MVT::i32));
8507 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8508 LD->getPointerInfo(), LD->isVolatile(),
8509 LD->isNonTemporal(), LD->isInvariant(),
8510 std::min(4U, LD->getAlignment() / 2));
8512 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8513 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8514 std::swap (NewLD1, NewLD2);
8515 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8522 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8523 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8524 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8525 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8526 SDValue Op0 = N->getOperand(0);
8527 SDValue Op1 = N->getOperand(1);
8528 if (Op0.getOpcode() == ISD::BITCAST)
8529 Op0 = Op0.getOperand(0);
8530 if (Op1.getOpcode() == ISD::BITCAST)
8531 Op1 = Op1.getOperand(0);
8532 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8533 Op0.getNode() == Op1.getNode() &&
8534 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8535 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8536 N->getValueType(0), Op0.getOperand(0));
8540 /// PerformSTORECombine - Target-specific dag combine xforms for
8542 static SDValue PerformSTORECombine(SDNode *N,
8543 TargetLowering::DAGCombinerInfo &DCI) {
8544 StoreSDNode *St = cast<StoreSDNode>(N);
8545 if (St->isVolatile())
8548 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8549 // pack all of the elements in one place. Next, store to memory in fewer
8551 SDValue StVal = St->getValue();
8552 EVT VT = StVal.getValueType();
8553 if (St->isTruncatingStore() && VT.isVector()) {
8554 SelectionDAG &DAG = DCI.DAG;
8555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8556 EVT StVT = St->getMemoryVT();
8557 unsigned NumElems = VT.getVectorNumElements();
8558 assert(StVT != VT && "Cannot truncate to the same type");
8559 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8560 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8562 // From, To sizes and ElemCount must be pow of two
8563 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8565 // We are going to use the original vector elt for storing.
8566 // Accumulated smaller vector elements must be a multiple of the store size.
8567 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8569 unsigned SizeRatio = FromEltSz / ToEltSz;
8570 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8572 // Create a type on which we perform the shuffle.
8573 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8574 NumElems*SizeRatio);
8575 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8578 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8579 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8580 for (unsigned i = 0; i < NumElems; ++i)
8581 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8583 // Can't shuffle using an illegal type.
8584 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8586 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8587 DAG.getUNDEF(WideVec.getValueType()),
8589 // At this point all of the data is stored at the bottom of the
8590 // register. We now need to save it to mem.
8592 // Find the largest store unit
8593 MVT StoreType = MVT::i8;
8594 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8595 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8596 MVT Tp = (MVT::SimpleValueType)tp;
8597 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8600 // Didn't find a legal store type.
8601 if (!TLI.isTypeLegal(StoreType))
8604 // Bitcast the original vector into a vector of store-size units
8605 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8606 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8607 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8608 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8609 SmallVector<SDValue, 8> Chains;
8610 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8611 TLI.getPointerTy());
8612 SDValue BasePtr = St->getBasePtr();
8614 // Perform one or more big stores into memory.
8615 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8616 for (unsigned I = 0; I < E; I++) {
8617 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8618 StoreType, ShuffWide,
8619 DAG.getIntPtrConstant(I));
8620 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8621 St->getPointerInfo(), St->isVolatile(),
8622 St->isNonTemporal(), St->getAlignment());
8623 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8625 Chains.push_back(Ch);
8627 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8630 if (!ISD::isNormalStore(St))
8633 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8634 // ARM stores of arguments in the same cache line.
8635 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8636 StVal.getNode()->hasOneUse()) {
8637 SelectionDAG &DAG = DCI.DAG;
8638 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8640 SDValue BasePtr = St->getBasePtr();
8641 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8642 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8643 BasePtr, St->getPointerInfo(), St->isVolatile(),
8644 St->isNonTemporal(), St->getAlignment());
8646 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8647 DAG.getConstant(4, MVT::i32));
8648 return DAG.getStore(NewST1.getValue(0), DL,
8649 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8650 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8651 St->isNonTemporal(),
8652 std::min(4U, St->getAlignment() / 2));
8655 if (StVal.getValueType() != MVT::i64 ||
8656 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8659 // Bitcast an i64 store extracted from a vector to f64.
8660 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8661 SelectionDAG &DAG = DCI.DAG;
8663 SDValue IntVec = StVal.getOperand(0);
8664 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8665 IntVec.getValueType().getVectorNumElements());
8666 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8667 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8668 Vec, StVal.getOperand(1));
8670 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8671 // Make the DAGCombiner fold the bitcasts.
8672 DCI.AddToWorklist(Vec.getNode());
8673 DCI.AddToWorklist(ExtElt.getNode());
8674 DCI.AddToWorklist(V.getNode());
8675 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8676 St->getPointerInfo(), St->isVolatile(),
8677 St->isNonTemporal(), St->getAlignment(),
8681 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8682 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8683 /// i64 vector to have f64 elements, since the value can then be loaded
8684 /// directly into a VFP register.
8685 static bool hasNormalLoadOperand(SDNode *N) {
8686 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8687 for (unsigned i = 0; i < NumElts; ++i) {
8688 SDNode *Elt = N->getOperand(i).getNode();
8689 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8695 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8696 /// ISD::BUILD_VECTOR.
8697 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8698 TargetLowering::DAGCombinerInfo &DCI){
8699 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8700 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8701 // into a pair of GPRs, which is fine when the value is used as a scalar,
8702 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8703 SelectionDAG &DAG = DCI.DAG;
8704 if (N->getNumOperands() == 2) {
8705 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8710 // Load i64 elements as f64 values so that type legalization does not split
8711 // them up into i32 values.
8712 EVT VT = N->getValueType(0);
8713 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8716 SmallVector<SDValue, 8> Ops;
8717 unsigned NumElts = VT.getVectorNumElements();
8718 for (unsigned i = 0; i < NumElts; ++i) {
8719 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8721 // Make the DAGCombiner fold the bitcast.
8722 DCI.AddToWorklist(V.getNode());
8724 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8725 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8726 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8729 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8731 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8732 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8733 // At that time, we may have inserted bitcasts from integer to float.
8734 // If these bitcasts have survived DAGCombine, change the lowering of this
8735 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8736 // force to use floating point types.
8738 // Make sure we can change the type of the vector.
8739 // This is possible iff:
8740 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8741 // 1.1. Vector is used only once.
8742 // 1.2. Use is a bit convert to an integer type.
8743 // 2. The size of its operands are 32-bits (64-bits are not legal).
8744 EVT VT = N->getValueType(0);
8745 EVT EltVT = VT.getVectorElementType();
8747 // Check 1.1. and 2.
8748 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8751 // By construction, the input type must be float.
8752 assert(EltVT == MVT::f32 && "Unexpected type!");
8755 SDNode *Use = *N->use_begin();
8756 if (Use->getOpcode() != ISD::BITCAST ||
8757 Use->getValueType(0).isFloatingPoint())
8760 // Check profitability.
8761 // Model is, if more than half of the relevant operands are bitcast from
8762 // i32, turn the build_vector into a sequence of insert_vector_elt.
8763 // Relevant operands are everything that is not statically
8764 // (i.e., at compile time) bitcasted.
8765 unsigned NumOfBitCastedElts = 0;
8766 unsigned NumElts = VT.getVectorNumElements();
8767 unsigned NumOfRelevantElts = NumElts;
8768 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8769 SDValue Elt = N->getOperand(Idx);
8770 if (Elt->getOpcode() == ISD::BITCAST) {
8771 // Assume only bit cast to i32 will go away.
8772 if (Elt->getOperand(0).getValueType() == MVT::i32)
8773 ++NumOfBitCastedElts;
8774 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8775 // Constants are statically casted, thus do not count them as
8776 // relevant operands.
8777 --NumOfRelevantElts;
8780 // Check if more than half of the elements require a non-free bitcast.
8781 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8784 SelectionDAG &DAG = DCI.DAG;
8785 // Create the new vector type.
8786 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8787 // Check if the type is legal.
8788 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8789 if (!TLI.isTypeLegal(VecVT))
8793 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8794 // => BITCAST INSERT_VECTOR_ELT
8795 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8797 SDValue Vec = DAG.getUNDEF(VecVT);
8799 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8800 SDValue V = N->getOperand(Idx);
8801 if (V.getOpcode() == ISD::UNDEF)
8803 if (V.getOpcode() == ISD::BITCAST &&
8804 V->getOperand(0).getValueType() == MVT::i32)
8805 // Fold obvious case.
8806 V = V.getOperand(0);
8808 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8809 // Make the DAGCombiner fold the bitcasts.
8810 DCI.AddToWorklist(V.getNode());
8812 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8813 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8815 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8816 // Make the DAGCombiner fold the bitcasts.
8817 DCI.AddToWorklist(Vec.getNode());
8821 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8822 /// ISD::INSERT_VECTOR_ELT.
8823 static SDValue PerformInsertEltCombine(SDNode *N,
8824 TargetLowering::DAGCombinerInfo &DCI) {
8825 // Bitcast an i64 load inserted into a vector to f64.
8826 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8827 EVT VT = N->getValueType(0);
8828 SDNode *Elt = N->getOperand(1).getNode();
8829 if (VT.getVectorElementType() != MVT::i64 ||
8830 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8833 SelectionDAG &DAG = DCI.DAG;
8835 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8836 VT.getVectorNumElements());
8837 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8838 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8839 // Make the DAGCombiner fold the bitcasts.
8840 DCI.AddToWorklist(Vec.getNode());
8841 DCI.AddToWorklist(V.getNode());
8842 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8843 Vec, V, N->getOperand(2));
8844 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8847 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8848 /// ISD::VECTOR_SHUFFLE.
8849 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8850 // The LLVM shufflevector instruction does not require the shuffle mask
8851 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8852 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8853 // operands do not match the mask length, they are extended by concatenating
8854 // them with undef vectors. That is probably the right thing for other
8855 // targets, but for NEON it is better to concatenate two double-register
8856 // size vector operands into a single quad-register size vector. Do that
8857 // transformation here:
8858 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8859 // shuffle(concat(v1, v2), undef)
8860 SDValue Op0 = N->getOperand(0);
8861 SDValue Op1 = N->getOperand(1);
8862 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8863 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8864 Op0.getNumOperands() != 2 ||
8865 Op1.getNumOperands() != 2)
8867 SDValue Concat0Op1 = Op0.getOperand(1);
8868 SDValue Concat1Op1 = Op1.getOperand(1);
8869 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8870 Concat1Op1.getOpcode() != ISD::UNDEF)
8872 // Skip the transformation if any of the types are illegal.
8873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8874 EVT VT = N->getValueType(0);
8875 if (!TLI.isTypeLegal(VT) ||
8876 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8877 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8880 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8881 Op0.getOperand(0), Op1.getOperand(0));
8882 // Translate the shuffle mask.
8883 SmallVector<int, 16> NewMask;
8884 unsigned NumElts = VT.getVectorNumElements();
8885 unsigned HalfElts = NumElts/2;
8886 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8887 for (unsigned n = 0; n < NumElts; ++n) {
8888 int MaskElt = SVN->getMaskElt(n);
8890 if (MaskElt < (int)HalfElts)
8892 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8893 NewElt = HalfElts + MaskElt - NumElts;
8894 NewMask.push_back(NewElt);
8896 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8897 DAG.getUNDEF(VT), NewMask.data());
8900 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8901 /// NEON load/store intrinsics to merge base address updates.
8902 static SDValue CombineBaseUpdate(SDNode *N,
8903 TargetLowering::DAGCombinerInfo &DCI) {
8904 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8907 SelectionDAG &DAG = DCI.DAG;
8908 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8909 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8910 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8911 SDValue Addr = N->getOperand(AddrOpIdx);
8913 // Search for a use of the address operand that is an increment.
8914 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8915 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8917 if (User->getOpcode() != ISD::ADD ||
8918 UI.getUse().getResNo() != Addr.getResNo())
8921 // Check that the add is independent of the load/store. Otherwise, folding
8922 // it would create a cycle.
8923 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8926 // Find the new opcode for the updating load/store.
8928 bool isLaneOp = false;
8929 unsigned NewOpc = 0;
8930 unsigned NumVecs = 0;
8932 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8934 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8935 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8937 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8939 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8941 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8943 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8944 NumVecs = 2; isLaneOp = true; break;
8945 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8946 NumVecs = 3; isLaneOp = true; break;
8947 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8948 NumVecs = 4; isLaneOp = true; break;
8949 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8950 NumVecs = 1; isLoad = false; break;
8951 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8952 NumVecs = 2; isLoad = false; break;
8953 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8954 NumVecs = 3; isLoad = false; break;
8955 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8956 NumVecs = 4; isLoad = false; break;
8957 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8958 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8959 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8960 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8961 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8962 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8966 switch (N->getOpcode()) {
8967 default: llvm_unreachable("unexpected opcode for Neon base update");
8968 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8969 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8970 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8974 // Find the size of memory referenced by the load/store.
8977 VecTy = N->getValueType(0);
8979 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8980 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8982 NumBytes /= VecTy.getVectorNumElements();
8984 // If the increment is a constant, it must match the memory ref size.
8985 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8986 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8987 uint64_t IncVal = CInc->getZExtValue();
8988 if (IncVal != NumBytes)
8990 } else if (NumBytes >= 3 * 16) {
8991 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8992 // separate instructions that make it harder to use a non-constant update.
8996 // Create the new updating load/store node.
8998 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9000 for (n = 0; n < NumResultVecs; ++n)
9002 Tys[n++] = MVT::i32;
9003 Tys[n] = MVT::Other;
9004 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
9005 SmallVector<SDValue, 8> Ops;
9006 Ops.push_back(N->getOperand(0)); // incoming chain
9007 Ops.push_back(N->getOperand(AddrOpIdx));
9009 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9010 Ops.push_back(N->getOperand(i));
9012 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9013 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9014 Ops, MemInt->getMemoryVT(),
9015 MemInt->getMemOperand());
9018 std::vector<SDValue> NewResults;
9019 for (unsigned i = 0; i < NumResultVecs; ++i) {
9020 NewResults.push_back(SDValue(UpdN.getNode(), i));
9022 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9023 DCI.CombineTo(N, NewResults);
9024 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9031 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9032 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9033 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9035 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9036 SelectionDAG &DAG = DCI.DAG;
9037 EVT VT = N->getValueType(0);
9038 // vldN-dup instructions only support 64-bit vectors for N > 1.
9039 if (!VT.is64BitVector())
9042 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9043 SDNode *VLD = N->getOperand(0).getNode();
9044 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9046 unsigned NumVecs = 0;
9047 unsigned NewOpc = 0;
9048 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9049 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9051 NewOpc = ARMISD::VLD2DUP;
9052 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9054 NewOpc = ARMISD::VLD3DUP;
9055 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9057 NewOpc = ARMISD::VLD4DUP;
9062 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9063 // numbers match the load.
9064 unsigned VLDLaneNo =
9065 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9066 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9068 // Ignore uses of the chain result.
9069 if (UI.getUse().getResNo() == NumVecs)
9072 if (User->getOpcode() != ARMISD::VDUPLANE ||
9073 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9077 // Create the vldN-dup node.
9080 for (n = 0; n < NumVecs; ++n)
9082 Tys[n] = MVT::Other;
9083 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9084 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9085 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9086 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9087 Ops, VLDMemInt->getMemoryVT(),
9088 VLDMemInt->getMemOperand());
9091 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9093 unsigned ResNo = UI.getUse().getResNo();
9094 // Ignore uses of the chain result.
9095 if (ResNo == NumVecs)
9098 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9101 // Now the vldN-lane intrinsic is dead except for its chain result.
9102 // Update uses of the chain.
9103 std::vector<SDValue> VLDDupResults;
9104 for (unsigned n = 0; n < NumVecs; ++n)
9105 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9106 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9107 DCI.CombineTo(VLD, VLDDupResults);
9112 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9113 /// ARMISD::VDUPLANE.
9114 static SDValue PerformVDUPLANECombine(SDNode *N,
9115 TargetLowering::DAGCombinerInfo &DCI) {
9116 SDValue Op = N->getOperand(0);
9118 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9119 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9120 if (CombineVLDDUP(N, DCI))
9121 return SDValue(N, 0);
9123 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9124 // redundant. Ignore bit_converts for now; element sizes are checked below.
9125 while (Op.getOpcode() == ISD::BITCAST)
9126 Op = Op.getOperand(0);
9127 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9130 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9131 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9132 // The canonical VMOV for a zero vector uses a 32-bit element size.
9133 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9135 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9137 EVT VT = N->getValueType(0);
9138 if (EltSize > VT.getVectorElementType().getSizeInBits())
9141 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9144 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9145 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9146 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9150 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9152 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9157 APFloat APF = C->getValueAPF();
9158 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9159 != APFloat::opOK || !isExact)
9162 c0 = (I == 0) ? cN : c0;
9163 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9170 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9171 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9172 /// when the VMUL has a constant operand that is a power of 2.
9174 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9175 /// vmul.f32 d16, d17, d16
9176 /// vcvt.s32.f32 d16, d16
9178 /// vcvt.s32.f32 d16, d16, #3
9179 static SDValue PerformVCVTCombine(SDNode *N,
9180 TargetLowering::DAGCombinerInfo &DCI,
9181 const ARMSubtarget *Subtarget) {
9182 SelectionDAG &DAG = DCI.DAG;
9183 SDValue Op = N->getOperand(0);
9185 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9186 Op.getOpcode() != ISD::FMUL)
9190 SDValue N0 = Op->getOperand(0);
9191 SDValue ConstVec = Op->getOperand(1);
9192 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9194 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9195 !isConstVecPow2(ConstVec, isSigned, C))
9198 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9199 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9200 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9201 // These instructions only exist converting from f32 to i32. We can handle
9202 // smaller integers by generating an extra truncate, but larger ones would
9207 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9208 Intrinsic::arm_neon_vcvtfp2fxu;
9209 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9210 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9211 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9212 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9213 DAG.getConstant(Log2_64(C), MVT::i32));
9215 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9216 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9221 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9222 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9223 /// when the VDIV has a constant operand that is a power of 2.
9225 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9226 /// vcvt.f32.s32 d16, d16
9227 /// vdiv.f32 d16, d17, d16
9229 /// vcvt.f32.s32 d16, d16, #3
9230 static SDValue PerformVDIVCombine(SDNode *N,
9231 TargetLowering::DAGCombinerInfo &DCI,
9232 const ARMSubtarget *Subtarget) {
9233 SelectionDAG &DAG = DCI.DAG;
9234 SDValue Op = N->getOperand(0);
9235 unsigned OpOpcode = Op.getNode()->getOpcode();
9237 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9238 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9242 SDValue ConstVec = N->getOperand(1);
9243 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9245 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9246 !isConstVecPow2(ConstVec, isSigned, C))
9249 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9250 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9251 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9252 // These instructions only exist converting from i32 to f32. We can handle
9253 // smaller integers by generating an extra extend, but larger ones would
9258 SDValue ConvInput = Op.getOperand(0);
9259 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9260 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9261 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9262 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9265 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9266 Intrinsic::arm_neon_vcvtfxu2fp;
9267 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9269 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9270 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9273 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9274 /// operand of a vector shift operation, where all the elements of the
9275 /// build_vector must have the same constant integer value.
9276 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9277 // Ignore bit_converts.
9278 while (Op.getOpcode() == ISD::BITCAST)
9279 Op = Op.getOperand(0);
9280 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9281 APInt SplatBits, SplatUndef;
9282 unsigned SplatBitSize;
9284 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9285 HasAnyUndefs, ElementBits) ||
9286 SplatBitSize > ElementBits)
9288 Cnt = SplatBits.getSExtValue();
9292 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9293 /// operand of a vector shift left operation. That value must be in the range:
9294 /// 0 <= Value < ElementBits for a left shift; or
9295 /// 0 <= Value <= ElementBits for a long left shift.
9296 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9297 assert(VT.isVector() && "vector shift count is not a vector type");
9298 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9299 if (! getVShiftImm(Op, ElementBits, Cnt))
9301 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9304 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9305 /// operand of a vector shift right operation. For a shift opcode, the value
9306 /// is positive, but for an intrinsic the value count must be negative. The
9307 /// absolute value must be in the range:
9308 /// 1 <= |Value| <= ElementBits for a right shift; or
9309 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9310 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9312 assert(VT.isVector() && "vector shift count is not a vector type");
9313 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9314 if (! getVShiftImm(Op, ElementBits, Cnt))
9318 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9321 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9322 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9323 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9326 // Don't do anything for most intrinsics.
9329 // Vector shifts: check for immediate versions and lower them.
9330 // Note: This is done during DAG combining instead of DAG legalizing because
9331 // the build_vectors for 64-bit vector element shift counts are generally
9332 // not legal, and it is hard to see their values after they get legalized to
9333 // loads from a constant pool.
9334 case Intrinsic::arm_neon_vshifts:
9335 case Intrinsic::arm_neon_vshiftu:
9336 case Intrinsic::arm_neon_vrshifts:
9337 case Intrinsic::arm_neon_vrshiftu:
9338 case Intrinsic::arm_neon_vrshiftn:
9339 case Intrinsic::arm_neon_vqshifts:
9340 case Intrinsic::arm_neon_vqshiftu:
9341 case Intrinsic::arm_neon_vqshiftsu:
9342 case Intrinsic::arm_neon_vqshiftns:
9343 case Intrinsic::arm_neon_vqshiftnu:
9344 case Intrinsic::arm_neon_vqshiftnsu:
9345 case Intrinsic::arm_neon_vqrshiftns:
9346 case Intrinsic::arm_neon_vqrshiftnu:
9347 case Intrinsic::arm_neon_vqrshiftnsu: {
9348 EVT VT = N->getOperand(1).getValueType();
9350 unsigned VShiftOpc = 0;
9353 case Intrinsic::arm_neon_vshifts:
9354 case Intrinsic::arm_neon_vshiftu:
9355 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9356 VShiftOpc = ARMISD::VSHL;
9359 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9360 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9361 ARMISD::VSHRs : ARMISD::VSHRu);
9366 case Intrinsic::arm_neon_vrshifts:
9367 case Intrinsic::arm_neon_vrshiftu:
9368 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9372 case Intrinsic::arm_neon_vqshifts:
9373 case Intrinsic::arm_neon_vqshiftu:
9374 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9378 case Intrinsic::arm_neon_vqshiftsu:
9379 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9381 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9383 case Intrinsic::arm_neon_vrshiftn:
9384 case Intrinsic::arm_neon_vqshiftns:
9385 case Intrinsic::arm_neon_vqshiftnu:
9386 case Intrinsic::arm_neon_vqshiftnsu:
9387 case Intrinsic::arm_neon_vqrshiftns:
9388 case Intrinsic::arm_neon_vqrshiftnu:
9389 case Intrinsic::arm_neon_vqrshiftnsu:
9390 // Narrowing shifts require an immediate right shift.
9391 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9393 llvm_unreachable("invalid shift count for narrowing vector shift "
9397 llvm_unreachable("unhandled vector shift");
9401 case Intrinsic::arm_neon_vshifts:
9402 case Intrinsic::arm_neon_vshiftu:
9403 // Opcode already set above.
9405 case Intrinsic::arm_neon_vrshifts:
9406 VShiftOpc = ARMISD::VRSHRs; break;
9407 case Intrinsic::arm_neon_vrshiftu:
9408 VShiftOpc = ARMISD::VRSHRu; break;
9409 case Intrinsic::arm_neon_vrshiftn:
9410 VShiftOpc = ARMISD::VRSHRN; break;
9411 case Intrinsic::arm_neon_vqshifts:
9412 VShiftOpc = ARMISD::VQSHLs; break;
9413 case Intrinsic::arm_neon_vqshiftu:
9414 VShiftOpc = ARMISD::VQSHLu; break;
9415 case Intrinsic::arm_neon_vqshiftsu:
9416 VShiftOpc = ARMISD::VQSHLsu; break;
9417 case Intrinsic::arm_neon_vqshiftns:
9418 VShiftOpc = ARMISD::VQSHRNs; break;
9419 case Intrinsic::arm_neon_vqshiftnu:
9420 VShiftOpc = ARMISD::VQSHRNu; break;
9421 case Intrinsic::arm_neon_vqshiftnsu:
9422 VShiftOpc = ARMISD::VQSHRNsu; break;
9423 case Intrinsic::arm_neon_vqrshiftns:
9424 VShiftOpc = ARMISD::VQRSHRNs; break;
9425 case Intrinsic::arm_neon_vqrshiftnu:
9426 VShiftOpc = ARMISD::VQRSHRNu; break;
9427 case Intrinsic::arm_neon_vqrshiftnsu:
9428 VShiftOpc = ARMISD::VQRSHRNsu; break;
9431 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9432 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9435 case Intrinsic::arm_neon_vshiftins: {
9436 EVT VT = N->getOperand(1).getValueType();
9438 unsigned VShiftOpc = 0;
9440 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9441 VShiftOpc = ARMISD::VSLI;
9442 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9443 VShiftOpc = ARMISD::VSRI;
9445 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9448 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9449 N->getOperand(1), N->getOperand(2),
9450 DAG.getConstant(Cnt, MVT::i32));
9453 case Intrinsic::arm_neon_vqrshifts:
9454 case Intrinsic::arm_neon_vqrshiftu:
9455 // No immediate versions of these to check for.
9462 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9463 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9464 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9465 /// vector element shift counts are generally not legal, and it is hard to see
9466 /// their values after they get legalized to loads from a constant pool.
9467 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9468 const ARMSubtarget *ST) {
9469 EVT VT = N->getValueType(0);
9470 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9471 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9472 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9473 SDValue N1 = N->getOperand(1);
9474 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9475 SDValue N0 = N->getOperand(0);
9476 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9477 DAG.MaskedValueIsZero(N0.getOperand(0),
9478 APInt::getHighBitsSet(32, 16)))
9479 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9483 // Nothing to be done for scalar shifts.
9484 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9485 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9488 assert(ST->hasNEON() && "unexpected vector shift");
9491 switch (N->getOpcode()) {
9492 default: llvm_unreachable("unexpected shift opcode");
9495 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9496 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9497 DAG.getConstant(Cnt, MVT::i32));
9502 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9503 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9504 ARMISD::VSHRs : ARMISD::VSHRu);
9505 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9506 DAG.getConstant(Cnt, MVT::i32));
9512 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9513 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9514 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9515 const ARMSubtarget *ST) {
9516 SDValue N0 = N->getOperand(0);
9518 // Check for sign- and zero-extensions of vector extract operations of 8-
9519 // and 16-bit vector elements. NEON supports these directly. They are
9520 // handled during DAG combining because type legalization will promote them
9521 // to 32-bit types and it is messy to recognize the operations after that.
9522 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9523 SDValue Vec = N0.getOperand(0);
9524 SDValue Lane = N0.getOperand(1);
9525 EVT VT = N->getValueType(0);
9526 EVT EltVT = N0.getValueType();
9527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9529 if (VT == MVT::i32 &&
9530 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9531 TLI.isTypeLegal(Vec.getValueType()) &&
9532 isa<ConstantSDNode>(Lane)) {
9535 switch (N->getOpcode()) {
9536 default: llvm_unreachable("unexpected opcode");
9537 case ISD::SIGN_EXTEND:
9538 Opc = ARMISD::VGETLANEs;
9540 case ISD::ZERO_EXTEND:
9541 case ISD::ANY_EXTEND:
9542 Opc = ARMISD::VGETLANEu;
9545 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9552 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9553 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9554 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9555 const ARMSubtarget *ST) {
9556 // If the target supports NEON, try to use vmax/vmin instructions for f32
9557 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9558 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9559 // a NaN; only do the transformation when it matches that behavior.
9561 // For now only do this when using NEON for FP operations; if using VFP, it
9562 // is not obvious that the benefit outweighs the cost of switching to the
9564 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9565 N->getValueType(0) != MVT::f32)
9568 SDValue CondLHS = N->getOperand(0);
9569 SDValue CondRHS = N->getOperand(1);
9570 SDValue LHS = N->getOperand(2);
9571 SDValue RHS = N->getOperand(3);
9572 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9574 unsigned Opcode = 0;
9576 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9577 IsReversed = false; // x CC y ? x : y
9578 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9579 IsReversed = true ; // x CC y ? y : x
9593 // If LHS is NaN, an ordered comparison will be false and the result will
9594 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9595 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9596 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9597 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9599 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9600 // will return -0, so vmin can only be used for unsafe math or if one of
9601 // the operands is known to be nonzero.
9602 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9603 !DAG.getTarget().Options.UnsafeFPMath &&
9604 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9606 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9615 // If LHS is NaN, an ordered comparison will be false and the result will
9616 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9617 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9618 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9619 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9621 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9622 // will return +0, so vmax can only be used for unsafe math or if one of
9623 // the operands is known to be nonzero.
9624 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9625 !DAG.getTarget().Options.UnsafeFPMath &&
9626 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9628 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9634 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9637 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9639 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9640 SDValue Cmp = N->getOperand(4);
9641 if (Cmp.getOpcode() != ARMISD::CMPZ)
9642 // Only looking at EQ and NE cases.
9645 EVT VT = N->getValueType(0);
9647 SDValue LHS = Cmp.getOperand(0);
9648 SDValue RHS = Cmp.getOperand(1);
9649 SDValue FalseVal = N->getOperand(0);
9650 SDValue TrueVal = N->getOperand(1);
9651 SDValue ARMcc = N->getOperand(2);
9652 ARMCC::CondCodes CC =
9653 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9671 /// FIXME: Turn this into a target neutral optimization?
9673 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9674 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9675 N->getOperand(3), Cmp);
9676 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9678 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9679 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9680 N->getOperand(3), NewCmp);
9683 if (Res.getNode()) {
9684 APInt KnownZero, KnownOne;
9685 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9686 // Capture demanded bits information that would be otherwise lost.
9687 if (KnownZero == 0xfffffffe)
9688 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9689 DAG.getValueType(MVT::i1));
9690 else if (KnownZero == 0xffffff00)
9691 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9692 DAG.getValueType(MVT::i8));
9693 else if (KnownZero == 0xffff0000)
9694 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9695 DAG.getValueType(MVT::i16));
9701 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9702 DAGCombinerInfo &DCI) const {
9703 switch (N->getOpcode()) {
9705 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9706 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9707 case ISD::SUB: return PerformSUBCombine(N, DCI);
9708 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9709 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9710 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9711 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9712 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9713 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9714 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9715 case ISD::STORE: return PerformSTORECombine(N, DCI);
9716 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9717 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9718 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9719 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9720 case ISD::FP_TO_SINT:
9721 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9722 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9723 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9726 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9727 case ISD::SIGN_EXTEND:
9728 case ISD::ZERO_EXTEND:
9729 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9730 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9731 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9732 case ARMISD::VLD2DUP:
9733 case ARMISD::VLD3DUP:
9734 case ARMISD::VLD4DUP:
9735 return CombineBaseUpdate(N, DCI);
9736 case ARMISD::BUILD_VECTOR:
9737 return PerformARMBUILD_VECTORCombine(N, DCI);
9738 case ISD::INTRINSIC_VOID:
9739 case ISD::INTRINSIC_W_CHAIN:
9740 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9741 case Intrinsic::arm_neon_vld1:
9742 case Intrinsic::arm_neon_vld2:
9743 case Intrinsic::arm_neon_vld3:
9744 case Intrinsic::arm_neon_vld4:
9745 case Intrinsic::arm_neon_vld2lane:
9746 case Intrinsic::arm_neon_vld3lane:
9747 case Intrinsic::arm_neon_vld4lane:
9748 case Intrinsic::arm_neon_vst1:
9749 case Intrinsic::arm_neon_vst2:
9750 case Intrinsic::arm_neon_vst3:
9751 case Intrinsic::arm_neon_vst4:
9752 case Intrinsic::arm_neon_vst2lane:
9753 case Intrinsic::arm_neon_vst3lane:
9754 case Intrinsic::arm_neon_vst4lane:
9755 return CombineBaseUpdate(N, DCI);
9763 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9765 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9768 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9772 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9773 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9775 switch (VT.getSimpleVT().SimpleTy) {
9781 // Unaligned access can use (for example) LRDB, LRDH, LDR
9782 if (AllowsUnaligned) {
9784 *Fast = Subtarget->hasV7Ops();
9791 // For any little-endian targets with neon, we can support unaligned ld/st
9792 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9793 // A big-endian target may also explicitly support unaligned accesses
9794 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9804 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9805 unsigned AlignCheck) {
9806 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9807 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9810 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9811 unsigned DstAlign, unsigned SrcAlign,
9812 bool IsMemset, bool ZeroMemset,
9814 MachineFunction &MF) const {
9815 const Function *F = MF.getFunction();
9817 // See if we can use NEON instructions for this...
9818 if ((!IsMemset || ZeroMemset) &&
9819 Subtarget->hasNEON() &&
9820 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9821 Attribute::NoImplicitFloat)) {
9824 (memOpAlign(SrcAlign, DstAlign, 16) ||
9825 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9827 } else if (Size >= 8 &&
9828 (memOpAlign(SrcAlign, DstAlign, 8) ||
9829 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9835 // Lowering to i32/i16 if the size permits.
9841 // Let the target-independent logic figure it out.
9845 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9846 if (Val.getOpcode() != ISD::LOAD)
9849 EVT VT1 = Val.getValueType();
9850 if (!VT1.isSimple() || !VT1.isInteger() ||
9851 !VT2.isSimple() || !VT2.isInteger())
9854 switch (VT1.getSimpleVT().SimpleTy) {
9859 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9866 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9867 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9870 if (!isTypeLegal(EVT::getEVT(Ty1)))
9873 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9875 // Assuming the caller doesn't have a zeroext or signext return parameter,
9876 // truncation all the way down to i1 is valid.
9881 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9886 switch (VT.getSimpleVT().SimpleTy) {
9887 default: return false;
9902 if ((V & (Scale - 1)) != 0)
9905 return V == (V & ((1LL << 5) - 1));
9908 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9909 const ARMSubtarget *Subtarget) {
9916 switch (VT.getSimpleVT().SimpleTy) {
9917 default: return false;
9922 // + imm12 or - imm8
9924 return V == (V & ((1LL << 8) - 1));
9925 return V == (V & ((1LL << 12) - 1));
9928 // Same as ARM mode. FIXME: NEON?
9929 if (!Subtarget->hasVFP2())
9934 return V == (V & ((1LL << 8) - 1));
9938 /// isLegalAddressImmediate - Return true if the integer value can be used
9939 /// as the offset of the target addressing mode for load / store of the
9941 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9942 const ARMSubtarget *Subtarget) {
9949 if (Subtarget->isThumb1Only())
9950 return isLegalT1AddressImmediate(V, VT);
9951 else if (Subtarget->isThumb2())
9952 return isLegalT2AddressImmediate(V, VT, Subtarget);
9957 switch (VT.getSimpleVT().SimpleTy) {
9958 default: return false;
9963 return V == (V & ((1LL << 12) - 1));
9966 return V == (V & ((1LL << 8) - 1));
9969 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9974 return V == (V & ((1LL << 8) - 1));
9978 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9980 int Scale = AM.Scale;
9984 switch (VT.getSimpleVT().SimpleTy) {
9985 default: return false;
9994 return Scale == 2 || Scale == 4 || Scale == 8;
9997 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10001 // Note, we allow "void" uses (basically, uses that aren't loads or
10002 // stores), because arm allows folding a scale into many arithmetic
10003 // operations. This should be made more precise and revisited later.
10005 // Allow r << imm, but the imm has to be a multiple of two.
10006 if (Scale & 1) return false;
10007 return isPowerOf2_32(Scale);
10011 /// isLegalAddressingMode - Return true if the addressing mode represented
10012 /// by AM is legal for this target, for a load/store of the specified type.
10013 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10015 EVT VT = getValueType(Ty, true);
10016 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10019 // Can never fold addr of global into load/store.
10023 switch (AM.Scale) {
10024 case 0: // no scale reg, must be "r+i" or "r", or "i".
10027 if (Subtarget->isThumb1Only())
10031 // ARM doesn't support any R+R*scale+imm addr modes.
10035 if (!VT.isSimple())
10038 if (Subtarget->isThumb2())
10039 return isLegalT2ScaledAddressingMode(AM, VT);
10041 int Scale = AM.Scale;
10042 switch (VT.getSimpleVT().SimpleTy) {
10043 default: return false;
10047 if (Scale < 0) Scale = -Scale;
10051 return isPowerOf2_32(Scale & ~1);
10055 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10060 // Note, we allow "void" uses (basically, uses that aren't loads or
10061 // stores), because arm allows folding a scale into many arithmetic
10062 // operations. This should be made more precise and revisited later.
10064 // Allow r << imm, but the imm has to be a multiple of two.
10065 if (Scale & 1) return false;
10066 return isPowerOf2_32(Scale);
10072 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10073 /// icmp immediate, that is the target has icmp instructions which can compare
10074 /// a register against the immediate without having to materialize the
10075 /// immediate into a register.
10076 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10077 // Thumb2 and ARM modes can use cmn for negative immediates.
10078 if (!Subtarget->isThumb())
10079 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10080 if (Subtarget->isThumb2())
10081 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10082 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10083 return Imm >= 0 && Imm <= 255;
10086 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10087 /// *or sub* immediate, that is the target has add or sub instructions which can
10088 /// add a register with the immediate without having to materialize the
10089 /// immediate into a register.
10090 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10091 // Same encoding for add/sub, just flip the sign.
10092 int64_t AbsImm = llvm::abs64(Imm);
10093 if (!Subtarget->isThumb())
10094 return ARM_AM::getSOImmVal(AbsImm) != -1;
10095 if (Subtarget->isThumb2())
10096 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10097 // Thumb1 only has 8-bit unsigned immediate.
10098 return AbsImm >= 0 && AbsImm <= 255;
10101 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10102 bool isSEXTLoad, SDValue &Base,
10103 SDValue &Offset, bool &isInc,
10104 SelectionDAG &DAG) {
10105 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10108 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10109 // AddressingMode 3
10110 Base = Ptr->getOperand(0);
10111 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10112 int RHSC = (int)RHS->getZExtValue();
10113 if (RHSC < 0 && RHSC > -256) {
10114 assert(Ptr->getOpcode() == ISD::ADD);
10116 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10120 isInc = (Ptr->getOpcode() == ISD::ADD);
10121 Offset = Ptr->getOperand(1);
10123 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10124 // AddressingMode 2
10125 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10126 int RHSC = (int)RHS->getZExtValue();
10127 if (RHSC < 0 && RHSC > -0x1000) {
10128 assert(Ptr->getOpcode() == ISD::ADD);
10130 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10131 Base = Ptr->getOperand(0);
10136 if (Ptr->getOpcode() == ISD::ADD) {
10138 ARM_AM::ShiftOpc ShOpcVal=
10139 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10140 if (ShOpcVal != ARM_AM::no_shift) {
10141 Base = Ptr->getOperand(1);
10142 Offset = Ptr->getOperand(0);
10144 Base = Ptr->getOperand(0);
10145 Offset = Ptr->getOperand(1);
10150 isInc = (Ptr->getOpcode() == ISD::ADD);
10151 Base = Ptr->getOperand(0);
10152 Offset = Ptr->getOperand(1);
10156 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10160 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10161 bool isSEXTLoad, SDValue &Base,
10162 SDValue &Offset, bool &isInc,
10163 SelectionDAG &DAG) {
10164 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10167 Base = Ptr->getOperand(0);
10168 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10169 int RHSC = (int)RHS->getZExtValue();
10170 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10171 assert(Ptr->getOpcode() == ISD::ADD);
10173 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10175 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10176 isInc = Ptr->getOpcode() == ISD::ADD;
10177 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10185 /// getPreIndexedAddressParts - returns true by value, base pointer and
10186 /// offset pointer and addressing mode by reference if the node's address
10187 /// can be legally represented as pre-indexed load / store address.
10189 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10191 ISD::MemIndexedMode &AM,
10192 SelectionDAG &DAG) const {
10193 if (Subtarget->isThumb1Only())
10198 bool isSEXTLoad = false;
10199 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10200 Ptr = LD->getBasePtr();
10201 VT = LD->getMemoryVT();
10202 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10203 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10204 Ptr = ST->getBasePtr();
10205 VT = ST->getMemoryVT();
10210 bool isLegal = false;
10211 if (Subtarget->isThumb2())
10212 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10213 Offset, isInc, DAG);
10215 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10216 Offset, isInc, DAG);
10220 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10224 /// getPostIndexedAddressParts - returns true by value, base pointer and
10225 /// offset pointer and addressing mode by reference if this node can be
10226 /// combined with a load / store to form a post-indexed load / store.
10227 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10230 ISD::MemIndexedMode &AM,
10231 SelectionDAG &DAG) const {
10232 if (Subtarget->isThumb1Only())
10237 bool isSEXTLoad = false;
10238 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10239 VT = LD->getMemoryVT();
10240 Ptr = LD->getBasePtr();
10241 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10242 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10243 VT = ST->getMemoryVT();
10244 Ptr = ST->getBasePtr();
10249 bool isLegal = false;
10250 if (Subtarget->isThumb2())
10251 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10254 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10260 // Swap base ptr and offset to catch more post-index load / store when
10261 // it's legal. In Thumb2 mode, offset must be an immediate.
10262 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10263 !Subtarget->isThumb2())
10264 std::swap(Base, Offset);
10266 // Post-indexed load / store update the base pointer.
10271 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10275 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10278 const SelectionDAG &DAG,
10279 unsigned Depth) const {
10280 unsigned BitWidth = KnownOne.getBitWidth();
10281 KnownZero = KnownOne = APInt(BitWidth, 0);
10282 switch (Op.getOpcode()) {
10288 // These nodes' second result is a boolean
10289 if (Op.getResNo() == 0)
10291 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10293 case ARMISD::CMOV: {
10294 // Bits are known zero/one if known on the LHS and RHS.
10295 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10296 if (KnownZero == 0 && KnownOne == 0) return;
10298 APInt KnownZeroRHS, KnownOneRHS;
10299 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10300 KnownZero &= KnownZeroRHS;
10301 KnownOne &= KnownOneRHS;
10304 case ISD::INTRINSIC_W_CHAIN: {
10305 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10306 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10309 case Intrinsic::arm_ldaex:
10310 case Intrinsic::arm_ldrex: {
10311 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10312 unsigned MemBits = VT.getScalarType().getSizeInBits();
10313 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10321 //===----------------------------------------------------------------------===//
10322 // ARM Inline Assembly Support
10323 //===----------------------------------------------------------------------===//
10325 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10326 // Looking for "rev" which is V6+.
10327 if (!Subtarget->hasV6Ops())
10330 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10331 std::string AsmStr = IA->getAsmString();
10332 SmallVector<StringRef, 4> AsmPieces;
10333 SplitString(AsmStr, AsmPieces, ";\n");
10335 switch (AsmPieces.size()) {
10336 default: return false;
10338 AsmStr = AsmPieces[0];
10340 SplitString(AsmStr, AsmPieces, " \t,");
10343 if (AsmPieces.size() == 3 &&
10344 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10345 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10346 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10347 if (Ty && Ty->getBitWidth() == 32)
10348 return IntrinsicLowering::LowerToByteSwap(CI);
10356 /// getConstraintType - Given a constraint letter, return the type of
10357 /// constraint it is for this target.
10358 ARMTargetLowering::ConstraintType
10359 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10360 if (Constraint.size() == 1) {
10361 switch (Constraint[0]) {
10363 case 'l': return C_RegisterClass;
10364 case 'w': return C_RegisterClass;
10365 case 'h': return C_RegisterClass;
10366 case 'x': return C_RegisterClass;
10367 case 't': return C_RegisterClass;
10368 case 'j': return C_Other; // Constant for movw.
10369 // An address with a single base register. Due to the way we
10370 // currently handle addresses it is the same as an 'r' memory constraint.
10371 case 'Q': return C_Memory;
10373 } else if (Constraint.size() == 2) {
10374 switch (Constraint[0]) {
10376 // All 'U+' constraints are addresses.
10377 case 'U': return C_Memory;
10380 return TargetLowering::getConstraintType(Constraint);
10383 /// Examine constraint type and operand type and determine a weight value.
10384 /// This object must already have been set up with the operand type
10385 /// and the current alternative constraint selected.
10386 TargetLowering::ConstraintWeight
10387 ARMTargetLowering::getSingleConstraintMatchWeight(
10388 AsmOperandInfo &info, const char *constraint) const {
10389 ConstraintWeight weight = CW_Invalid;
10390 Value *CallOperandVal = info.CallOperandVal;
10391 // If we don't have a value, we can't do a match,
10392 // but allow it at the lowest weight.
10393 if (!CallOperandVal)
10395 Type *type = CallOperandVal->getType();
10396 // Look at the constraint type.
10397 switch (*constraint) {
10399 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10402 if (type->isIntegerTy()) {
10403 if (Subtarget->isThumb())
10404 weight = CW_SpecificReg;
10406 weight = CW_Register;
10410 if (type->isFloatingPointTy())
10411 weight = CW_Register;
10417 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10419 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10421 if (Constraint.size() == 1) {
10422 // GCC ARM Constraint Letters
10423 switch (Constraint[0]) {
10424 case 'l': // Low regs or general regs.
10425 if (Subtarget->isThumb())
10426 return RCPair(0U, &ARM::tGPRRegClass);
10427 return RCPair(0U, &ARM::GPRRegClass);
10428 case 'h': // High regs or no regs.
10429 if (Subtarget->isThumb())
10430 return RCPair(0U, &ARM::hGPRRegClass);
10433 return RCPair(0U, &ARM::GPRRegClass);
10435 if (VT == MVT::Other)
10437 if (VT == MVT::f32)
10438 return RCPair(0U, &ARM::SPRRegClass);
10439 if (VT.getSizeInBits() == 64)
10440 return RCPair(0U, &ARM::DPRRegClass);
10441 if (VT.getSizeInBits() == 128)
10442 return RCPair(0U, &ARM::QPRRegClass);
10445 if (VT == MVT::Other)
10447 if (VT == MVT::f32)
10448 return RCPair(0U, &ARM::SPR_8RegClass);
10449 if (VT.getSizeInBits() == 64)
10450 return RCPair(0U, &ARM::DPR_8RegClass);
10451 if (VT.getSizeInBits() == 128)
10452 return RCPair(0U, &ARM::QPR_8RegClass);
10455 if (VT == MVT::f32)
10456 return RCPair(0U, &ARM::SPRRegClass);
10460 if (StringRef("{cc}").equals_lower(Constraint))
10461 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10463 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10466 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10467 /// vector. If it is invalid, don't add anything to Ops.
10468 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10469 std::string &Constraint,
10470 std::vector<SDValue>&Ops,
10471 SelectionDAG &DAG) const {
10474 // Currently only support length 1 constraints.
10475 if (Constraint.length() != 1) return;
10477 char ConstraintLetter = Constraint[0];
10478 switch (ConstraintLetter) {
10481 case 'I': case 'J': case 'K': case 'L':
10482 case 'M': case 'N': case 'O':
10483 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10487 int64_t CVal64 = C->getSExtValue();
10488 int CVal = (int) CVal64;
10489 // None of these constraints allow values larger than 32 bits. Check
10490 // that the value fits in an int.
10491 if (CVal != CVal64)
10494 switch (ConstraintLetter) {
10496 // Constant suitable for movw, must be between 0 and
10498 if (Subtarget->hasV6T2Ops())
10499 if (CVal >= 0 && CVal <= 65535)
10503 if (Subtarget->isThumb1Only()) {
10504 // This must be a constant between 0 and 255, for ADD
10506 if (CVal >= 0 && CVal <= 255)
10508 } else if (Subtarget->isThumb2()) {
10509 // A constant that can be used as an immediate value in a
10510 // data-processing instruction.
10511 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10514 // A constant that can be used as an immediate value in a
10515 // data-processing instruction.
10516 if (ARM_AM::getSOImmVal(CVal) != -1)
10522 if (Subtarget->isThumb()) { // FIXME thumb2
10523 // This must be a constant between -255 and -1, for negated ADD
10524 // immediates. This can be used in GCC with an "n" modifier that
10525 // prints the negated value, for use with SUB instructions. It is
10526 // not useful otherwise but is implemented for compatibility.
10527 if (CVal >= -255 && CVal <= -1)
10530 // This must be a constant between -4095 and 4095. It is not clear
10531 // what this constraint is intended for. Implemented for
10532 // compatibility with GCC.
10533 if (CVal >= -4095 && CVal <= 4095)
10539 if (Subtarget->isThumb1Only()) {
10540 // A 32-bit value where only one byte has a nonzero value. Exclude
10541 // zero to match GCC. This constraint is used by GCC internally for
10542 // constants that can be loaded with a move/shift combination.
10543 // It is not useful otherwise but is implemented for compatibility.
10544 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10546 } else if (Subtarget->isThumb2()) {
10547 // A constant whose bitwise inverse can be used as an immediate
10548 // value in a data-processing instruction. This can be used in GCC
10549 // with a "B" modifier that prints the inverted value, for use with
10550 // BIC and MVN instructions. It is not useful otherwise but is
10551 // implemented for compatibility.
10552 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10555 // A constant whose bitwise inverse can be used as an immediate
10556 // value in a data-processing instruction. This can be used in GCC
10557 // with a "B" modifier that prints the inverted value, for use with
10558 // BIC and MVN instructions. It is not useful otherwise but is
10559 // implemented for compatibility.
10560 if (ARM_AM::getSOImmVal(~CVal) != -1)
10566 if (Subtarget->isThumb1Only()) {
10567 // This must be a constant between -7 and 7,
10568 // for 3-operand ADD/SUB immediate instructions.
10569 if (CVal >= -7 && CVal < 7)
10571 } else if (Subtarget->isThumb2()) {
10572 // A constant whose negation can be used as an immediate value in a
10573 // data-processing instruction. This can be used in GCC with an "n"
10574 // modifier that prints the negated value, for use with SUB
10575 // instructions. It is not useful otherwise but is implemented for
10577 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10580 // A constant whose negation can be used as an immediate value in a
10581 // data-processing instruction. This can be used in GCC with an "n"
10582 // modifier that prints the negated value, for use with SUB
10583 // instructions. It is not useful otherwise but is implemented for
10585 if (ARM_AM::getSOImmVal(-CVal) != -1)
10591 if (Subtarget->isThumb()) { // FIXME thumb2
10592 // This must be a multiple of 4 between 0 and 1020, for
10593 // ADD sp + immediate.
10594 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10597 // A power of two or a constant between 0 and 32. This is used in
10598 // GCC for the shift amount on shifted register operands, but it is
10599 // useful in general for any shift amounts.
10600 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10606 if (Subtarget->isThumb()) { // FIXME thumb2
10607 // This must be a constant between 0 and 31, for shift amounts.
10608 if (CVal >= 0 && CVal <= 31)
10614 if (Subtarget->isThumb()) { // FIXME thumb2
10615 // This must be a multiple of 4 between -508 and 508, for
10616 // ADD/SUB sp = sp + immediate.
10617 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10622 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10626 if (Result.getNode()) {
10627 Ops.push_back(Result);
10630 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10633 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10634 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10635 unsigned Opcode = Op->getOpcode();
10636 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10637 "Invalid opcode for Div/Rem lowering");
10638 bool isSigned = (Opcode == ISD::SDIVREM);
10639 EVT VT = Op->getValueType(0);
10640 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10643 switch (VT.getSimpleVT().SimpleTy) {
10644 default: llvm_unreachable("Unexpected request for libcall!");
10645 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10646 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10647 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10648 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10651 SDValue InChain = DAG.getEntryNode();
10653 TargetLowering::ArgListTy Args;
10654 TargetLowering::ArgListEntry Entry;
10655 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10656 EVT ArgVT = Op->getOperand(i).getValueType();
10657 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10658 Entry.Node = Op->getOperand(i);
10660 Entry.isSExt = isSigned;
10661 Entry.isZExt = !isSigned;
10662 Args.push_back(Entry);
10665 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10668 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10671 TargetLowering::CallLoweringInfo CLI(DAG);
10672 CLI.setDebugLoc(dl).setChain(InChain)
10673 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10674 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10676 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10677 return CallInfo.first;
10681 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10682 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10686 SDValue Chain = Op.getOperand(0);
10687 SDValue Size = Op.getOperand(1);
10689 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10690 DAG.getConstant(2, MVT::i32));
10693 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10694 Flag = Chain.getValue(1);
10696 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10697 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10699 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10700 Chain = NewSP.getValue(1);
10702 SDValue Ops[2] = { NewSP, Chain };
10703 return DAG.getMergeValues(Ops, DL);
10707 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10708 // The ARM target isn't yet aware of offsets.
10712 bool ARM::isBitFieldInvertedMask(unsigned v) {
10713 if (v == 0xffffffff)
10716 // there can be 1's on either or both "outsides", all the "inside"
10717 // bits must be 0's
10718 unsigned TO = CountTrailingOnes_32(v);
10719 unsigned LO = CountLeadingOnes_32(v);
10720 v = (v >> TO) << TO;
10721 v = (v << LO) >> LO;
10725 /// isFPImmLegal - Returns true if the target can instruction select the
10726 /// specified FP immediate natively. If false, the legalizer will
10727 /// materialize the FP immediate as a load from a constant pool.
10728 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10729 if (!Subtarget->hasVFP3())
10731 if (VT == MVT::f32)
10732 return ARM_AM::getFP32Imm(Imm) != -1;
10733 if (VT == MVT::f64)
10734 return ARM_AM::getFP64Imm(Imm) != -1;
10738 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10739 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10740 /// specified in the intrinsic calls.
10741 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10743 unsigned Intrinsic) const {
10744 switch (Intrinsic) {
10745 case Intrinsic::arm_neon_vld1:
10746 case Intrinsic::arm_neon_vld2:
10747 case Intrinsic::arm_neon_vld3:
10748 case Intrinsic::arm_neon_vld4:
10749 case Intrinsic::arm_neon_vld2lane:
10750 case Intrinsic::arm_neon_vld3lane:
10751 case Intrinsic::arm_neon_vld4lane: {
10752 Info.opc = ISD::INTRINSIC_W_CHAIN;
10753 // Conservatively set memVT to the entire set of vectors loaded.
10754 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10755 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10756 Info.ptrVal = I.getArgOperand(0);
10758 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10759 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10760 Info.vol = false; // volatile loads with NEON intrinsics not supported
10761 Info.readMem = true;
10762 Info.writeMem = false;
10765 case Intrinsic::arm_neon_vst1:
10766 case Intrinsic::arm_neon_vst2:
10767 case Intrinsic::arm_neon_vst3:
10768 case Intrinsic::arm_neon_vst4:
10769 case Intrinsic::arm_neon_vst2lane:
10770 case Intrinsic::arm_neon_vst3lane:
10771 case Intrinsic::arm_neon_vst4lane: {
10772 Info.opc = ISD::INTRINSIC_VOID;
10773 // Conservatively set memVT to the entire set of vectors stored.
10774 unsigned NumElts = 0;
10775 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10776 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10777 if (!ArgTy->isVectorTy())
10779 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10781 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10782 Info.ptrVal = I.getArgOperand(0);
10784 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10785 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10786 Info.vol = false; // volatile stores with NEON intrinsics not supported
10787 Info.readMem = false;
10788 Info.writeMem = true;
10791 case Intrinsic::arm_ldaex:
10792 case Intrinsic::arm_ldrex: {
10793 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10794 Info.opc = ISD::INTRINSIC_W_CHAIN;
10795 Info.memVT = MVT::getVT(PtrTy->getElementType());
10796 Info.ptrVal = I.getArgOperand(0);
10798 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10800 Info.readMem = true;
10801 Info.writeMem = false;
10804 case Intrinsic::arm_stlex:
10805 case Intrinsic::arm_strex: {
10806 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10807 Info.opc = ISD::INTRINSIC_W_CHAIN;
10808 Info.memVT = MVT::getVT(PtrTy->getElementType());
10809 Info.ptrVal = I.getArgOperand(1);
10811 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10813 Info.readMem = false;
10814 Info.writeMem = true;
10817 case Intrinsic::arm_stlexd:
10818 case Intrinsic::arm_strexd: {
10819 Info.opc = ISD::INTRINSIC_W_CHAIN;
10820 Info.memVT = MVT::i64;
10821 Info.ptrVal = I.getArgOperand(2);
10825 Info.readMem = false;
10826 Info.writeMem = true;
10829 case Intrinsic::arm_ldaexd:
10830 case Intrinsic::arm_ldrexd: {
10831 Info.opc = ISD::INTRINSIC_W_CHAIN;
10832 Info.memVT = MVT::i64;
10833 Info.ptrVal = I.getArgOperand(0);
10837 Info.readMem = true;
10838 Info.writeMem = false;
10848 /// \brief Returns true if it is beneficial to convert a load of a constant
10849 /// to just the constant itself.
10850 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10852 assert(Ty->isIntegerTy());
10854 unsigned Bits = Ty->getPrimitiveSizeInBits();
10855 if (Bits == 0 || Bits > 32)
10860 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10861 // Loads and stores less than 64-bits are already atomic; ones above that
10862 // are doomed anyway, so defer to the default libcall and blame the OS when
10863 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10864 // anything for those.
10865 bool IsMClass = Subtarget->isMClass();
10866 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10867 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10868 return Size == 64 && !IsMClass;
10869 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10870 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10873 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10874 // and up to 64 bits on the non-M profiles
10875 unsigned AtomicLimit = IsMClass ? 32 : 64;
10876 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10879 // This has so far only been implemented for MachO.
10880 bool ARMTargetLowering::useLoadStackGuardNode() const {
10881 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10884 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10885 AtomicOrdering Ord) const {
10886 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10887 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10888 bool IsAcquire = isAtLeastAcquire(Ord);
10890 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10891 // intrinsic must return {i32, i32} and we have to recombine them into a
10892 // single i64 here.
10893 if (ValTy->getPrimitiveSizeInBits() == 64) {
10894 Intrinsic::ID Int =
10895 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10896 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10898 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10899 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10901 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10902 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10903 if (!Subtarget->isLittle())
10904 std::swap (Lo, Hi);
10905 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10906 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10907 return Builder.CreateOr(
10908 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10911 Type *Tys[] = { Addr->getType() };
10912 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10913 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10915 return Builder.CreateTruncOrBitCast(
10916 Builder.CreateCall(Ldrex, Addr),
10917 cast<PointerType>(Addr->getType())->getElementType());
10920 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10922 AtomicOrdering Ord) const {
10923 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10924 bool IsRelease = isAtLeastRelease(Ord);
10926 // Since the intrinsics must have legal type, the i64 intrinsics take two
10927 // parameters: "i32, i32". We must marshal Val into the appropriate form
10928 // before the call.
10929 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10930 Intrinsic::ID Int =
10931 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10932 Function *Strex = Intrinsic::getDeclaration(M, Int);
10933 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10935 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10936 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10937 if (!Subtarget->isLittle())
10938 std::swap (Lo, Hi);
10939 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10940 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10943 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10944 Type *Tys[] = { Addr->getType() };
10945 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10947 return Builder.CreateCall2(
10948 Strex, Builder.CreateZExtOrBitCast(
10949 Val, Strex->getFunctionType()->getParamType(0)),
10961 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10962 uint64_t &Members) {
10963 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10964 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10965 uint64_t SubMembers = 0;
10966 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10968 Members += SubMembers;
10970 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10971 uint64_t SubMembers = 0;
10972 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10974 Members += SubMembers * AT->getNumElements();
10975 } else if (Ty->isFloatTy()) {
10976 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10980 } else if (Ty->isDoubleTy()) {
10981 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10985 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10992 return VT->getBitWidth() == 64;
10994 return VT->getBitWidth() == 128;
10996 switch (VT->getBitWidth()) {
11009 return (Members > 0 && Members <= 4);
11012 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11013 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11014 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11015 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11016 CallingConv::ARM_AAPCS_VFP)
11019 HABaseType Base = HA_UNKNOWN;
11020 uint64_t Members = 0;
11021 bool result = isHomogeneousAggregate(Ty, Base, Members);
11022 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());