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 // If the calling conventions do not match, then we'd better make sure the
2001 // results are returned in the same way as what the caller expects.
2003 SmallVector<CCValAssign, 16> RVLocs1;
2004 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2005 *DAG.getContext(), Call);
2006 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2008 SmallVector<CCValAssign, 16> RVLocs2;
2009 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2010 *DAG.getContext(), Call);
2011 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2013 if (RVLocs1.size() != RVLocs2.size())
2015 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2016 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2018 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2020 if (RVLocs1[i].isRegLoc()) {
2021 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2024 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2030 // If Caller's vararg or byval argument has been split between registers and
2031 // stack, do not perform tail call, since part of the argument is in caller's
2033 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2034 getInfo<ARMFunctionInfo>();
2035 if (AFI_Caller->getArgRegsSaveSize())
2038 // If the callee takes no arguments then go on to check the results of the
2040 if (!Outs.empty()) {
2041 // Check if stack adjustment is needed. For now, do not do this if any
2042 // argument is passed on the stack.
2043 SmallVector<CCValAssign, 16> ArgLocs;
2044 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2045 *DAG.getContext(), Call);
2046 CCInfo.AnalyzeCallOperands(Outs,
2047 CCAssignFnForNode(CalleeCC, false, isVarArg));
2048 if (CCInfo.getNextStackOffset()) {
2049 MachineFunction &MF = DAG.getMachineFunction();
2051 // Check if the arguments are already laid out in the right way as
2052 // the caller's fixed stack objects.
2053 MachineFrameInfo *MFI = MF.getFrameInfo();
2054 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2055 const TargetInstrInfo *TII =
2056 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2057 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2059 ++i, ++realArgIdx) {
2060 CCValAssign &VA = ArgLocs[i];
2061 EVT RegVT = VA.getLocVT();
2062 SDValue Arg = OutVals[realArgIdx];
2063 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2064 if (VA.getLocInfo() == CCValAssign::Indirect)
2066 if (VA.needsCustom()) {
2067 // f64 and vector types are split into multiple registers or
2068 // register/stack-slot combinations. The types will not match
2069 // the registers; give up on memory f64 refs until we figure
2070 // out what to do about this.
2073 if (!ArgLocs[++i].isRegLoc())
2075 if (RegVT == MVT::v2f64) {
2076 if (!ArgLocs[++i].isRegLoc())
2078 if (!ArgLocs[++i].isRegLoc())
2081 } else if (!VA.isRegLoc()) {
2082 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2094 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2095 MachineFunction &MF, bool isVarArg,
2096 const SmallVectorImpl<ISD::OutputArg> &Outs,
2097 LLVMContext &Context) const {
2098 SmallVector<CCValAssign, 16> RVLocs;
2099 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2100 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2104 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2105 SDLoc DL, SelectionDAG &DAG) {
2106 const MachineFunction &MF = DAG.getMachineFunction();
2107 const Function *F = MF.getFunction();
2109 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2111 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2112 // version of the "preferred return address". These offsets affect the return
2113 // instruction if this is a return from PL1 without hypervisor extensions.
2114 // IRQ/FIQ: +4 "subs pc, lr, #4"
2115 // SWI: 0 "subs pc, lr, #0"
2116 // ABORT: +4 "subs pc, lr, #4"
2117 // UNDEF: +4/+2 "subs pc, lr, #0"
2118 // UNDEF varies depending on where the exception came from ARM or Thumb
2119 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2122 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2125 else if (IntKind == "SWI" || IntKind == "UNDEF")
2128 report_fatal_error("Unsupported interrupt attribute. If present, value "
2129 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2131 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2133 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2137 ARMTargetLowering::LowerReturn(SDValue Chain,
2138 CallingConv::ID CallConv, bool isVarArg,
2139 const SmallVectorImpl<ISD::OutputArg> &Outs,
2140 const SmallVectorImpl<SDValue> &OutVals,
2141 SDLoc dl, SelectionDAG &DAG) const {
2143 // CCValAssign - represent the assignment of the return value to a location.
2144 SmallVector<CCValAssign, 16> RVLocs;
2146 // CCState - Info about the registers and stack slots.
2147 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2148 *DAG.getContext(), Call);
2150 // Analyze outgoing return values.
2151 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2155 SmallVector<SDValue, 4> RetOps;
2156 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2157 bool isLittleEndian = Subtarget->isLittle();
2159 MachineFunction &MF = DAG.getMachineFunction();
2160 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2161 AFI->setReturnRegsCount(RVLocs.size());
2163 // Copy the result values into the output registers.
2164 for (unsigned i = 0, realRVLocIdx = 0;
2166 ++i, ++realRVLocIdx) {
2167 CCValAssign &VA = RVLocs[i];
2168 assert(VA.isRegLoc() && "Can only return in registers!");
2170 SDValue Arg = OutVals[realRVLocIdx];
2172 switch (VA.getLocInfo()) {
2173 default: llvm_unreachable("Unknown loc info!");
2174 case CCValAssign::Full: break;
2175 case CCValAssign::BCvt:
2176 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2180 if (VA.needsCustom()) {
2181 if (VA.getLocVT() == MVT::v2f64) {
2182 // Extract the first half and return it in two registers.
2183 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2184 DAG.getConstant(0, MVT::i32));
2185 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2186 DAG.getVTList(MVT::i32, MVT::i32), Half);
2188 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2189 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2191 Flag = Chain.getValue(1);
2192 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2193 VA = RVLocs[++i]; // skip ahead to next loc
2194 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2195 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2197 Flag = Chain.getValue(1);
2198 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2199 VA = RVLocs[++i]; // skip ahead to next loc
2201 // Extract the 2nd half and fall through to handle it as an f64 value.
2202 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2203 DAG.getConstant(1, MVT::i32));
2205 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2207 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2208 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2209 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2210 fmrrd.getValue(isLittleEndian ? 0 : 1),
2212 Flag = Chain.getValue(1);
2213 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2214 VA = RVLocs[++i]; // skip ahead to next loc
2215 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2216 fmrrd.getValue(isLittleEndian ? 1 : 0),
2219 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2221 // Guarantee that all emitted copies are
2222 // stuck together, avoiding something bad.
2223 Flag = Chain.getValue(1);
2224 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227 // Update chain and glue.
2230 RetOps.push_back(Flag);
2232 // CPUs which aren't M-class use a special sequence to return from
2233 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2234 // though we use "subs pc, lr, #N").
2236 // M-class CPUs actually use a normal return sequence with a special
2237 // (hardware-provided) value in LR, so the normal code path works.
2238 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2239 !Subtarget->isMClass()) {
2240 if (Subtarget->isThumb1Only())
2241 report_fatal_error("interrupt attribute is not supported in Thumb1");
2242 return LowerInterruptReturn(RetOps, dl, DAG);
2245 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2248 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2249 if (N->getNumValues() != 1)
2251 if (!N->hasNUsesOfValue(1, 0))
2254 SDValue TCChain = Chain;
2255 SDNode *Copy = *N->use_begin();
2256 if (Copy->getOpcode() == ISD::CopyToReg) {
2257 // If the copy has a glue operand, we conservatively assume it isn't safe to
2258 // perform a tail call.
2259 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2261 TCChain = Copy->getOperand(0);
2262 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2263 SDNode *VMov = Copy;
2264 // f64 returned in a pair of GPRs.
2265 SmallPtrSet<SDNode*, 2> Copies;
2266 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2268 if (UI->getOpcode() != ISD::CopyToReg)
2272 if (Copies.size() > 2)
2275 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2277 SDValue UseChain = UI->getOperand(0);
2278 if (Copies.count(UseChain.getNode()))
2285 } else if (Copy->getOpcode() == ISD::BITCAST) {
2286 // f32 returned in a single GPR.
2287 if (!Copy->hasOneUse())
2289 Copy = *Copy->use_begin();
2290 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2292 TCChain = Copy->getOperand(0);
2297 bool HasRet = false;
2298 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2300 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2301 UI->getOpcode() != ARMISD::INTRET_FLAG)
2313 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2314 if (!Subtarget->supportsTailCall())
2317 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2320 return !Subtarget->isThumb1Only();
2323 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2324 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2325 // one of the above mentioned nodes. It has to be wrapped because otherwise
2326 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2327 // be used to form addressing mode. These wrapped nodes will be selected
2329 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2330 EVT PtrVT = Op.getValueType();
2331 // FIXME there is no actual debug info here
2333 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2335 if (CP->isMachineConstantPoolEntry())
2336 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2337 CP->getAlignment());
2339 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2340 CP->getAlignment());
2341 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2344 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2345 return MachineJumpTableInfo::EK_Inline;
2348 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2349 SelectionDAG &DAG) const {
2350 MachineFunction &MF = DAG.getMachineFunction();
2351 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352 unsigned ARMPCLabelIndex = 0;
2354 EVT PtrVT = getPointerTy();
2355 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2356 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2358 if (RelocM == Reloc::Static) {
2359 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2361 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2362 ARMPCLabelIndex = AFI->createPICLabelUId();
2363 ARMConstantPoolValue *CPV =
2364 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2365 ARMCP::CPBlockAddress, PCAdj);
2366 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2369 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2372 if (RelocM == Reloc::Static)
2374 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2378 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2380 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2381 SelectionDAG &DAG) const {
2383 EVT PtrVT = getPointerTy();
2384 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2385 MachineFunction &MF = DAG.getMachineFunction();
2386 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2387 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2388 ARMConstantPoolValue *CPV =
2389 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2390 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2391 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2392 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2393 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2394 MachinePointerInfo::getConstantPool(),
2395 false, false, false, 0);
2396 SDValue Chain = Argument.getValue(1);
2398 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2399 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2401 // call __tls_get_addr.
2404 Entry.Node = Argument;
2405 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2406 Args.push_back(Entry);
2408 // FIXME: is there useful debug info available here?
2409 TargetLowering::CallLoweringInfo CLI(DAG);
2410 CLI.setDebugLoc(dl).setChain(Chain)
2411 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2412 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2415 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2416 return CallResult.first;
2419 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2420 // "local exec" model.
2422 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2424 TLSModel::Model model) const {
2425 const GlobalValue *GV = GA->getGlobal();
2428 SDValue Chain = DAG.getEntryNode();
2429 EVT PtrVT = getPointerTy();
2430 // Get the Thread Pointer
2431 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2433 if (model == TLSModel::InitialExec) {
2434 MachineFunction &MF = DAG.getMachineFunction();
2435 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2436 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2437 // Initial exec model.
2438 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2439 ARMConstantPoolValue *CPV =
2440 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2441 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2443 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2444 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2445 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2446 MachinePointerInfo::getConstantPool(),
2447 false, false, false, 0);
2448 Chain = Offset.getValue(1);
2450 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2451 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2453 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2454 MachinePointerInfo::getConstantPool(),
2455 false, false, false, 0);
2458 assert(model == TLSModel::LocalExec);
2459 ARMConstantPoolValue *CPV =
2460 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2461 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2462 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2463 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2464 MachinePointerInfo::getConstantPool(),
2465 false, false, false, 0);
2468 // The address of the thread local variable is the add of the thread
2469 // pointer with the offset of the variable.
2470 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2474 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2475 // TODO: implement the "local dynamic" model
2476 assert(Subtarget->isTargetELF() &&
2477 "TLS not implemented for non-ELF targets");
2478 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2480 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2483 case TLSModel::GeneralDynamic:
2484 case TLSModel::LocalDynamic:
2485 return LowerToTLSGeneralDynamicModel(GA, DAG);
2486 case TLSModel::InitialExec:
2487 case TLSModel::LocalExec:
2488 return LowerToTLSExecModels(GA, DAG, model);
2490 llvm_unreachable("bogus TLS model");
2493 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2494 SelectionDAG &DAG) const {
2495 EVT PtrVT = getPointerTy();
2497 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2498 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2499 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2500 ARMConstantPoolValue *CPV =
2501 ARMConstantPoolConstant::Create(GV,
2502 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2503 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2504 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2505 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2507 MachinePointerInfo::getConstantPool(),
2508 false, false, false, 0);
2509 SDValue Chain = Result.getValue(1);
2510 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2511 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2513 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2514 MachinePointerInfo::getGOT(),
2515 false, false, false, 0);
2519 // If we have T2 ops, we can materialize the address directly via movt/movw
2520 // pair. This is always cheaper.
2521 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2523 // FIXME: Once remat is capable of dealing with instructions with register
2524 // operands, expand this into two nodes.
2525 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2526 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2528 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2529 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2530 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2531 MachinePointerInfo::getConstantPool(),
2532 false, false, false, 0);
2536 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2537 SelectionDAG &DAG) const {
2538 EVT PtrVT = getPointerTy();
2540 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2543 if (Subtarget->useMovt(DAG.getMachineFunction()))
2546 // FIXME: Once remat is capable of dealing with instructions with register
2547 // operands, expand this into multiple nodes
2549 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2551 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2552 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2554 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2555 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2556 MachinePointerInfo::getGOT(), false, false, false, 0);
2560 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2561 SelectionDAG &DAG) const {
2562 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2563 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2564 "Windows on ARM expects to use movw/movt");
2566 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2567 const ARMII::TOF TargetFlags =
2568 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2569 EVT PtrVT = getPointerTy();
2575 // FIXME: Once remat is capable of dealing with instructions with register
2576 // operands, expand this into two nodes.
2577 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2578 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2580 if (GV->hasDLLImportStorageClass())
2581 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2582 MachinePointerInfo::getGOT(), false, false, false, 0);
2586 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2587 SelectionDAG &DAG) const {
2588 assert(Subtarget->isTargetELF() &&
2589 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2590 MachineFunction &MF = DAG.getMachineFunction();
2591 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2592 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2593 EVT PtrVT = getPointerTy();
2595 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2596 ARMConstantPoolValue *CPV =
2597 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2598 ARMPCLabelIndex, PCAdj);
2599 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2600 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2601 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2602 MachinePointerInfo::getConstantPool(),
2603 false, false, false, 0);
2604 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2605 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2609 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2611 SDValue Val = DAG.getConstant(0, MVT::i32);
2612 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2613 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2614 Op.getOperand(1), Val);
2618 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2620 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2621 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2625 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2626 const ARMSubtarget *Subtarget) const {
2627 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2630 default: return SDValue(); // Don't custom lower most intrinsics.
2631 case Intrinsic::arm_rbit: {
2632 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2633 "RBIT intrinsic must have i32 type!");
2634 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2636 case Intrinsic::arm_thread_pointer: {
2637 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2638 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2640 case Intrinsic::eh_sjlj_lsda: {
2641 MachineFunction &MF = DAG.getMachineFunction();
2642 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2643 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2644 EVT PtrVT = getPointerTy();
2645 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2647 unsigned PCAdj = (RelocM != Reloc::PIC_)
2648 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2649 ARMConstantPoolValue *CPV =
2650 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2651 ARMCP::CPLSDA, PCAdj);
2652 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2653 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2655 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2656 MachinePointerInfo::getConstantPool(),
2657 false, false, false, 0);
2659 if (RelocM == Reloc::PIC_) {
2660 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2661 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2665 case Intrinsic::arm_neon_vmulls:
2666 case Intrinsic::arm_neon_vmullu: {
2667 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2668 ? ARMISD::VMULLs : ARMISD::VMULLu;
2669 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2670 Op.getOperand(1), Op.getOperand(2));
2675 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2676 const ARMSubtarget *Subtarget) {
2677 // FIXME: handle "fence singlethread" more efficiently.
2679 if (!Subtarget->hasDataBarrier()) {
2680 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2681 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2683 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2684 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2685 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2686 DAG.getConstant(0, MVT::i32));
2689 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2690 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2691 unsigned Domain = ARM_MB::ISH;
2692 if (Subtarget->isMClass()) {
2693 // Only a full system barrier exists in the M-class architectures.
2694 Domain = ARM_MB::SY;
2695 } else if (Subtarget->isSwift() && Ord == Release) {
2696 // Swift happens to implement ISHST barriers in a way that's compatible with
2697 // Release semantics but weaker than ISH so we'd be fools not to use
2698 // it. Beware: other processors probably don't!
2699 Domain = ARM_MB::ISHST;
2702 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2703 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2704 DAG.getConstant(Domain, MVT::i32));
2707 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2708 const ARMSubtarget *Subtarget) {
2709 // ARM pre v5TE and Thumb1 does not have preload instructions.
2710 if (!(Subtarget->isThumb2() ||
2711 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2712 // Just preserve the chain.
2713 return Op.getOperand(0);
2716 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2718 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2719 // ARMv7 with MP extension has PLDW.
2720 return Op.getOperand(0);
2722 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2723 if (Subtarget->isThumb()) {
2725 isRead = ~isRead & 1;
2726 isData = ~isData & 1;
2729 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2730 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2731 DAG.getConstant(isData, MVT::i32));
2734 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2735 MachineFunction &MF = DAG.getMachineFunction();
2736 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2738 // vastart just stores the address of the VarArgsFrameIndex slot into the
2739 // memory location argument.
2741 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2742 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2743 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2744 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2745 MachinePointerInfo(SV), false, false, 0);
2749 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2750 SDValue &Root, SelectionDAG &DAG,
2752 MachineFunction &MF = DAG.getMachineFunction();
2753 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2755 const TargetRegisterClass *RC;
2756 if (AFI->isThumb1OnlyFunction())
2757 RC = &ARM::tGPRRegClass;
2759 RC = &ARM::GPRRegClass;
2761 // Transform the arguments stored in physical registers into virtual ones.
2762 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2763 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2766 if (NextVA.isMemLoc()) {
2767 MachineFrameInfo *MFI = MF.getFrameInfo();
2768 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2770 // Create load node to retrieve arguments from the stack.
2771 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2773 MachinePointerInfo::getFixedStack(FI),
2774 false, false, false, 0);
2776 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2777 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2779 if (!Subtarget->isLittle())
2780 std::swap (ArgValue, ArgValue2);
2781 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2785 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2786 unsigned InRegsParamRecordIdx,
2788 unsigned &ArgRegsSize,
2789 unsigned &ArgRegsSaveSize)
2792 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2793 unsigned RBegin, REnd;
2794 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2795 NumGPRs = REnd - RBegin;
2797 unsigned int firstUnalloced;
2798 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2799 sizeof(GPRArgRegs) /
2800 sizeof(GPRArgRegs[0]));
2801 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2804 unsigned Align = MF.getTarget()
2806 ->getFrameLowering()
2807 ->getStackAlignment();
2808 ArgRegsSize = NumGPRs * 4;
2810 // If parameter is split between stack and GPRs...
2811 if (NumGPRs && Align > 4 &&
2812 (ArgRegsSize < ArgSize ||
2813 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2814 // Add padding for part of param recovered from GPRs. For example,
2815 // if Align == 8, its last byte must be at address K*8 - 1.
2816 // We need to do it, since remained (stack) part of parameter has
2817 // stack alignment, and we need to "attach" "GPRs head" without gaps
2820 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2821 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2823 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2825 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2826 ArgRegsSaveSize = ArgRegsSize + Padding;
2828 // We don't need to extend regs save size for byval parameters if they
2829 // are passed via GPRs only.
2830 ArgRegsSaveSize = ArgRegsSize;
2833 // The remaining GPRs hold either the beginning of variable-argument
2834 // data, or the beginning of an aggregate passed by value (usually
2835 // byval). Either way, we allocate stack slots adjacent to the data
2836 // provided by our caller, and store the unallocated registers there.
2837 // If this is a variadic function, the va_list pointer will begin with
2838 // these values; otherwise, this reassembles a (byval) structure that
2839 // was split between registers and memory.
2840 // Return: The frame index registers were stored into.
2842 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2843 SDLoc dl, SDValue &Chain,
2844 const Value *OrigArg,
2845 unsigned InRegsParamRecordIdx,
2846 unsigned OffsetFromOrigArg,
2850 unsigned ByValStoreOffset,
2851 unsigned TotalArgRegsSaveSize) const {
2853 // Currently, two use-cases possible:
2854 // Case #1. Non-var-args function, and we meet first byval parameter.
2855 // Setup first unallocated register as first byval register;
2856 // eat all remained registers
2857 // (these two actions are performed by HandleByVal method).
2858 // Then, here, we initialize stack frame with
2859 // "store-reg" instructions.
2860 // Case #2. Var-args function, that doesn't contain byval parameters.
2861 // The same: eat all remained unallocated registers,
2862 // initialize stack frame.
2864 MachineFunction &MF = DAG.getMachineFunction();
2865 MachineFrameInfo *MFI = MF.getFrameInfo();
2866 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2867 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2868 unsigned RBegin, REnd;
2869 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2870 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2871 firstRegToSaveIndex = RBegin - ARM::R0;
2872 lastRegToSaveIndex = REnd - ARM::R0;
2874 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2875 (GPRArgRegs, array_lengthof(GPRArgRegs));
2876 lastRegToSaveIndex = 4;
2879 unsigned ArgRegsSize, ArgRegsSaveSize;
2880 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2881 ArgRegsSize, ArgRegsSaveSize);
2883 // Store any by-val regs to their spots on the stack so that they may be
2884 // loaded by deferencing the result of formal parameter pointer or va_next.
2885 // Note: once stack area for byval/varargs registers
2886 // was initialized, it can't be initialized again.
2887 if (ArgRegsSaveSize) {
2888 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2891 assert(AFI->getStoredByValParamsPadding() == 0 &&
2892 "The only parameter may be padded.");
2893 AFI->setStoredByValParamsPadding(Padding);
2896 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2899 (int64_t)TotalArgRegsSaveSize,
2901 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2903 MFI->CreateFixedObject(Padding,
2904 ArgOffset + ByValStoreOffset -
2905 (int64_t)ArgRegsSaveSize,
2909 SmallVector<SDValue, 4> MemOps;
2910 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2911 ++firstRegToSaveIndex, ++i) {
2912 const TargetRegisterClass *RC;
2913 if (AFI->isThumb1OnlyFunction())
2914 RC = &ARM::tGPRRegClass;
2916 RC = &ARM::GPRRegClass;
2918 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2919 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2921 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2922 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2924 MemOps.push_back(Store);
2925 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2926 DAG.getConstant(4, getPointerTy()));
2929 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2931 if (!MemOps.empty())
2932 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2936 // We cannot allocate a zero-byte object for the first variadic argument,
2937 // so just make up a size.
2940 // This will point to the next argument passed via stack.
2941 return MFI->CreateFixedObject(
2942 ArgSize, ArgOffset, !ForceMutable);
2946 // Setup stack frame, the va_list pointer will start from.
2948 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2949 SDLoc dl, SDValue &Chain,
2951 unsigned TotalArgRegsSaveSize,
2952 bool ForceMutable) const {
2953 MachineFunction &MF = DAG.getMachineFunction();
2954 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2956 // Try to store any remaining integer argument regs
2957 // to their spots on the stack so that they may be loaded by deferencing
2958 // the result of va_next.
2959 // If there is no regs to be stored, just point address after last
2960 // argument passed via stack.
2962 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2963 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2964 0, TotalArgRegsSaveSize);
2966 AFI->setVarArgsFrameIndex(FrameIndex);
2970 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2971 CallingConv::ID CallConv, bool isVarArg,
2972 const SmallVectorImpl<ISD::InputArg>
2974 SDLoc dl, SelectionDAG &DAG,
2975 SmallVectorImpl<SDValue> &InVals)
2977 MachineFunction &MF = DAG.getMachineFunction();
2978 MachineFrameInfo *MFI = MF.getFrameInfo();
2980 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2982 // Assign locations to all of the incoming arguments.
2983 SmallVector<CCValAssign, 16> ArgLocs;
2984 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2985 *DAG.getContext(), Prologue);
2986 CCInfo.AnalyzeFormalArguments(Ins,
2987 CCAssignFnForNode(CallConv, /* Return*/ false,
2990 SmallVector<SDValue, 16> ArgValues;
2991 int lastInsIndex = -1;
2993 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2994 unsigned CurArgIdx = 0;
2996 // Initially ArgRegsSaveSize is zero.
2997 // Then we increase this value each time we meet byval parameter.
2998 // We also increase this value in case of varargs function.
2999 AFI->setArgRegsSaveSize(0);
3001 unsigned ByValStoreOffset = 0;
3002 unsigned TotalArgRegsSaveSize = 0;
3003 unsigned ArgRegsSaveSizeMaxAlign = 4;
3005 // Calculate the amount of stack space that we need to allocate to store
3006 // byval and variadic arguments that are passed in registers.
3007 // We need to know this before we allocate the first byval or variadic
3008 // argument, as they will be allocated a stack slot below the CFA (Canonical
3009 // Frame Address, the stack pointer at entry to the function).
3010 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3011 CCValAssign &VA = ArgLocs[i];
3012 if (VA.isMemLoc()) {
3013 int index = VA.getValNo();
3014 if (index != lastInsIndex) {
3015 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3016 if (Flags.isByVal()) {
3017 unsigned ExtraArgRegsSize;
3018 unsigned ExtraArgRegsSaveSize;
3019 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3020 Flags.getByValSize(),
3021 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3023 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3024 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3025 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3026 CCInfo.nextInRegsParam();
3028 lastInsIndex = index;
3032 CCInfo.rewindByValRegsInfo();
3035 unsigned ExtraArgRegsSize;
3036 unsigned ExtraArgRegsSaveSize;
3037 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3038 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3039 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3041 // If the arg regs save area contains N-byte aligned values, the
3042 // bottom of it must be at least N-byte aligned.
3043 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3044 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3046 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3047 CCValAssign &VA = ArgLocs[i];
3048 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3049 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3050 // Arguments stored in registers.
3051 if (VA.isRegLoc()) {
3052 EVT RegVT = VA.getLocVT();
3054 if (VA.needsCustom()) {
3055 // f64 and vector types are split up into multiple registers or
3056 // combinations of registers and stack slots.
3057 if (VA.getLocVT() == MVT::v2f64) {
3058 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3060 VA = ArgLocs[++i]; // skip ahead to next loc
3062 if (VA.isMemLoc()) {
3063 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3064 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3065 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3066 MachinePointerInfo::getFixedStack(FI),
3067 false, false, false, 0);
3069 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3072 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3073 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3074 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3075 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3076 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3078 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3081 const TargetRegisterClass *RC;
3083 if (RegVT == MVT::f32)
3084 RC = &ARM::SPRRegClass;
3085 else if (RegVT == MVT::f64)
3086 RC = &ARM::DPRRegClass;
3087 else if (RegVT == MVT::v2f64)
3088 RC = &ARM::QPRRegClass;
3089 else if (RegVT == MVT::i32)
3090 RC = AFI->isThumb1OnlyFunction() ?
3091 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3092 (const TargetRegisterClass*)&ARM::GPRRegClass;
3094 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3096 // Transform the arguments in physical registers into virtual ones.
3097 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3098 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3101 // If this is an 8 or 16-bit value, it is really passed promoted
3102 // to 32 bits. Insert an assert[sz]ext to capture this, then
3103 // truncate to the right size.
3104 switch (VA.getLocInfo()) {
3105 default: llvm_unreachable("Unknown loc info!");
3106 case CCValAssign::Full: break;
3107 case CCValAssign::BCvt:
3108 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3110 case CCValAssign::SExt:
3111 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3112 DAG.getValueType(VA.getValVT()));
3113 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3115 case CCValAssign::ZExt:
3116 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3117 DAG.getValueType(VA.getValVT()));
3118 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3122 InVals.push_back(ArgValue);
3124 } else { // VA.isRegLoc()
3127 assert(VA.isMemLoc());
3128 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3130 int index = ArgLocs[i].getValNo();
3132 // Some Ins[] entries become multiple ArgLoc[] entries.
3133 // Process them only once.
3134 if (index != lastInsIndex)
3136 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3137 // FIXME: For now, all byval parameter objects are marked mutable.
3138 // This can be changed with more analysis.
3139 // In case of tail call optimization mark all arguments mutable.
3140 // Since they could be overwritten by lowering of arguments in case of
3142 if (Flags.isByVal()) {
3143 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3145 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3146 int FrameIndex = StoreByValRegs(
3147 CCInfo, DAG, dl, Chain, CurOrigArg,
3149 Ins[VA.getValNo()].PartOffset,
3150 VA.getLocMemOffset(),
3151 Flags.getByValSize(),
3152 true /*force mutable frames*/,
3154 TotalArgRegsSaveSize);
3155 ByValStoreOffset += Flags.getByValSize();
3156 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3157 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3158 CCInfo.nextInRegsParam();
3160 unsigned FIOffset = VA.getLocMemOffset();
3161 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3164 // Create load nodes to retrieve arguments from the stack.
3165 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3166 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3167 MachinePointerInfo::getFixedStack(FI),
3168 false, false, false, 0));
3170 lastInsIndex = index;
3177 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3178 CCInfo.getNextStackOffset(),
3179 TotalArgRegsSaveSize);
3181 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3186 /// isFloatingPointZero - Return true if this is +0.0.
3187 static bool isFloatingPointZero(SDValue Op) {
3188 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3189 return CFP->getValueAPF().isPosZero();
3190 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3191 // Maybe this has already been legalized into the constant pool?
3192 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3193 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3194 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3195 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3196 return CFP->getValueAPF().isPosZero();
3202 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3203 /// the given operands.
3205 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3206 SDValue &ARMcc, SelectionDAG &DAG,
3208 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3209 unsigned C = RHSC->getZExtValue();
3210 if (!isLegalICmpImmediate(C)) {
3211 // Constant does not fit, try adjusting it by one?
3216 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3217 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3218 RHS = DAG.getConstant(C-1, MVT::i32);
3223 if (C != 0 && isLegalICmpImmediate(C-1)) {
3224 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3225 RHS = DAG.getConstant(C-1, MVT::i32);
3230 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3231 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3232 RHS = DAG.getConstant(C+1, MVT::i32);
3237 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3238 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3239 RHS = DAG.getConstant(C+1, MVT::i32);
3246 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3247 ARMISD::NodeType CompareType;
3250 CompareType = ARMISD::CMP;
3255 CompareType = ARMISD::CMPZ;
3258 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3259 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3262 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3264 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3267 if (!isFloatingPointZero(RHS))
3268 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3270 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3271 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3274 /// duplicateCmp - Glue values can have only one use, so this function
3275 /// duplicates a comparison node.
3277 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3278 unsigned Opc = Cmp.getOpcode();
3280 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3281 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3283 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3284 Cmp = Cmp.getOperand(0);
3285 Opc = Cmp.getOpcode();
3286 if (Opc == ARMISD::CMPFP)
3287 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3289 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3290 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3292 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3295 std::pair<SDValue, SDValue>
3296 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3297 SDValue &ARMcc) const {
3298 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3300 SDValue Value, OverflowCmp;
3301 SDValue LHS = Op.getOperand(0);
3302 SDValue RHS = Op.getOperand(1);
3305 // FIXME: We are currently always generating CMPs because we don't support
3306 // generating CMN through the backend. This is not as good as the natural
3307 // CMP case because it causes a register dependency and cannot be folded
3310 switch (Op.getOpcode()) {
3312 llvm_unreachable("Unknown overflow instruction!");
3314 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3315 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3316 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3319 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3320 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3321 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3324 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3325 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3326 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3329 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3330 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3331 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3335 return std::make_pair(Value, OverflowCmp);
3340 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3341 // Let legalize expand this if it isn't a legal type yet.
3342 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3345 SDValue Value, OverflowCmp;
3347 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3348 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3349 // We use 0 and 1 as false and true values.
3350 SDValue TVal = DAG.getConstant(1, MVT::i32);
3351 SDValue FVal = DAG.getConstant(0, MVT::i32);
3352 EVT VT = Op.getValueType();
3354 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3355 ARMcc, CCR, OverflowCmp);
3357 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3358 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3362 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3363 SDValue Cond = Op.getOperand(0);
3364 SDValue SelectTrue = Op.getOperand(1);
3365 SDValue SelectFalse = Op.getOperand(2);
3367 unsigned Opc = Cond.getOpcode();
3369 if (Cond.getResNo() == 1 &&
3370 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3371 Opc == ISD::USUBO)) {
3372 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3375 SDValue Value, OverflowCmp;
3377 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3378 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3379 EVT VT = Op.getValueType();
3381 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3382 ARMcc, CCR, OverflowCmp);
3388 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3389 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3391 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3392 const ConstantSDNode *CMOVTrue =
3393 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3394 const ConstantSDNode *CMOVFalse =
3395 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3397 if (CMOVTrue && CMOVFalse) {
3398 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3399 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3403 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3405 False = SelectFalse;
3406 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3411 if (True.getNode() && False.getNode()) {
3412 EVT VT = Op.getValueType();
3413 SDValue ARMcc = Cond.getOperand(2);
3414 SDValue CCR = Cond.getOperand(3);
3415 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3416 assert(True.getValueType() == VT);
3417 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3422 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3423 // undefined bits before doing a full-word comparison with zero.
3424 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3425 DAG.getConstant(1, Cond.getValueType()));
3427 return DAG.getSelectCC(dl, Cond,
3428 DAG.getConstant(0, Cond.getValueType()),
3429 SelectTrue, SelectFalse, ISD::SETNE);
3432 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3433 if (CC == ISD::SETNE)
3435 return ISD::getSetCCInverse(CC, true);
3438 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3439 bool &swpCmpOps, bool &swpVselOps) {
3440 // Start by selecting the GE condition code for opcodes that return true for
3442 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3444 CondCode = ARMCC::GE;
3446 // and GT for opcodes that return false for 'equality'.
3447 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3449 CondCode = ARMCC::GT;
3451 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3452 // to swap the compare operands.
3453 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3457 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3458 // If we have an unordered opcode, we need to swap the operands to the VSEL
3459 // instruction (effectively negating the condition).
3461 // This also has the effect of swapping which one of 'less' or 'greater'
3462 // returns true, so we also swap the compare operands. It also switches
3463 // whether we return true for 'equality', so we compensate by picking the
3464 // opposite condition code to our original choice.
3465 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3466 CC == ISD::SETUGT) {
3467 swpCmpOps = !swpCmpOps;
3468 swpVselOps = !swpVselOps;
3469 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3472 // 'ordered' is 'anything but unordered', so use the VS condition code and
3473 // swap the VSEL operands.
3474 if (CC == ISD::SETO) {
3475 CondCode = ARMCC::VS;
3479 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3480 // code and swap the VSEL operands.
3481 if (CC == ISD::SETUNE) {
3482 CondCode = ARMCC::EQ;
3487 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3488 EVT VT = Op.getValueType();
3489 SDValue LHS = Op.getOperand(0);
3490 SDValue RHS = Op.getOperand(1);
3491 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3492 SDValue TrueVal = Op.getOperand(2);
3493 SDValue FalseVal = Op.getOperand(3);
3496 if (LHS.getValueType() == MVT::i32) {
3497 // Try to generate VSEL on ARMv8.
3498 // The VSEL instruction can't use all the usual ARM condition
3499 // codes: it only has two bits to select the condition code, so it's
3500 // constrained to use only GE, GT, VS and EQ.
3502 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3503 // swap the operands of the previous compare instruction (effectively
3504 // inverting the compare condition, swapping 'less' and 'greater') and
3505 // sometimes need to swap the operands to the VSEL (which inverts the
3506 // condition in the sense of firing whenever the previous condition didn't)
3507 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3508 TrueVal.getValueType() == MVT::f64)) {
3509 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3510 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3511 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3512 CC = getInverseCCForVSEL(CC);
3513 std::swap(TrueVal, FalseVal);
3518 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3519 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3520 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3524 ARMCC::CondCodes CondCode, CondCode2;
3525 FPCCToARMCC(CC, CondCode, CondCode2);
3527 // Try to generate VSEL on ARMv8.
3528 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3529 TrueVal.getValueType() == MVT::f64)) {
3530 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3531 // same operands, as follows:
3532 // c = fcmp [ogt, olt, ugt, ult] a, b
3534 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3535 // handled differently than the original code sequence.
3536 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3538 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3539 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3540 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3541 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3544 bool swpCmpOps = false;
3545 bool swpVselOps = false;
3546 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3548 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3549 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3551 std::swap(LHS, RHS);
3553 std::swap(TrueVal, FalseVal);
3557 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3558 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3559 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3560 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3562 if (CondCode2 != ARMCC::AL) {
3563 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3564 // FIXME: Needs another CMP because flag can have but one use.
3565 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3566 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3567 Result, TrueVal, ARMcc2, CCR, Cmp2);
3572 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3573 /// to morph to an integer compare sequence.
3574 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3575 const ARMSubtarget *Subtarget) {
3576 SDNode *N = Op.getNode();
3577 if (!N->hasOneUse())
3578 // Otherwise it requires moving the value from fp to integer registers.
3580 if (!N->getNumValues())
3582 EVT VT = Op.getValueType();
3583 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3584 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3585 // vmrs are very slow, e.g. cortex-a8.
3588 if (isFloatingPointZero(Op)) {
3592 return ISD::isNormalLoad(N);
3595 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3596 if (isFloatingPointZero(Op))
3597 return DAG.getConstant(0, MVT::i32);
3599 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3600 return DAG.getLoad(MVT::i32, SDLoc(Op),
3601 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3602 Ld->isVolatile(), Ld->isNonTemporal(),
3603 Ld->isInvariant(), Ld->getAlignment());
3605 llvm_unreachable("Unknown VFP cmp argument!");
3608 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3609 SDValue &RetVal1, SDValue &RetVal2) {
3610 if (isFloatingPointZero(Op)) {
3611 RetVal1 = DAG.getConstant(0, MVT::i32);
3612 RetVal2 = DAG.getConstant(0, MVT::i32);
3616 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3617 SDValue Ptr = Ld->getBasePtr();
3618 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3619 Ld->getChain(), Ptr,
3620 Ld->getPointerInfo(),
3621 Ld->isVolatile(), Ld->isNonTemporal(),
3622 Ld->isInvariant(), Ld->getAlignment());
3624 EVT PtrType = Ptr.getValueType();
3625 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3626 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3627 PtrType, Ptr, DAG.getConstant(4, PtrType));
3628 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3629 Ld->getChain(), NewPtr,
3630 Ld->getPointerInfo().getWithOffset(4),
3631 Ld->isVolatile(), Ld->isNonTemporal(),
3632 Ld->isInvariant(), NewAlign);
3636 llvm_unreachable("Unknown VFP cmp argument!");
3639 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3640 /// f32 and even f64 comparisons to integer ones.
3642 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3643 SDValue Chain = Op.getOperand(0);
3644 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3645 SDValue LHS = Op.getOperand(2);
3646 SDValue RHS = Op.getOperand(3);
3647 SDValue Dest = Op.getOperand(4);
3650 bool LHSSeenZero = false;
3651 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3652 bool RHSSeenZero = false;
3653 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3654 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3655 // If unsafe fp math optimization is enabled and there are no other uses of
3656 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3657 // to an integer comparison.
3658 if (CC == ISD::SETOEQ)
3660 else if (CC == ISD::SETUNE)
3663 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3665 if (LHS.getValueType() == MVT::f32) {
3666 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3667 bitcastf32Toi32(LHS, DAG), Mask);
3668 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3669 bitcastf32Toi32(RHS, DAG), Mask);
3670 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3671 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3672 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3673 Chain, Dest, ARMcc, CCR, Cmp);
3678 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3679 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3680 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3681 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3682 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3683 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3684 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3685 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3686 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3692 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3693 SDValue Chain = Op.getOperand(0);
3694 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3695 SDValue LHS = Op.getOperand(2);
3696 SDValue RHS = Op.getOperand(3);
3697 SDValue Dest = Op.getOperand(4);
3700 if (LHS.getValueType() == MVT::i32) {
3702 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3703 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3704 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3705 Chain, Dest, ARMcc, CCR, Cmp);
3708 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3710 if (getTargetMachine().Options.UnsafeFPMath &&
3711 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3712 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3713 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3714 if (Result.getNode())
3718 ARMCC::CondCodes CondCode, CondCode2;
3719 FPCCToARMCC(CC, CondCode, CondCode2);
3721 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3722 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3723 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3724 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3725 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3726 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3727 if (CondCode2 != ARMCC::AL) {
3728 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3729 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3730 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3735 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3736 SDValue Chain = Op.getOperand(0);
3737 SDValue Table = Op.getOperand(1);
3738 SDValue Index = Op.getOperand(2);
3741 EVT PTy = getPointerTy();
3742 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3743 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3744 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3745 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3746 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3747 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3748 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3749 if (Subtarget->isThumb2()) {
3750 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3751 // which does another jump to the destination. This also makes it easier
3752 // to translate it to TBB / TBH later.
3753 // FIXME: This might not work if the function is extremely large.
3754 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3755 Addr, Op.getOperand(2), JTI, UId);
3757 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3758 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3759 MachinePointerInfo::getJumpTable(),
3760 false, false, false, 0);
3761 Chain = Addr.getValue(1);
3762 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3763 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3765 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3766 MachinePointerInfo::getJumpTable(),
3767 false, false, false, 0);
3768 Chain = Addr.getValue(1);
3769 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3773 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3774 EVT VT = Op.getValueType();
3777 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3778 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3780 return DAG.UnrollVectorOp(Op.getNode());
3783 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3784 "Invalid type for custom lowering!");
3785 if (VT != MVT::v4i16)
3786 return DAG.UnrollVectorOp(Op.getNode());
3788 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3789 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3792 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3793 EVT VT = Op.getValueType();
3795 return LowerVectorFP_TO_INT(Op, DAG);
3800 switch (Op.getOpcode()) {
3801 default: llvm_unreachable("Invalid opcode!");
3802 case ISD::FP_TO_SINT:
3803 Opc = ARMISD::FTOSI;
3805 case ISD::FP_TO_UINT:
3806 Opc = ARMISD::FTOUI;
3809 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3810 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3813 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3814 EVT VT = Op.getValueType();
3817 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3818 if (VT.getVectorElementType() == MVT::f32)
3820 return DAG.UnrollVectorOp(Op.getNode());
3823 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3824 "Invalid type for custom lowering!");
3825 if (VT != MVT::v4f32)
3826 return DAG.UnrollVectorOp(Op.getNode());
3830 switch (Op.getOpcode()) {
3831 default: llvm_unreachable("Invalid opcode!");
3832 case ISD::SINT_TO_FP:
3833 CastOpc = ISD::SIGN_EXTEND;
3834 Opc = ISD::SINT_TO_FP;
3836 case ISD::UINT_TO_FP:
3837 CastOpc = ISD::ZERO_EXTEND;
3838 Opc = ISD::UINT_TO_FP;
3842 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3843 return DAG.getNode(Opc, dl, VT, Op);
3846 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3847 EVT VT = Op.getValueType();
3849 return LowerVectorINT_TO_FP(Op, DAG);
3854 switch (Op.getOpcode()) {
3855 default: llvm_unreachable("Invalid opcode!");
3856 case ISD::SINT_TO_FP:
3857 Opc = ARMISD::SITOF;
3859 case ISD::UINT_TO_FP:
3860 Opc = ARMISD::UITOF;
3864 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3865 return DAG.getNode(Opc, dl, VT, Op);
3868 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3869 // Implement fcopysign with a fabs and a conditional fneg.
3870 SDValue Tmp0 = Op.getOperand(0);
3871 SDValue Tmp1 = Op.getOperand(1);
3873 EVT VT = Op.getValueType();
3874 EVT SrcVT = Tmp1.getValueType();
3875 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3876 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3877 bool UseNEON = !InGPR && Subtarget->hasNEON();
3880 // Use VBSL to copy the sign bit.
3881 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3882 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3883 DAG.getTargetConstant(EncodedVal, MVT::i32));
3884 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3886 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3887 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3888 DAG.getConstant(32, MVT::i32));
3889 else /*if (VT == MVT::f32)*/
3890 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3891 if (SrcVT == MVT::f32) {
3892 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3894 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3895 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3896 DAG.getConstant(32, MVT::i32));
3897 } else if (VT == MVT::f32)
3898 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3899 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3900 DAG.getConstant(32, MVT::i32));
3901 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3902 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3904 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3906 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3907 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3908 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3910 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3911 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3912 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3913 if (VT == MVT::f32) {
3914 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3915 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3916 DAG.getConstant(0, MVT::i32));
3918 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3924 // Bitcast operand 1 to i32.
3925 if (SrcVT == MVT::f64)
3926 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3928 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3930 // Or in the signbit with integer operations.
3931 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3932 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3933 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3934 if (VT == MVT::f32) {
3935 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3936 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3937 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3938 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3941 // f64: Or the high part with signbit and then combine two parts.
3942 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3944 SDValue Lo = Tmp0.getValue(0);
3945 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3946 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3947 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3950 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3951 MachineFunction &MF = DAG.getMachineFunction();
3952 MachineFrameInfo *MFI = MF.getFrameInfo();
3953 MFI->setReturnAddressIsTaken(true);
3955 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3958 EVT VT = Op.getValueType();
3960 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3962 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3963 SDValue Offset = DAG.getConstant(4, MVT::i32);
3964 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3965 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3966 MachinePointerInfo(), false, false, false, 0);
3969 // Return LR, which contains the return address. Mark it an implicit live-in.
3970 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3971 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3974 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3975 const ARMBaseRegisterInfo &ARI =
3976 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3977 MachineFunction &MF = DAG.getMachineFunction();
3978 MachineFrameInfo *MFI = MF.getFrameInfo();
3979 MFI->setFrameAddressIsTaken(true);
3981 EVT VT = Op.getValueType();
3982 SDLoc dl(Op); // FIXME probably not meaningful
3983 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3984 unsigned FrameReg = ARI.getFrameRegister(MF);
3985 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3987 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3988 MachinePointerInfo(),
3989 false, false, false, 0);
3993 // FIXME? Maybe this could be a TableGen attribute on some registers and
3994 // this table could be generated automatically from RegInfo.
3995 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3997 unsigned Reg = StringSwitch<unsigned>(RegName)
3998 .Case("sp", ARM::SP)
4002 report_fatal_error("Invalid register name global variable");
4005 /// ExpandBITCAST - If the target supports VFP, this function is called to
4006 /// expand a bit convert where either the source or destination type is i64 to
4007 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4008 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4009 /// vectors), since the legalizer won't know what to do with that.
4010 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4011 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4013 SDValue Op = N->getOperand(0);
4015 // This function is only supposed to be called for i64 types, either as the
4016 // source or destination of the bit convert.
4017 EVT SrcVT = Op.getValueType();
4018 EVT DstVT = N->getValueType(0);
4019 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4020 "ExpandBITCAST called for non-i64 type");
4022 // Turn i64->f64 into VMOVDRR.
4023 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4024 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4025 DAG.getConstant(0, MVT::i32));
4026 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4027 DAG.getConstant(1, MVT::i32));
4028 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4029 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4032 // Turn f64->i64 into VMOVRRD.
4033 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4035 if (TLI.isBigEndian() && SrcVT.isVector() &&
4036 SrcVT.getVectorNumElements() > 1)
4037 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4038 DAG.getVTList(MVT::i32, MVT::i32),
4039 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4041 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4042 DAG.getVTList(MVT::i32, MVT::i32), Op);
4043 // Merge the pieces into a single i64 value.
4044 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4050 /// getZeroVector - Returns a vector of specified type with all zero elements.
4051 /// Zero vectors are used to represent vector negation and in those cases
4052 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4053 /// not support i64 elements, so sometimes the zero vectors will need to be
4054 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4056 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4057 assert(VT.isVector() && "Expected a vector type");
4058 // The canonical modified immediate encoding of a zero vector is....0!
4059 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4060 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4061 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4062 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4065 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4066 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4067 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4068 SelectionDAG &DAG) const {
4069 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4070 EVT VT = Op.getValueType();
4071 unsigned VTBits = VT.getSizeInBits();
4073 SDValue ShOpLo = Op.getOperand(0);
4074 SDValue ShOpHi = Op.getOperand(1);
4075 SDValue ShAmt = Op.getOperand(2);
4077 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4079 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4081 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4082 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4083 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4084 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4085 DAG.getConstant(VTBits, MVT::i32));
4086 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4087 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4088 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4090 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4091 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4093 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4094 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4097 SDValue Ops[2] = { Lo, Hi };
4098 return DAG.getMergeValues(Ops, dl);
4101 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4102 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4103 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4104 SelectionDAG &DAG) const {
4105 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4106 EVT VT = Op.getValueType();
4107 unsigned VTBits = VT.getSizeInBits();
4109 SDValue ShOpLo = Op.getOperand(0);
4110 SDValue ShOpHi = Op.getOperand(1);
4111 SDValue ShAmt = Op.getOperand(2);
4114 assert(Op.getOpcode() == ISD::SHL_PARTS);
4115 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4116 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4117 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4118 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4119 DAG.getConstant(VTBits, MVT::i32));
4120 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4121 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4123 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4124 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4125 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4127 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4128 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4131 SDValue Ops[2] = { Lo, Hi };
4132 return DAG.getMergeValues(Ops, dl);
4135 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 // The rounding mode is in bits 23:22 of the FPSCR.
4138 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4139 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4140 // so that the shift + and get folded into a bitfield extract.
4142 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4143 DAG.getConstant(Intrinsic::arm_get_fpscr,
4145 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4146 DAG.getConstant(1U << 22, MVT::i32));
4147 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4148 DAG.getConstant(22, MVT::i32));
4149 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4150 DAG.getConstant(3, MVT::i32));
4153 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4154 const ARMSubtarget *ST) {
4155 EVT VT = N->getValueType(0);
4158 if (!ST->hasV6T2Ops())
4161 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4162 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4165 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4166 /// for each 16-bit element from operand, repeated. The basic idea is to
4167 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4169 /// Trace for v4i16:
4170 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4171 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4172 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4173 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4174 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4175 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4176 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4177 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4178 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4179 EVT VT = N->getValueType(0);
4182 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4183 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4184 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4185 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4186 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4187 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4190 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4191 /// bit-count for each 16-bit element from the operand. We need slightly
4192 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4193 /// 64/128-bit registers.
4195 /// Trace for v4i16:
4196 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4197 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4198 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4199 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4200 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4201 EVT VT = N->getValueType(0);
4204 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4205 if (VT.is64BitVector()) {
4206 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4207 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4208 DAG.getIntPtrConstant(0));
4210 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4211 BitCounts, DAG.getIntPtrConstant(0));
4212 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4216 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4217 /// bit-count for each 32-bit element from the operand. The idea here is
4218 /// to split the vector into 16-bit elements, leverage the 16-bit count
4219 /// routine, and then combine the results.
4221 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4222 /// input = [v0 v1 ] (vi: 32-bit elements)
4223 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4224 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4225 /// vrev: N0 = [k1 k0 k3 k2 ]
4227 /// N1 =+[k1 k0 k3 k2 ]
4229 /// N2 =+[k1 k3 k0 k2 ]
4231 /// Extended =+[k1 k3 k0 k2 ]
4233 /// Extracted=+[k1 k3 ]
4235 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4236 EVT VT = N->getValueType(0);
4239 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4241 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4242 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4243 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4244 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4245 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4247 if (VT.is64BitVector()) {
4248 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4249 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4250 DAG.getIntPtrConstant(0));
4252 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4253 DAG.getIntPtrConstant(0));
4254 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4258 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4259 const ARMSubtarget *ST) {
4260 EVT VT = N->getValueType(0);
4262 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4263 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4264 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4265 "Unexpected type for custom ctpop lowering");
4267 if (VT.getVectorElementType() == MVT::i32)
4268 return lowerCTPOP32BitElements(N, DAG);
4270 return lowerCTPOP16BitElements(N, DAG);
4273 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4274 const ARMSubtarget *ST) {
4275 EVT VT = N->getValueType(0);
4281 // Lower vector shifts on NEON to use VSHL.
4282 assert(ST->hasNEON() && "unexpected vector shift");
4284 // Left shifts translate directly to the vshiftu intrinsic.
4285 if (N->getOpcode() == ISD::SHL)
4286 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4287 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4288 N->getOperand(0), N->getOperand(1));
4290 assert((N->getOpcode() == ISD::SRA ||
4291 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4293 // NEON uses the same intrinsics for both left and right shifts. For
4294 // right shifts, the shift amounts are negative, so negate the vector of
4296 EVT ShiftVT = N->getOperand(1).getValueType();
4297 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4298 getZeroVector(ShiftVT, DAG, dl),
4300 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4301 Intrinsic::arm_neon_vshifts :
4302 Intrinsic::arm_neon_vshiftu);
4303 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4304 DAG.getConstant(vshiftInt, MVT::i32),
4305 N->getOperand(0), NegatedCount);
4308 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4309 const ARMSubtarget *ST) {
4310 EVT VT = N->getValueType(0);
4313 // We can get here for a node like i32 = ISD::SHL i32, i64
4317 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4318 "Unknown shift to lower!");
4320 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4321 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4322 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4325 // If we are in thumb mode, we don't have RRX.
4326 if (ST->isThumb1Only()) return SDValue();
4328 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4329 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4330 DAG.getConstant(0, MVT::i32));
4331 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4332 DAG.getConstant(1, MVT::i32));
4334 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4335 // captures the result into a carry flag.
4336 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4337 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4339 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4340 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4342 // Merge the pieces into a single i64 value.
4343 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4346 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4347 SDValue TmpOp0, TmpOp1;
4348 bool Invert = false;
4352 SDValue Op0 = Op.getOperand(0);
4353 SDValue Op1 = Op.getOperand(1);
4354 SDValue CC = Op.getOperand(2);
4355 EVT VT = Op.getValueType();
4356 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4359 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4360 switch (SetCCOpcode) {
4361 default: llvm_unreachable("Illegal FP comparison");
4363 case ISD::SETNE: Invert = true; // Fallthrough
4365 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4367 case ISD::SETLT: Swap = true; // Fallthrough
4369 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4371 case ISD::SETLE: Swap = true; // Fallthrough
4373 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4374 case ISD::SETUGE: Swap = true; // Fallthrough
4375 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4376 case ISD::SETUGT: Swap = true; // Fallthrough
4377 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4378 case ISD::SETUEQ: Invert = true; // Fallthrough
4380 // Expand this to (OLT | OGT).
4384 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4385 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4387 case ISD::SETUO: Invert = true; // Fallthrough
4389 // Expand this to (OLT | OGE).
4393 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4394 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4398 // Integer comparisons.
4399 switch (SetCCOpcode) {
4400 default: llvm_unreachable("Illegal integer comparison");
4401 case ISD::SETNE: Invert = true;
4402 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4403 case ISD::SETLT: Swap = true;
4404 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4405 case ISD::SETLE: Swap = true;
4406 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4407 case ISD::SETULT: Swap = true;
4408 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4409 case ISD::SETULE: Swap = true;
4410 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4413 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4414 if (Opc == ARMISD::VCEQ) {
4417 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4419 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4422 // Ignore bitconvert.
4423 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4424 AndOp = AndOp.getOperand(0);
4426 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4428 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4429 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4436 std::swap(Op0, Op1);
4438 // If one of the operands is a constant vector zero, attempt to fold the
4439 // comparison to a specialized compare-against-zero form.
4441 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4443 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4444 if (Opc == ARMISD::VCGE)
4445 Opc = ARMISD::VCLEZ;
4446 else if (Opc == ARMISD::VCGT)
4447 Opc = ARMISD::VCLTZ;
4452 if (SingleOp.getNode()) {
4455 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4457 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4459 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4461 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4463 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4465 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4468 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4472 Result = DAG.getNOT(dl, Result, VT);
4477 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4478 /// valid vector constant for a NEON instruction with a "modified immediate"
4479 /// operand (e.g., VMOV). If so, return the encoded value.
4480 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4481 unsigned SplatBitSize, SelectionDAG &DAG,
4482 EVT &VT, bool is128Bits, NEONModImmType type) {
4483 unsigned OpCmode, Imm;
4485 // SplatBitSize is set to the smallest size that splats the vector, so a
4486 // zero vector will always have SplatBitSize == 8. However, NEON modified
4487 // immediate instructions others than VMOV do not support the 8-bit encoding
4488 // of a zero vector, and the default encoding of zero is supposed to be the
4493 switch (SplatBitSize) {
4495 if (type != VMOVModImm)
4497 // Any 1-byte value is OK. Op=0, Cmode=1110.
4498 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4501 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4505 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4506 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4507 if ((SplatBits & ~0xff) == 0) {
4508 // Value = 0x00nn: Op=x, Cmode=100x.
4513 if ((SplatBits & ~0xff00) == 0) {
4514 // Value = 0xnn00: Op=x, Cmode=101x.
4516 Imm = SplatBits >> 8;
4522 // NEON's 32-bit VMOV supports splat values where:
4523 // * only one byte is nonzero, or
4524 // * the least significant byte is 0xff and the second byte is nonzero, or
4525 // * the least significant 2 bytes are 0xff and the third is nonzero.
4526 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4527 if ((SplatBits & ~0xff) == 0) {
4528 // Value = 0x000000nn: Op=x, Cmode=000x.
4533 if ((SplatBits & ~0xff00) == 0) {
4534 // Value = 0x0000nn00: Op=x, Cmode=001x.
4536 Imm = SplatBits >> 8;
4539 if ((SplatBits & ~0xff0000) == 0) {
4540 // Value = 0x00nn0000: Op=x, Cmode=010x.
4542 Imm = SplatBits >> 16;
4545 if ((SplatBits & ~0xff000000) == 0) {
4546 // Value = 0xnn000000: Op=x, Cmode=011x.
4548 Imm = SplatBits >> 24;
4552 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4553 if (type == OtherModImm) return SDValue();
4555 if ((SplatBits & ~0xffff) == 0 &&
4556 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4557 // Value = 0x0000nnff: Op=x, Cmode=1100.
4559 Imm = SplatBits >> 8;
4563 if ((SplatBits & ~0xffffff) == 0 &&
4564 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4565 // Value = 0x00nnffff: Op=x, Cmode=1101.
4567 Imm = SplatBits >> 16;
4571 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4572 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4573 // VMOV.I32. A (very) minor optimization would be to replicate the value
4574 // and fall through here to test for a valid 64-bit splat. But, then the
4575 // caller would also need to check and handle the change in size.
4579 if (type != VMOVModImm)
4581 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4582 uint64_t BitMask = 0xff;
4584 unsigned ImmMask = 1;
4586 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4587 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4590 } else if ((SplatBits & BitMask) != 0) {
4597 if (DAG.getTargetLoweringInfo().isBigEndian())
4598 // swap higher and lower 32 bit word
4599 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4601 // Op=1, Cmode=1110.
4603 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4608 llvm_unreachable("unexpected size for isNEONModifiedImm");
4611 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4612 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4615 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4616 const ARMSubtarget *ST) const {
4620 bool IsDouble = Op.getValueType() == MVT::f64;
4621 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4623 // Try splatting with a VMOV.f32...
4624 APFloat FPVal = CFP->getValueAPF();
4625 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4628 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4629 // We have code in place to select a valid ConstantFP already, no need to
4634 // It's a float and we are trying to use NEON operations where
4635 // possible. Lower it to a splat followed by an extract.
4637 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4638 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4640 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4641 DAG.getConstant(0, MVT::i32));
4644 // The rest of our options are NEON only, make sure that's allowed before
4646 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4650 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4652 // It wouldn't really be worth bothering for doubles except for one very
4653 // important value, which does happen to match: 0.0. So make sure we don't do
4655 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4658 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4659 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4661 if (NewVal != SDValue()) {
4663 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4666 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4668 // It's a float: cast and extract a vector element.
4669 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4671 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4672 DAG.getConstant(0, MVT::i32));
4675 // Finally, try a VMVN.i32
4676 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4678 if (NewVal != SDValue()) {
4680 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4683 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4685 // It's a float: cast and extract a vector element.
4686 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4688 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4689 DAG.getConstant(0, MVT::i32));
4695 // check if an VEXT instruction can handle the shuffle mask when the
4696 // vector sources of the shuffle are the same.
4697 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4698 unsigned NumElts = VT.getVectorNumElements();
4700 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4706 // If this is a VEXT shuffle, the immediate value is the index of the first
4707 // element. The other shuffle indices must be the successive elements after
4709 unsigned ExpectedElt = Imm;
4710 for (unsigned i = 1; i < NumElts; ++i) {
4711 // Increment the expected index. If it wraps around, just follow it
4712 // back to index zero and keep going.
4714 if (ExpectedElt == NumElts)
4717 if (M[i] < 0) continue; // ignore UNDEF indices
4718 if (ExpectedElt != static_cast<unsigned>(M[i]))
4726 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4727 bool &ReverseVEXT, unsigned &Imm) {
4728 unsigned NumElts = VT.getVectorNumElements();
4729 ReverseVEXT = false;
4731 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4737 // If this is a VEXT shuffle, the immediate value is the index of the first
4738 // element. The other shuffle indices must be the successive elements after
4740 unsigned ExpectedElt = Imm;
4741 for (unsigned i = 1; i < NumElts; ++i) {
4742 // Increment the expected index. If it wraps around, it may still be
4743 // a VEXT but the source vectors must be swapped.
4745 if (ExpectedElt == NumElts * 2) {
4750 if (M[i] < 0) continue; // ignore UNDEF indices
4751 if (ExpectedElt != static_cast<unsigned>(M[i]))
4755 // Adjust the index value if the source operands will be swapped.
4762 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4763 /// instruction with the specified blocksize. (The order of the elements
4764 /// within each block of the vector is reversed.)
4765 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4766 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4767 "Only possible block sizes for VREV are: 16, 32, 64");
4769 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4773 unsigned NumElts = VT.getVectorNumElements();
4774 unsigned BlockElts = M[0] + 1;
4775 // If the first shuffle index is UNDEF, be optimistic.
4777 BlockElts = BlockSize / EltSz;
4779 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4782 for (unsigned i = 0; i < NumElts; ++i) {
4783 if (M[i] < 0) continue; // ignore UNDEF indices
4784 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4791 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4792 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4793 // range, then 0 is placed into the resulting vector. So pretty much any mask
4794 // of 8 elements can work here.
4795 return VT == MVT::v8i8 && M.size() == 8;
4798 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4799 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4803 unsigned NumElts = VT.getVectorNumElements();
4804 WhichResult = (M[0] == 0 ? 0 : 1);
4805 for (unsigned i = 0; i < NumElts; i += 2) {
4806 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4807 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4813 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4814 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4815 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4816 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4817 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4821 unsigned NumElts = VT.getVectorNumElements();
4822 WhichResult = (M[0] == 0 ? 0 : 1);
4823 for (unsigned i = 0; i < NumElts; i += 2) {
4824 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4825 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4831 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4832 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4836 unsigned NumElts = VT.getVectorNumElements();
4837 WhichResult = (M[0] == 0 ? 0 : 1);
4838 for (unsigned i = 0; i != NumElts; ++i) {
4839 if (M[i] < 0) continue; // ignore UNDEF indices
4840 if ((unsigned) M[i] != 2 * i + WhichResult)
4844 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4845 if (VT.is64BitVector() && EltSz == 32)
4851 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4852 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4853 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4854 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4855 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4859 unsigned Half = VT.getVectorNumElements() / 2;
4860 WhichResult = (M[0] == 0 ? 0 : 1);
4861 for (unsigned j = 0; j != 2; ++j) {
4862 unsigned Idx = WhichResult;
4863 for (unsigned i = 0; i != Half; ++i) {
4864 int MIdx = M[i + j * Half];
4865 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4871 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4872 if (VT.is64BitVector() && EltSz == 32)
4878 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4879 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4883 unsigned NumElts = VT.getVectorNumElements();
4884 WhichResult = (M[0] == 0 ? 0 : 1);
4885 unsigned Idx = WhichResult * NumElts / 2;
4886 for (unsigned i = 0; i != NumElts; i += 2) {
4887 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4888 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4893 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4894 if (VT.is64BitVector() && EltSz == 32)
4900 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4901 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4902 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4903 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4904 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4908 unsigned NumElts = VT.getVectorNumElements();
4909 WhichResult = (M[0] == 0 ? 0 : 1);
4910 unsigned Idx = WhichResult * NumElts / 2;
4911 for (unsigned i = 0; i != NumElts; i += 2) {
4912 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4913 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4918 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4919 if (VT.is64BitVector() && EltSz == 32)
4925 /// \return true if this is a reverse operation on an vector.
4926 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4927 unsigned NumElts = VT.getVectorNumElements();
4928 // Make sure the mask has the right size.
4929 if (NumElts != M.size())
4932 // Look for <15, ..., 3, -1, 1, 0>.
4933 for (unsigned i = 0; i != NumElts; ++i)
4934 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4940 // If N is an integer constant that can be moved into a register in one
4941 // instruction, return an SDValue of such a constant (will become a MOV
4942 // instruction). Otherwise return null.
4943 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4944 const ARMSubtarget *ST, SDLoc dl) {
4946 if (!isa<ConstantSDNode>(N))
4948 Val = cast<ConstantSDNode>(N)->getZExtValue();
4950 if (ST->isThumb1Only()) {
4951 if (Val <= 255 || ~Val <= 255)
4952 return DAG.getConstant(Val, MVT::i32);
4954 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4955 return DAG.getConstant(Val, MVT::i32);
4960 // If this is a case we can't handle, return null and let the default
4961 // expansion code take care of it.
4962 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4963 const ARMSubtarget *ST) const {
4964 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4966 EVT VT = Op.getValueType();
4968 APInt SplatBits, SplatUndef;
4969 unsigned SplatBitSize;
4971 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4972 if (SplatBitSize <= 64) {
4973 // Check if an immediate VMOV works.
4975 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4976 SplatUndef.getZExtValue(), SplatBitSize,
4977 DAG, VmovVT, VT.is128BitVector(),
4979 if (Val.getNode()) {
4980 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4981 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4984 // Try an immediate VMVN.
4985 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4986 Val = isNEONModifiedImm(NegatedImm,
4987 SplatUndef.getZExtValue(), SplatBitSize,
4988 DAG, VmovVT, VT.is128BitVector(),
4990 if (Val.getNode()) {
4991 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4992 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4995 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4996 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4997 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4999 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5000 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5006 // Scan through the operands to see if only one value is used.
5008 // As an optimisation, even if more than one value is used it may be more
5009 // profitable to splat with one value then change some lanes.
5011 // Heuristically we decide to do this if the vector has a "dominant" value,
5012 // defined as splatted to more than half of the lanes.
5013 unsigned NumElts = VT.getVectorNumElements();
5014 bool isOnlyLowElement = true;
5015 bool usesOnlyOneValue = true;
5016 bool hasDominantValue = false;
5017 bool isConstant = true;
5019 // Map of the number of times a particular SDValue appears in the
5021 DenseMap<SDValue, unsigned> ValueCounts;
5023 for (unsigned i = 0; i < NumElts; ++i) {
5024 SDValue V = Op.getOperand(i);
5025 if (V.getOpcode() == ISD::UNDEF)
5028 isOnlyLowElement = false;
5029 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5032 ValueCounts.insert(std::make_pair(V, 0));
5033 unsigned &Count = ValueCounts[V];
5035 // Is this value dominant? (takes up more than half of the lanes)
5036 if (++Count > (NumElts / 2)) {
5037 hasDominantValue = true;
5041 if (ValueCounts.size() != 1)
5042 usesOnlyOneValue = false;
5043 if (!Value.getNode() && ValueCounts.size() > 0)
5044 Value = ValueCounts.begin()->first;
5046 if (ValueCounts.size() == 0)
5047 return DAG.getUNDEF(VT);
5049 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5050 // Keep going if we are hitting this case.
5051 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5052 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5054 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5056 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5057 // i32 and try again.
5058 if (hasDominantValue && EltSize <= 32) {
5062 // If we are VDUPing a value that comes directly from a vector, that will
5063 // cause an unnecessary move to and from a GPR, where instead we could
5064 // just use VDUPLANE. We can only do this if the lane being extracted
5065 // is at a constant index, as the VDUP from lane instructions only have
5066 // constant-index forms.
5067 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5068 isa<ConstantSDNode>(Value->getOperand(1))) {
5069 // We need to create a new undef vector to use for the VDUPLANE if the
5070 // size of the vector from which we get the value is different than the
5071 // size of the vector that we need to create. We will insert the element
5072 // such that the register coalescer will remove unnecessary copies.
5073 if (VT != Value->getOperand(0).getValueType()) {
5074 ConstantSDNode *constIndex;
5075 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5076 assert(constIndex && "The index is not a constant!");
5077 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5078 VT.getVectorNumElements();
5079 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5080 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5081 Value, DAG.getConstant(index, MVT::i32)),
5082 DAG.getConstant(index, MVT::i32));
5084 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5085 Value->getOperand(0), Value->getOperand(1));
5087 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5089 if (!usesOnlyOneValue) {
5090 // The dominant value was splatted as 'N', but we now have to insert
5091 // all differing elements.
5092 for (unsigned I = 0; I < NumElts; ++I) {
5093 if (Op.getOperand(I) == Value)
5095 SmallVector<SDValue, 3> Ops;
5097 Ops.push_back(Op.getOperand(I));
5098 Ops.push_back(DAG.getConstant(I, MVT::i32));
5099 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5104 if (VT.getVectorElementType().isFloatingPoint()) {
5105 SmallVector<SDValue, 8> Ops;
5106 for (unsigned i = 0; i < NumElts; ++i)
5107 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5109 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5110 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5111 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5113 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5115 if (usesOnlyOneValue) {
5116 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5117 if (isConstant && Val.getNode())
5118 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5122 // If all elements are constants and the case above didn't get hit, fall back
5123 // to the default expansion, which will generate a load from the constant
5128 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5130 SDValue shuffle = ReconstructShuffle(Op, DAG);
5131 if (shuffle != SDValue())
5135 // Vectors with 32- or 64-bit elements can be built by directly assigning
5136 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5137 // will be legalized.
5138 if (EltSize >= 32) {
5139 // Do the expansion with floating-point types, since that is what the VFP
5140 // registers are defined to use, and since i64 is not legal.
5141 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5142 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5143 SmallVector<SDValue, 8> Ops;
5144 for (unsigned i = 0; i < NumElts; ++i)
5145 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5146 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5147 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5150 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5151 // know the default expansion would otherwise fall back on something even
5152 // worse. For a vector with one or two non-undef values, that's
5153 // scalar_to_vector for the elements followed by a shuffle (provided the
5154 // shuffle is valid for the target) and materialization element by element
5155 // on the stack followed by a load for everything else.
5156 if (!isConstant && !usesOnlyOneValue) {
5157 SDValue Vec = DAG.getUNDEF(VT);
5158 for (unsigned i = 0 ; i < NumElts; ++i) {
5159 SDValue V = Op.getOperand(i);
5160 if (V.getOpcode() == ISD::UNDEF)
5162 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5163 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5171 // Gather data to see if the operation can be modelled as a
5172 // shuffle in combination with VEXTs.
5173 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5174 SelectionDAG &DAG) const {
5176 EVT VT = Op.getValueType();
5177 unsigned NumElts = VT.getVectorNumElements();
5179 SmallVector<SDValue, 2> SourceVecs;
5180 SmallVector<unsigned, 2> MinElts;
5181 SmallVector<unsigned, 2> MaxElts;
5183 for (unsigned i = 0; i < NumElts; ++i) {
5184 SDValue V = Op.getOperand(i);
5185 if (V.getOpcode() == ISD::UNDEF)
5187 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5188 // A shuffle can only come from building a vector from various
5189 // elements of other vectors.
5191 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5192 VT.getVectorElementType()) {
5193 // This code doesn't know how to handle shuffles where the vector
5194 // element types do not match (this happens because type legalization
5195 // promotes the return type of EXTRACT_VECTOR_ELT).
5196 // FIXME: It might be appropriate to extend this code to handle
5197 // mismatched types.
5201 // Record this extraction against the appropriate vector if possible...
5202 SDValue SourceVec = V.getOperand(0);
5203 // If the element number isn't a constant, we can't effectively
5204 // analyze what's going on.
5205 if (!isa<ConstantSDNode>(V.getOperand(1)))
5207 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5208 bool FoundSource = false;
5209 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5210 if (SourceVecs[j] == SourceVec) {
5211 if (MinElts[j] > EltNo)
5213 if (MaxElts[j] < EltNo)
5220 // Or record a new source if not...
5222 SourceVecs.push_back(SourceVec);
5223 MinElts.push_back(EltNo);
5224 MaxElts.push_back(EltNo);
5228 // Currently only do something sane when at most two source vectors
5230 if (SourceVecs.size() > 2)
5233 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5234 int VEXTOffsets[2] = {0, 0};
5236 // This loop extracts the usage patterns of the source vectors
5237 // and prepares appropriate SDValues for a shuffle if possible.
5238 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5239 if (SourceVecs[i].getValueType() == VT) {
5240 // No VEXT necessary
5241 ShuffleSrcs[i] = SourceVecs[i];
5244 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5245 // It probably isn't worth padding out a smaller vector just to
5246 // break it down again in a shuffle.
5250 // Since only 64-bit and 128-bit vectors are legal on ARM and
5251 // we've eliminated the other cases...
5252 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5253 "unexpected vector sizes in ReconstructShuffle");
5255 if (MaxElts[i] - MinElts[i] >= NumElts) {
5256 // Span too large for a VEXT to cope
5260 if (MinElts[i] >= NumElts) {
5261 // The extraction can just take the second half
5262 VEXTOffsets[i] = NumElts;
5263 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5265 DAG.getIntPtrConstant(NumElts));
5266 } else if (MaxElts[i] < NumElts) {
5267 // The extraction can just take the first half
5269 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5271 DAG.getIntPtrConstant(0));
5273 // An actual VEXT is needed
5274 VEXTOffsets[i] = MinElts[i];
5275 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5277 DAG.getIntPtrConstant(0));
5278 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5280 DAG.getIntPtrConstant(NumElts));
5281 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5282 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5286 SmallVector<int, 8> Mask;
5288 for (unsigned i = 0; i < NumElts; ++i) {
5289 SDValue Entry = Op.getOperand(i);
5290 if (Entry.getOpcode() == ISD::UNDEF) {
5295 SDValue ExtractVec = Entry.getOperand(0);
5296 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5297 .getOperand(1))->getSExtValue();
5298 if (ExtractVec == SourceVecs[0]) {
5299 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5301 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5305 // Final check before we try to produce nonsense...
5306 if (isShuffleMaskLegal(Mask, VT))
5307 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5313 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5314 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5315 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5316 /// are assumed to be legal.
5318 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5320 if (VT.getVectorNumElements() == 4 &&
5321 (VT.is128BitVector() || VT.is64BitVector())) {
5322 unsigned PFIndexes[4];
5323 for (unsigned i = 0; i != 4; ++i) {
5327 PFIndexes[i] = M[i];
5330 // Compute the index in the perfect shuffle table.
5331 unsigned PFTableIndex =
5332 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5333 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5334 unsigned Cost = (PFEntry >> 30);
5341 unsigned Imm, WhichResult;
5343 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5344 return (EltSize >= 32 ||
5345 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5346 isVREVMask(M, VT, 64) ||
5347 isVREVMask(M, VT, 32) ||
5348 isVREVMask(M, VT, 16) ||
5349 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5350 isVTBLMask(M, VT) ||
5351 isVTRNMask(M, VT, WhichResult) ||
5352 isVUZPMask(M, VT, WhichResult) ||
5353 isVZIPMask(M, VT, WhichResult) ||
5354 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5355 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5356 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5357 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5360 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5361 /// the specified operations to build the shuffle.
5362 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5363 SDValue RHS, SelectionDAG &DAG,
5365 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5366 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5367 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5370 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5379 OP_VUZPL, // VUZP, left result
5380 OP_VUZPR, // VUZP, right result
5381 OP_VZIPL, // VZIP, left result
5382 OP_VZIPR, // VZIP, right result
5383 OP_VTRNL, // VTRN, left result
5384 OP_VTRNR // VTRN, right result
5387 if (OpNum == OP_COPY) {
5388 if (LHSID == (1*9+2)*9+3) return LHS;
5389 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5393 SDValue OpLHS, OpRHS;
5394 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5395 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5396 EVT VT = OpLHS.getValueType();
5399 default: llvm_unreachable("Unknown shuffle opcode!");
5401 // VREV divides the vector in half and swaps within the half.
5402 if (VT.getVectorElementType() == MVT::i32 ||
5403 VT.getVectorElementType() == MVT::f32)
5404 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5405 // vrev <4 x i16> -> VREV32
5406 if (VT.getVectorElementType() == MVT::i16)
5407 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5408 // vrev <4 x i8> -> VREV16
5409 assert(VT.getVectorElementType() == MVT::i8);
5410 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5415 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5416 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5420 return DAG.getNode(ARMISD::VEXT, dl, VT,
5422 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5425 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5426 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5429 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5430 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5433 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5434 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5438 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5439 ArrayRef<int> ShuffleMask,
5440 SelectionDAG &DAG) {
5441 // Check to see if we can use the VTBL instruction.
5442 SDValue V1 = Op.getOperand(0);
5443 SDValue V2 = Op.getOperand(1);
5446 SmallVector<SDValue, 8> VTBLMask;
5447 for (ArrayRef<int>::iterator
5448 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5449 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5451 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5452 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5453 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5455 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5456 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5459 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5460 SelectionDAG &DAG) {
5462 SDValue OpLHS = Op.getOperand(0);
5463 EVT VT = OpLHS.getValueType();
5465 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5466 "Expect an v8i16/v16i8 type");
5467 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5468 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5469 // extract the first 8 bytes into the top double word and the last 8 bytes
5470 // into the bottom double word. The v8i16 case is similar.
5471 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5472 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5473 DAG.getConstant(ExtractNum, MVT::i32));
5476 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5477 SDValue V1 = Op.getOperand(0);
5478 SDValue V2 = Op.getOperand(1);
5480 EVT VT = Op.getValueType();
5481 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5483 // Convert shuffles that are directly supported on NEON to target-specific
5484 // DAG nodes, instead of keeping them as shuffles and matching them again
5485 // during code selection. This is more efficient and avoids the possibility
5486 // of inconsistencies between legalization and selection.
5487 // FIXME: floating-point vectors should be canonicalized to integer vectors
5488 // of the same time so that they get CSEd properly.
5489 ArrayRef<int> ShuffleMask = SVN->getMask();
5491 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5492 if (EltSize <= 32) {
5493 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5494 int Lane = SVN->getSplatIndex();
5495 // If this is undef splat, generate it via "just" vdup, if possible.
5496 if (Lane == -1) Lane = 0;
5498 // Test if V1 is a SCALAR_TO_VECTOR.
5499 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5500 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5502 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5503 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5505 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5506 !isa<ConstantSDNode>(V1.getOperand(0))) {
5507 bool IsScalarToVector = true;
5508 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5509 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5510 IsScalarToVector = false;
5513 if (IsScalarToVector)
5514 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5516 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5517 DAG.getConstant(Lane, MVT::i32));
5522 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5525 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5526 DAG.getConstant(Imm, MVT::i32));
5529 if (isVREVMask(ShuffleMask, VT, 64))
5530 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5531 if (isVREVMask(ShuffleMask, VT, 32))
5532 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5533 if (isVREVMask(ShuffleMask, VT, 16))
5534 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5536 if (V2->getOpcode() == ISD::UNDEF &&
5537 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5538 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5539 DAG.getConstant(Imm, MVT::i32));
5542 // Check for Neon shuffles that modify both input vectors in place.
5543 // If both results are used, i.e., if there are two shuffles with the same
5544 // source operands and with masks corresponding to both results of one of
5545 // these operations, DAG memoization will ensure that a single node is
5546 // used for both shuffles.
5547 unsigned WhichResult;
5548 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5549 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5550 V1, V2).getValue(WhichResult);
5551 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5552 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5553 V1, V2).getValue(WhichResult);
5554 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5555 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5556 V1, V2).getValue(WhichResult);
5558 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5559 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5560 V1, V1).getValue(WhichResult);
5561 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5562 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5563 V1, V1).getValue(WhichResult);
5564 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5565 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5566 V1, V1).getValue(WhichResult);
5569 // If the shuffle is not directly supported and it has 4 elements, use
5570 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5571 unsigned NumElts = VT.getVectorNumElements();
5573 unsigned PFIndexes[4];
5574 for (unsigned i = 0; i != 4; ++i) {
5575 if (ShuffleMask[i] < 0)
5578 PFIndexes[i] = ShuffleMask[i];
5581 // Compute the index in the perfect shuffle table.
5582 unsigned PFTableIndex =
5583 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5584 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5585 unsigned Cost = (PFEntry >> 30);
5588 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5591 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5592 if (EltSize >= 32) {
5593 // Do the expansion with floating-point types, since that is what the VFP
5594 // registers are defined to use, and since i64 is not legal.
5595 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5596 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5597 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5598 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5599 SmallVector<SDValue, 8> Ops;
5600 for (unsigned i = 0; i < NumElts; ++i) {
5601 if (ShuffleMask[i] < 0)
5602 Ops.push_back(DAG.getUNDEF(EltVT));
5604 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5605 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5606 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5609 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5610 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5613 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5614 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5616 if (VT == MVT::v8i8) {
5617 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5618 if (NewOp.getNode())
5625 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5626 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5627 SDValue Lane = Op.getOperand(2);
5628 if (!isa<ConstantSDNode>(Lane))
5634 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5635 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5636 SDValue Lane = Op.getOperand(1);
5637 if (!isa<ConstantSDNode>(Lane))
5640 SDValue Vec = Op.getOperand(0);
5641 if (Op.getValueType() == MVT::i32 &&
5642 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5644 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5650 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5651 // The only time a CONCAT_VECTORS operation can have legal types is when
5652 // two 64-bit vectors are concatenated to a 128-bit vector.
5653 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5654 "unexpected CONCAT_VECTORS");
5656 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5657 SDValue Op0 = Op.getOperand(0);
5658 SDValue Op1 = Op.getOperand(1);
5659 if (Op0.getOpcode() != ISD::UNDEF)
5660 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5661 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5662 DAG.getIntPtrConstant(0));
5663 if (Op1.getOpcode() != ISD::UNDEF)
5664 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5665 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5666 DAG.getIntPtrConstant(1));
5667 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5670 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5671 /// element has been zero/sign-extended, depending on the isSigned parameter,
5672 /// from an integer type half its size.
5673 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5675 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5676 EVT VT = N->getValueType(0);
5677 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5678 SDNode *BVN = N->getOperand(0).getNode();
5679 if (BVN->getValueType(0) != MVT::v4i32 ||
5680 BVN->getOpcode() != ISD::BUILD_VECTOR)
5682 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5683 unsigned HiElt = 1 - LoElt;
5684 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5685 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5686 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5687 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5688 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5691 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5692 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5695 if (Hi0->isNullValue() && Hi1->isNullValue())
5701 if (N->getOpcode() != ISD::BUILD_VECTOR)
5704 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5705 SDNode *Elt = N->getOperand(i).getNode();
5706 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5707 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5708 unsigned HalfSize = EltSize / 2;
5710 if (!isIntN(HalfSize, C->getSExtValue()))
5713 if (!isUIntN(HalfSize, C->getZExtValue()))
5724 /// isSignExtended - Check if a node is a vector value that is sign-extended
5725 /// or a constant BUILD_VECTOR with sign-extended elements.
5726 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5727 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5729 if (isExtendedBUILD_VECTOR(N, DAG, true))
5734 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5735 /// or a constant BUILD_VECTOR with zero-extended elements.
5736 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5737 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5739 if (isExtendedBUILD_VECTOR(N, DAG, false))
5744 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5745 if (OrigVT.getSizeInBits() >= 64)
5748 assert(OrigVT.isSimple() && "Expecting a simple value type");
5750 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5751 switch (OrigSimpleTy) {
5752 default: llvm_unreachable("Unexpected Vector Type");
5761 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5762 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5763 /// We insert the required extension here to get the vector to fill a D register.
5764 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5767 unsigned ExtOpcode) {
5768 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5769 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5770 // 64-bits we need to insert a new extension so that it will be 64-bits.
5771 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5772 if (OrigTy.getSizeInBits() >= 64)
5775 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5776 EVT NewVT = getExtensionTo64Bits(OrigTy);
5778 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5781 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5782 /// does not do any sign/zero extension. If the original vector is less
5783 /// than 64 bits, an appropriate extension will be added after the load to
5784 /// reach a total size of 64 bits. We have to add the extension separately
5785 /// because ARM does not have a sign/zero extending load for vectors.
5786 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5787 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5789 // The load already has the right type.
5790 if (ExtendedTy == LD->getMemoryVT())
5791 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5792 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5793 LD->isNonTemporal(), LD->isInvariant(),
5794 LD->getAlignment());
5796 // We need to create a zextload/sextload. We cannot just create a load
5797 // followed by a zext/zext node because LowerMUL is also run during normal
5798 // operation legalization where we can't create illegal types.
5799 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5800 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5801 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5802 LD->isNonTemporal(), LD->getAlignment());
5805 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5806 /// extending load, or BUILD_VECTOR with extended elements, return the
5807 /// unextended value. The unextended vector should be 64 bits so that it can
5808 /// be used as an operand to a VMULL instruction. If the original vector size
5809 /// before extension is less than 64 bits we add a an extension to resize
5810 /// the vector to 64 bits.
5811 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5812 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5813 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5814 N->getOperand(0)->getValueType(0),
5818 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5819 return SkipLoadExtensionForVMULL(LD, DAG);
5821 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5822 // have been legalized as a BITCAST from v4i32.
5823 if (N->getOpcode() == ISD::BITCAST) {
5824 SDNode *BVN = N->getOperand(0).getNode();
5825 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5826 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5827 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5828 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5829 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5831 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5832 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5833 EVT VT = N->getValueType(0);
5834 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5835 unsigned NumElts = VT.getVectorNumElements();
5836 MVT TruncVT = MVT::getIntegerVT(EltSize);
5837 SmallVector<SDValue, 8> Ops;
5838 for (unsigned i = 0; i != NumElts; ++i) {
5839 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5840 const APInt &CInt = C->getAPIntValue();
5841 // Element types smaller than 32 bits are not legal, so use i32 elements.
5842 // The values are implicitly truncated so sext vs. zext doesn't matter.
5843 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5845 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5846 MVT::getVectorVT(TruncVT, NumElts), Ops);
5849 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5850 unsigned Opcode = N->getOpcode();
5851 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5852 SDNode *N0 = N->getOperand(0).getNode();
5853 SDNode *N1 = N->getOperand(1).getNode();
5854 return N0->hasOneUse() && N1->hasOneUse() &&
5855 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5860 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5861 unsigned Opcode = N->getOpcode();
5862 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5863 SDNode *N0 = N->getOperand(0).getNode();
5864 SDNode *N1 = N->getOperand(1).getNode();
5865 return N0->hasOneUse() && N1->hasOneUse() &&
5866 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5871 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5872 // Multiplications are only custom-lowered for 128-bit vectors so that
5873 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5874 EVT VT = Op.getValueType();
5875 assert(VT.is128BitVector() && VT.isInteger() &&
5876 "unexpected type for custom-lowering ISD::MUL");
5877 SDNode *N0 = Op.getOperand(0).getNode();
5878 SDNode *N1 = Op.getOperand(1).getNode();
5879 unsigned NewOpc = 0;
5881 bool isN0SExt = isSignExtended(N0, DAG);
5882 bool isN1SExt = isSignExtended(N1, DAG);
5883 if (isN0SExt && isN1SExt)
5884 NewOpc = ARMISD::VMULLs;
5886 bool isN0ZExt = isZeroExtended(N0, DAG);
5887 bool isN1ZExt = isZeroExtended(N1, DAG);
5888 if (isN0ZExt && isN1ZExt)
5889 NewOpc = ARMISD::VMULLu;
5890 else if (isN1SExt || isN1ZExt) {
5891 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5892 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5893 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5894 NewOpc = ARMISD::VMULLs;
5896 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5897 NewOpc = ARMISD::VMULLu;
5899 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5901 NewOpc = ARMISD::VMULLu;
5907 if (VT == MVT::v2i64)
5908 // Fall through to expand this. It is not legal.
5911 // Other vector multiplications are legal.
5916 // Legalize to a VMULL instruction.
5919 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5921 Op0 = SkipExtensionForVMULL(N0, DAG);
5922 assert(Op0.getValueType().is64BitVector() &&
5923 Op1.getValueType().is64BitVector() &&
5924 "unexpected types for extended operands to VMULL");
5925 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5928 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5929 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5936 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5937 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5938 EVT Op1VT = Op1.getValueType();
5939 return DAG.getNode(N0->getOpcode(), DL, VT,
5940 DAG.getNode(NewOpc, DL, VT,
5941 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5942 DAG.getNode(NewOpc, DL, VT,
5943 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5947 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5949 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5950 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5951 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5952 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5953 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5954 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5955 // Get reciprocal estimate.
5956 // float4 recip = vrecpeq_f32(yf);
5957 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5958 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5959 // Because char has a smaller range than uchar, we can actually get away
5960 // without any newton steps. This requires that we use a weird bias
5961 // of 0xb000, however (again, this has been exhaustively tested).
5962 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5963 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5964 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5965 Y = DAG.getConstant(0xb000, MVT::i32);
5966 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5967 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5968 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5969 // Convert back to short.
5970 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5971 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5976 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5978 // Convert to float.
5979 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5980 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5981 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5982 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5983 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5984 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5986 // Use reciprocal estimate and one refinement step.
5987 // float4 recip = vrecpeq_f32(yf);
5988 // recip *= vrecpsq_f32(yf, recip);
5989 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5990 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5991 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5992 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5994 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5995 // Because short has a smaller range than ushort, we can actually get away
5996 // with only a single newton step. This requires that we use a weird bias
5997 // of 89, however (again, this has been exhaustively tested).
5998 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5999 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6000 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6001 N1 = DAG.getConstant(0x89, MVT::i32);
6002 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6003 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6004 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6005 // Convert back to integer and return.
6006 // return vmovn_s32(vcvt_s32_f32(result));
6007 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6008 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6012 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6013 EVT VT = Op.getValueType();
6014 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6015 "unexpected type for custom-lowering ISD::SDIV");
6018 SDValue N0 = Op.getOperand(0);
6019 SDValue N1 = Op.getOperand(1);
6022 if (VT == MVT::v8i8) {
6023 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6024 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6026 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6027 DAG.getIntPtrConstant(4));
6028 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6029 DAG.getIntPtrConstant(4));
6030 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6031 DAG.getIntPtrConstant(0));
6032 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6033 DAG.getIntPtrConstant(0));
6035 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6036 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6038 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6039 N0 = LowerCONCAT_VECTORS(N0, DAG);
6041 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6044 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6047 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6048 EVT VT = Op.getValueType();
6049 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6050 "unexpected type for custom-lowering ISD::UDIV");
6053 SDValue N0 = Op.getOperand(0);
6054 SDValue N1 = Op.getOperand(1);
6057 if (VT == MVT::v8i8) {
6058 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6059 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6061 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6062 DAG.getIntPtrConstant(4));
6063 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6064 DAG.getIntPtrConstant(4));
6065 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6066 DAG.getIntPtrConstant(0));
6067 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6068 DAG.getIntPtrConstant(0));
6070 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6071 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6073 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6074 N0 = LowerCONCAT_VECTORS(N0, DAG);
6076 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6077 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6082 // v4i16 sdiv ... Convert to float.
6083 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6084 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6085 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6086 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6087 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6088 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6090 // Use reciprocal estimate and two refinement steps.
6091 // float4 recip = vrecpeq_f32(yf);
6092 // recip *= vrecpsq_f32(yf, recip);
6093 // recip *= vrecpsq_f32(yf, recip);
6094 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6095 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6096 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6097 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6099 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6100 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6101 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6103 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6104 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6105 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6106 // and that it will never cause us to return an answer too large).
6107 // float4 result = as_float4(as_int4(xf*recip) + 2);
6108 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6109 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6110 N1 = DAG.getConstant(2, MVT::i32);
6111 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6112 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6113 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6114 // Convert back to integer and return.
6115 // return vmovn_u32(vcvt_s32_f32(result));
6116 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6117 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6121 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6122 EVT VT = Op.getNode()->getValueType(0);
6123 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6126 bool ExtraOp = false;
6127 switch (Op.getOpcode()) {
6128 default: llvm_unreachable("Invalid code");
6129 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6130 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6131 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6132 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6136 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6138 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6139 Op.getOperand(1), Op.getOperand(2));
6142 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6143 assert(Subtarget->isTargetDarwin());
6145 // For iOS, we want to call an alternative entry point: __sincos_stret,
6146 // return values are passed via sret.
6148 SDValue Arg = Op.getOperand(0);
6149 EVT ArgVT = Arg.getValueType();
6150 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6152 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6153 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6155 // Pair of floats / doubles used to pass the result.
6156 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6158 // Create stack object for sret.
6159 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6160 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6161 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6162 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6168 Entry.Ty = RetTy->getPointerTo();
6169 Entry.isSExt = false;
6170 Entry.isZExt = false;
6171 Entry.isSRet = true;
6172 Args.push_back(Entry);
6176 Entry.isSExt = false;
6177 Entry.isZExt = false;
6178 Args.push_back(Entry);
6180 const char *LibcallName = (ArgVT == MVT::f64)
6181 ? "__sincos_stret" : "__sincosf_stret";
6182 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6184 TargetLowering::CallLoweringInfo CLI(DAG);
6185 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6186 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6188 .setDiscardResult();
6190 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6192 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6193 MachinePointerInfo(), false, false, false, 0);
6195 // Address of cos field.
6196 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6197 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6198 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6199 MachinePointerInfo(), false, false, false, 0);
6201 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6202 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6203 LoadSin.getValue(0), LoadCos.getValue(0));
6206 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6207 // Monotonic load/store is legal for all targets
6208 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6211 // Acquire/Release load/store is not legal for targets without a
6212 // dmb or equivalent available.
6216 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6217 SmallVectorImpl<SDValue> &Results,
6219 const ARMSubtarget *Subtarget) {
6221 SDValue Cycles32, OutChain;
6223 if (Subtarget->hasPerfMon()) {
6224 // Under Power Management extensions, the cycle-count is:
6225 // mrc p15, #0, <Rt>, c9, c13, #0
6226 SDValue Ops[] = { N->getOperand(0), // Chain
6227 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6228 DAG.getConstant(15, MVT::i32),
6229 DAG.getConstant(0, MVT::i32),
6230 DAG.getConstant(9, MVT::i32),
6231 DAG.getConstant(13, MVT::i32),
6232 DAG.getConstant(0, MVT::i32)
6235 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6236 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6237 OutChain = Cycles32.getValue(1);
6239 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6240 // there are older ARM CPUs that have implementation-specific ways of
6241 // obtaining this information (FIXME!).
6242 Cycles32 = DAG.getConstant(0, MVT::i32);
6243 OutChain = DAG.getEntryNode();
6247 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6248 Cycles32, DAG.getConstant(0, MVT::i32));
6249 Results.push_back(Cycles64);
6250 Results.push_back(OutChain);
6253 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6254 switch (Op.getOpcode()) {
6255 default: llvm_unreachable("Don't know how to custom lower this!");
6256 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6257 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6258 case ISD::GlobalAddress:
6259 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6260 default: llvm_unreachable("unknown object format");
6262 return LowerGlobalAddressWindows(Op, DAG);
6264 return LowerGlobalAddressELF(Op, DAG);
6266 return LowerGlobalAddressDarwin(Op, DAG);
6268 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6269 case ISD::SELECT: return LowerSELECT(Op, DAG);
6270 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6271 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6272 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6273 case ISD::VASTART: return LowerVASTART(Op, DAG);
6274 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6275 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6276 case ISD::SINT_TO_FP:
6277 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6278 case ISD::FP_TO_SINT:
6279 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6280 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6281 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6282 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6283 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6284 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6285 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6286 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6288 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6291 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6292 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6293 case ISD::SRL_PARTS:
6294 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6295 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6296 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6297 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6298 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6299 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6300 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6301 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6302 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6303 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6304 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6305 case ISD::MUL: return LowerMUL(Op, DAG);
6306 case ISD::SDIV: return LowerSDIV(Op, DAG);
6307 case ISD::UDIV: return LowerUDIV(Op, DAG);
6311 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6316 return LowerXALUO(Op, DAG);
6317 case ISD::ATOMIC_LOAD:
6318 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6319 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6321 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6322 case ISD::DYNAMIC_STACKALLOC:
6323 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6324 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6325 llvm_unreachable("Don't know how to custom lower this!");
6329 /// ReplaceNodeResults - Replace the results of node with an illegal result
6330 /// type with new values built out of custom code.
6331 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6332 SmallVectorImpl<SDValue>&Results,
6333 SelectionDAG &DAG) const {
6335 switch (N->getOpcode()) {
6337 llvm_unreachable("Don't know how to custom expand this!");
6339 Res = ExpandBITCAST(N, DAG);
6343 Res = Expand64BitShift(N, DAG, Subtarget);
6345 case ISD::READCYCLECOUNTER:
6346 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6350 Results.push_back(Res);
6353 //===----------------------------------------------------------------------===//
6354 // ARM Scheduler Hooks
6355 //===----------------------------------------------------------------------===//
6357 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6358 /// registers the function context.
6359 void ARMTargetLowering::
6360 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6361 MachineBasicBlock *DispatchBB, int FI) const {
6362 const TargetInstrInfo *TII =
6363 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6364 DebugLoc dl = MI->getDebugLoc();
6365 MachineFunction *MF = MBB->getParent();
6366 MachineRegisterInfo *MRI = &MF->getRegInfo();
6367 MachineConstantPool *MCP = MF->getConstantPool();
6368 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6369 const Function *F = MF->getFunction();
6371 bool isThumb = Subtarget->isThumb();
6372 bool isThumb2 = Subtarget->isThumb2();
6374 unsigned PCLabelId = AFI->createPICLabelUId();
6375 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6376 ARMConstantPoolValue *CPV =
6377 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6378 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6380 const TargetRegisterClass *TRC = isThumb ?
6381 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6382 (const TargetRegisterClass*)&ARM::GPRRegClass;
6384 // Grab constant pool and fixed stack memory operands.
6385 MachineMemOperand *CPMMO =
6386 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6387 MachineMemOperand::MOLoad, 4, 4);
6389 MachineMemOperand *FIMMOSt =
6390 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6391 MachineMemOperand::MOStore, 4, 4);
6393 // Load the address of the dispatch MBB into the jump buffer.
6395 // Incoming value: jbuf
6396 // ldr.n r5, LCPI1_1
6399 // str r5, [$jbuf, #+4] ; &jbuf[1]
6400 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6401 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6402 .addConstantPoolIndex(CPI)
6403 .addMemOperand(CPMMO));
6404 // Set the low bit because of thumb mode.
6405 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6407 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6408 .addReg(NewVReg1, RegState::Kill)
6410 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6411 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6412 .addReg(NewVReg2, RegState::Kill)
6414 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6415 .addReg(NewVReg3, RegState::Kill)
6417 .addImm(36) // &jbuf[1] :: pc
6418 .addMemOperand(FIMMOSt));
6419 } else if (isThumb) {
6420 // Incoming value: jbuf
6421 // ldr.n r1, LCPI1_4
6425 // add r2, $jbuf, #+4 ; &jbuf[1]
6427 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6428 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6429 .addConstantPoolIndex(CPI)
6430 .addMemOperand(CPMMO));
6431 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6432 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6433 .addReg(NewVReg1, RegState::Kill)
6435 // Set the low bit because of thumb mode.
6436 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6437 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6438 .addReg(ARM::CPSR, RegState::Define)
6440 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6441 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6442 .addReg(ARM::CPSR, RegState::Define)
6443 .addReg(NewVReg2, RegState::Kill)
6444 .addReg(NewVReg3, RegState::Kill));
6445 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6446 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6448 .addImm(36)); // &jbuf[1] :: pc
6449 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6450 .addReg(NewVReg4, RegState::Kill)
6451 .addReg(NewVReg5, RegState::Kill)
6453 .addMemOperand(FIMMOSt));
6455 // Incoming value: jbuf
6458 // str r1, [$jbuf, #+4] ; &jbuf[1]
6459 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6460 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6461 .addConstantPoolIndex(CPI)
6463 .addMemOperand(CPMMO));
6464 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6465 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6466 .addReg(NewVReg1, RegState::Kill)
6467 .addImm(PCLabelId));
6468 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6469 .addReg(NewVReg2, RegState::Kill)
6471 .addImm(36) // &jbuf[1] :: pc
6472 .addMemOperand(FIMMOSt));
6476 MachineBasicBlock *ARMTargetLowering::
6477 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6478 const TargetInstrInfo *TII =
6479 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6480 DebugLoc dl = MI->getDebugLoc();
6481 MachineFunction *MF = MBB->getParent();
6482 MachineRegisterInfo *MRI = &MF->getRegInfo();
6483 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6484 MachineFrameInfo *MFI = MF->getFrameInfo();
6485 int FI = MFI->getFunctionContextIndex();
6487 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6488 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6489 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6491 // Get a mapping of the call site numbers to all of the landing pads they're
6493 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6494 unsigned MaxCSNum = 0;
6495 MachineModuleInfo &MMI = MF->getMMI();
6496 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6498 if (!BB->isLandingPad()) continue;
6500 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6502 for (MachineBasicBlock::iterator
6503 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6504 if (!II->isEHLabel()) continue;
6506 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6507 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6509 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6510 for (SmallVectorImpl<unsigned>::iterator
6511 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6512 CSI != CSE; ++CSI) {
6513 CallSiteNumToLPad[*CSI].push_back(BB);
6514 MaxCSNum = std::max(MaxCSNum, *CSI);
6520 // Get an ordered list of the machine basic blocks for the jump table.
6521 std::vector<MachineBasicBlock*> LPadList;
6522 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6523 LPadList.reserve(CallSiteNumToLPad.size());
6524 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6525 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6526 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6527 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6528 LPadList.push_back(*II);
6529 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6533 assert(!LPadList.empty() &&
6534 "No landing pad destinations for the dispatch jump table!");
6536 // Create the jump table and associated information.
6537 MachineJumpTableInfo *JTI =
6538 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6539 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6540 unsigned UId = AFI->createJumpTableUId();
6541 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6543 // Create the MBBs for the dispatch code.
6545 // Shove the dispatch's address into the return slot in the function context.
6546 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6547 DispatchBB->setIsLandingPad();
6549 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6550 unsigned trap_opcode;
6551 if (Subtarget->isThumb())
6552 trap_opcode = ARM::tTRAP;
6554 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6556 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6557 DispatchBB->addSuccessor(TrapBB);
6559 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6560 DispatchBB->addSuccessor(DispContBB);
6563 MF->insert(MF->end(), DispatchBB);
6564 MF->insert(MF->end(), DispContBB);
6565 MF->insert(MF->end(), TrapBB);
6567 // Insert code into the entry block that creates and registers the function
6569 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6571 MachineMemOperand *FIMMOLd =
6572 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6573 MachineMemOperand::MOLoad |
6574 MachineMemOperand::MOVolatile, 4, 4);
6576 MachineInstrBuilder MIB;
6577 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6579 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6580 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6582 // Add a register mask with no preserved registers. This results in all
6583 // registers being marked as clobbered.
6584 MIB.addRegMask(RI.getNoPreservedMask());
6586 unsigned NumLPads = LPadList.size();
6587 if (Subtarget->isThumb2()) {
6588 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6589 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6592 .addMemOperand(FIMMOLd));
6594 if (NumLPads < 256) {
6595 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6597 .addImm(LPadList.size()));
6599 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6600 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6601 .addImm(NumLPads & 0xFFFF));
6603 unsigned VReg2 = VReg1;
6604 if ((NumLPads & 0xFFFF0000) != 0) {
6605 VReg2 = MRI->createVirtualRegister(TRC);
6606 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6608 .addImm(NumLPads >> 16));
6611 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6616 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6621 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6622 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6623 .addJumpTableIndex(MJTI)
6626 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6629 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6630 .addReg(NewVReg3, RegState::Kill)
6632 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6634 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6635 .addReg(NewVReg4, RegState::Kill)
6637 .addJumpTableIndex(MJTI)
6639 } else if (Subtarget->isThumb()) {
6640 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6641 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6644 .addMemOperand(FIMMOLd));
6646 if (NumLPads < 256) {
6647 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6651 MachineConstantPool *ConstantPool = MF->getConstantPool();
6652 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6653 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6655 // MachineConstantPool wants an explicit alignment.
6656 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6658 Align = getDataLayout()->getTypeAllocSize(C->getType());
6659 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6661 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6662 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6663 .addReg(VReg1, RegState::Define)
6664 .addConstantPoolIndex(Idx));
6665 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6670 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6675 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6676 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6677 .addReg(ARM::CPSR, RegState::Define)
6681 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6682 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6683 .addJumpTableIndex(MJTI)
6686 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6687 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6688 .addReg(ARM::CPSR, RegState::Define)
6689 .addReg(NewVReg2, RegState::Kill)
6692 MachineMemOperand *JTMMOLd =
6693 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6694 MachineMemOperand::MOLoad, 4, 4);
6696 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6697 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6698 .addReg(NewVReg4, RegState::Kill)
6700 .addMemOperand(JTMMOLd));
6702 unsigned NewVReg6 = NewVReg5;
6703 if (RelocM == Reloc::PIC_) {
6704 NewVReg6 = MRI->createVirtualRegister(TRC);
6705 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6706 .addReg(ARM::CPSR, RegState::Define)
6707 .addReg(NewVReg5, RegState::Kill)
6711 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6712 .addReg(NewVReg6, RegState::Kill)
6713 .addJumpTableIndex(MJTI)
6716 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6717 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6720 .addMemOperand(FIMMOLd));
6722 if (NumLPads < 256) {
6723 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6726 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6727 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6728 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6729 .addImm(NumLPads & 0xFFFF));
6731 unsigned VReg2 = VReg1;
6732 if ((NumLPads & 0xFFFF0000) != 0) {
6733 VReg2 = MRI->createVirtualRegister(TRC);
6734 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6736 .addImm(NumLPads >> 16));
6739 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6743 MachineConstantPool *ConstantPool = MF->getConstantPool();
6744 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6745 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6747 // MachineConstantPool wants an explicit alignment.
6748 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6750 Align = getDataLayout()->getTypeAllocSize(C->getType());
6751 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6753 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6754 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6755 .addReg(VReg1, RegState::Define)
6756 .addConstantPoolIndex(Idx)
6758 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6760 .addReg(VReg1, RegState::Kill));
6763 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6768 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6770 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6772 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6773 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6774 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6775 .addJumpTableIndex(MJTI)
6778 MachineMemOperand *JTMMOLd =
6779 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6780 MachineMemOperand::MOLoad, 4, 4);
6781 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6783 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6784 .addReg(NewVReg3, RegState::Kill)
6787 .addMemOperand(JTMMOLd));
6789 if (RelocM == Reloc::PIC_) {
6790 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6791 .addReg(NewVReg5, RegState::Kill)
6793 .addJumpTableIndex(MJTI)
6796 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6797 .addReg(NewVReg5, RegState::Kill)
6798 .addJumpTableIndex(MJTI)
6803 // Add the jump table entries as successors to the MBB.
6804 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6805 for (std::vector<MachineBasicBlock*>::iterator
6806 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6807 MachineBasicBlock *CurMBB = *I;
6808 if (SeenMBBs.insert(CurMBB))
6809 DispContBB->addSuccessor(CurMBB);
6812 // N.B. the order the invoke BBs are processed in doesn't matter here.
6813 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6814 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6815 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6816 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6817 MachineBasicBlock *BB = *I;
6819 // Remove the landing pad successor from the invoke block and replace it
6820 // with the new dispatch block.
6821 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6823 while (!Successors.empty()) {
6824 MachineBasicBlock *SMBB = Successors.pop_back_val();
6825 if (SMBB->isLandingPad()) {
6826 BB->removeSuccessor(SMBB);
6827 MBBLPads.push_back(SMBB);
6831 BB->addSuccessor(DispatchBB);
6833 // Find the invoke call and mark all of the callee-saved registers as
6834 // 'implicit defined' so that they're spilled. This prevents code from
6835 // moving instructions to before the EH block, where they will never be
6837 for (MachineBasicBlock::reverse_iterator
6838 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6839 if (!II->isCall()) continue;
6841 DenseMap<unsigned, bool> DefRegs;
6842 for (MachineInstr::mop_iterator
6843 OI = II->operands_begin(), OE = II->operands_end();
6845 if (!OI->isReg()) continue;
6846 DefRegs[OI->getReg()] = true;
6849 MachineInstrBuilder MIB(*MF, &*II);
6851 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6852 unsigned Reg = SavedRegs[i];
6853 if (Subtarget->isThumb2() &&
6854 !ARM::tGPRRegClass.contains(Reg) &&
6855 !ARM::hGPRRegClass.contains(Reg))
6857 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6859 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6862 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6869 // Mark all former landing pads as non-landing pads. The dispatch is the only
6871 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6872 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6873 (*I)->setIsLandingPad(false);
6875 // The instruction is gone now.
6876 MI->eraseFromParent();
6882 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6883 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6884 E = MBB->succ_end(); I != E; ++I)
6887 llvm_unreachable("Expecting a BB with two successors!");
6890 /// Return the load opcode for a given load size. If load size >= 8,
6891 /// neon opcode will be returned.
6892 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6894 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6895 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6897 return LdSize == 4 ? ARM::tLDRi
6898 : LdSize == 2 ? ARM::tLDRHi
6899 : LdSize == 1 ? ARM::tLDRBi : 0;
6901 return LdSize == 4 ? ARM::t2LDR_POST
6902 : LdSize == 2 ? ARM::t2LDRH_POST
6903 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6904 return LdSize == 4 ? ARM::LDR_POST_IMM
6905 : LdSize == 2 ? ARM::LDRH_POST
6906 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6909 /// Return the store opcode for a given store size. If store size >= 8,
6910 /// neon opcode will be returned.
6911 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6913 return StSize == 16 ? ARM::VST1q32wb_fixed
6914 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6916 return StSize == 4 ? ARM::tSTRi
6917 : StSize == 2 ? ARM::tSTRHi
6918 : StSize == 1 ? ARM::tSTRBi : 0;
6920 return StSize == 4 ? ARM::t2STR_POST
6921 : StSize == 2 ? ARM::t2STRH_POST
6922 : StSize == 1 ? ARM::t2STRB_POST : 0;
6923 return StSize == 4 ? ARM::STR_POST_IMM
6924 : StSize == 2 ? ARM::STRH_POST
6925 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6928 /// Emit a post-increment load operation with given size. The instructions
6929 /// will be added to BB at Pos.
6930 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6931 const TargetInstrInfo *TII, DebugLoc dl,
6932 unsigned LdSize, unsigned Data, unsigned AddrIn,
6933 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6934 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6935 assert(LdOpc != 0 && "Should have a load opcode");
6937 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6938 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6940 } else if (IsThumb1) {
6941 // load + update AddrIn
6942 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6943 .addReg(AddrIn).addImm(0));
6944 MachineInstrBuilder MIB =
6945 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6946 MIB = AddDefaultT1CC(MIB);
6947 MIB.addReg(AddrIn).addImm(LdSize);
6948 AddDefaultPred(MIB);
6949 } else if (IsThumb2) {
6950 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6951 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6954 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6955 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6956 .addReg(0).addImm(LdSize));
6960 /// Emit a post-increment store operation with given size. The instructions
6961 /// will be added to BB at Pos.
6962 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6963 const TargetInstrInfo *TII, DebugLoc dl,
6964 unsigned StSize, unsigned Data, unsigned AddrIn,
6965 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6966 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6967 assert(StOpc != 0 && "Should have a store opcode");
6969 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6970 .addReg(AddrIn).addImm(0).addReg(Data));
6971 } else if (IsThumb1) {
6972 // store + update AddrIn
6973 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6974 .addReg(AddrIn).addImm(0));
6975 MachineInstrBuilder MIB =
6976 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6977 MIB = AddDefaultT1CC(MIB);
6978 MIB.addReg(AddrIn).addImm(StSize);
6979 AddDefaultPred(MIB);
6980 } else if (IsThumb2) {
6981 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6982 .addReg(Data).addReg(AddrIn).addImm(StSize));
6984 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6985 .addReg(Data).addReg(AddrIn).addReg(0)
6991 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6992 MachineBasicBlock *BB) const {
6993 // This pseudo instruction has 3 operands: dst, src, size
6994 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6995 // Otherwise, we will generate unrolled scalar copies.
6996 const TargetInstrInfo *TII =
6997 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6998 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6999 MachineFunction::iterator It = BB;
7002 unsigned dest = MI->getOperand(0).getReg();
7003 unsigned src = MI->getOperand(1).getReg();
7004 unsigned SizeVal = MI->getOperand(2).getImm();
7005 unsigned Align = MI->getOperand(3).getImm();
7006 DebugLoc dl = MI->getDebugLoc();
7008 MachineFunction *MF = BB->getParent();
7009 MachineRegisterInfo &MRI = MF->getRegInfo();
7010 unsigned UnitSize = 0;
7011 const TargetRegisterClass *TRC = nullptr;
7012 const TargetRegisterClass *VecTRC = nullptr;
7014 bool IsThumb1 = Subtarget->isThumb1Only();
7015 bool IsThumb2 = Subtarget->isThumb2();
7019 } else if (Align & 2) {
7022 // Check whether we can use NEON instructions.
7023 if (!MF->getFunction()->getAttributes().
7024 hasAttribute(AttributeSet::FunctionIndex,
7025 Attribute::NoImplicitFloat) &&
7026 Subtarget->hasNEON()) {
7027 if ((Align % 16 == 0) && SizeVal >= 16)
7029 else if ((Align % 8 == 0) && SizeVal >= 8)
7032 // Can't use NEON instructions.
7037 // Select the correct opcode and register class for unit size load/store
7038 bool IsNeon = UnitSize >= 8;
7039 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7040 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7042 VecTRC = UnitSize == 16
7043 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7045 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7048 unsigned BytesLeft = SizeVal % UnitSize;
7049 unsigned LoopSize = SizeVal - BytesLeft;
7051 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7052 // Use LDR and STR to copy.
7053 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7054 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7055 unsigned srcIn = src;
7056 unsigned destIn = dest;
7057 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7058 unsigned srcOut = MRI.createVirtualRegister(TRC);
7059 unsigned destOut = MRI.createVirtualRegister(TRC);
7060 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7061 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7062 IsThumb1, IsThumb2);
7063 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7064 IsThumb1, IsThumb2);
7069 // Handle the leftover bytes with LDRB and STRB.
7070 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7071 // [destOut] = STRB_POST(scratch, destIn, 1)
7072 for (unsigned i = 0; i < BytesLeft; i++) {
7073 unsigned srcOut = MRI.createVirtualRegister(TRC);
7074 unsigned destOut = MRI.createVirtualRegister(TRC);
7075 unsigned scratch = MRI.createVirtualRegister(TRC);
7076 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7077 IsThumb1, IsThumb2);
7078 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7079 IsThumb1, IsThumb2);
7083 MI->eraseFromParent(); // The instruction is gone now.
7087 // Expand the pseudo op to a loop.
7090 // movw varEnd, # --> with thumb2
7092 // ldrcp varEnd, idx --> without thumb2
7093 // fallthrough --> loopMBB
7095 // PHI varPhi, varEnd, varLoop
7096 // PHI srcPhi, src, srcLoop
7097 // PHI destPhi, dst, destLoop
7098 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7099 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7100 // subs varLoop, varPhi, #UnitSize
7102 // fallthrough --> exitMBB
7104 // epilogue to handle left-over bytes
7105 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7106 // [destOut] = STRB_POST(scratch, destLoop, 1)
7107 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7108 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7109 MF->insert(It, loopMBB);
7110 MF->insert(It, exitMBB);
7112 // Transfer the remainder of BB and its successor edges to exitMBB.
7113 exitMBB->splice(exitMBB->begin(), BB,
7114 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7115 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7117 // Load an immediate to varEnd.
7118 unsigned varEnd = MRI.createVirtualRegister(TRC);
7120 unsigned Vtmp = varEnd;
7121 if ((LoopSize & 0xFFFF0000) != 0)
7122 Vtmp = MRI.createVirtualRegister(TRC);
7123 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7124 .addImm(LoopSize & 0xFFFF));
7126 if ((LoopSize & 0xFFFF0000) != 0)
7127 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7128 .addReg(Vtmp).addImm(LoopSize >> 16));
7130 MachineConstantPool *ConstantPool = MF->getConstantPool();
7131 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7132 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7134 // MachineConstantPool wants an explicit alignment.
7135 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7137 Align = getDataLayout()->getTypeAllocSize(C->getType());
7138 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7141 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7142 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7144 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7145 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7147 BB->addSuccessor(loopMBB);
7149 // Generate the loop body:
7150 // varPhi = PHI(varLoop, varEnd)
7151 // srcPhi = PHI(srcLoop, src)
7152 // destPhi = PHI(destLoop, dst)
7153 MachineBasicBlock *entryBB = BB;
7155 unsigned varLoop = MRI.createVirtualRegister(TRC);
7156 unsigned varPhi = MRI.createVirtualRegister(TRC);
7157 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7158 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7159 unsigned destLoop = MRI.createVirtualRegister(TRC);
7160 unsigned destPhi = MRI.createVirtualRegister(TRC);
7162 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7163 .addReg(varLoop).addMBB(loopMBB)
7164 .addReg(varEnd).addMBB(entryBB);
7165 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7166 .addReg(srcLoop).addMBB(loopMBB)
7167 .addReg(src).addMBB(entryBB);
7168 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7169 .addReg(destLoop).addMBB(loopMBB)
7170 .addReg(dest).addMBB(entryBB);
7172 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7173 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7174 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7175 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7176 IsThumb1, IsThumb2);
7177 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7178 IsThumb1, IsThumb2);
7180 // Decrement loop variable by UnitSize.
7182 MachineInstrBuilder MIB =
7183 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7184 MIB = AddDefaultT1CC(MIB);
7185 MIB.addReg(varPhi).addImm(UnitSize);
7186 AddDefaultPred(MIB);
7188 MachineInstrBuilder MIB =
7189 BuildMI(*BB, BB->end(), dl,
7190 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7191 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7192 MIB->getOperand(5).setReg(ARM::CPSR);
7193 MIB->getOperand(5).setIsDef(true);
7195 BuildMI(*BB, BB->end(), dl,
7196 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7197 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7199 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7200 BB->addSuccessor(loopMBB);
7201 BB->addSuccessor(exitMBB);
7203 // Add epilogue to handle BytesLeft.
7205 MachineInstr *StartOfExit = exitMBB->begin();
7207 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7208 // [destOut] = STRB_POST(scratch, destLoop, 1)
7209 unsigned srcIn = srcLoop;
7210 unsigned destIn = destLoop;
7211 for (unsigned i = 0; i < BytesLeft; i++) {
7212 unsigned srcOut = MRI.createVirtualRegister(TRC);
7213 unsigned destOut = MRI.createVirtualRegister(TRC);
7214 unsigned scratch = MRI.createVirtualRegister(TRC);
7215 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7216 IsThumb1, IsThumb2);
7217 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7218 IsThumb1, IsThumb2);
7223 MI->eraseFromParent(); // The instruction is gone now.
7228 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7229 MachineBasicBlock *MBB) const {
7230 const TargetMachine &TM = getTargetMachine();
7231 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7232 DebugLoc DL = MI->getDebugLoc();
7234 assert(Subtarget->isTargetWindows() &&
7235 "__chkstk is only supported on Windows");
7236 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7238 // __chkstk takes the number of words to allocate on the stack in R4, and
7239 // returns the stack adjustment in number of bytes in R4. This will not
7240 // clober any other registers (other than the obvious lr).
7242 // Although, technically, IP should be considered a register which may be
7243 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7244 // thumb-2 environment, so there is no interworking required. As a result, we
7245 // do not expect a veneer to be emitted by the linker, clobbering IP.
7247 // Each module receives its own copy of __chkstk, so no import thunk is
7248 // required, again, ensuring that IP is not clobbered.
7250 // Finally, although some linkers may theoretically provide a trampoline for
7251 // out of range calls (which is quite common due to a 32M range limitation of
7252 // branches for Thumb), we can generate the long-call version via
7253 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7256 switch (TM.getCodeModel()) {
7257 case CodeModel::Small:
7258 case CodeModel::Medium:
7259 case CodeModel::Default:
7260 case CodeModel::Kernel:
7261 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7262 .addImm((unsigned)ARMCC::AL).addReg(0)
7263 .addExternalSymbol("__chkstk")
7264 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7265 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7266 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7268 case CodeModel::Large:
7269 case CodeModel::JITDefault: {
7270 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7271 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7273 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7274 .addExternalSymbol("__chkstk");
7275 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7276 .addImm((unsigned)ARMCC::AL).addReg(0)
7277 .addReg(Reg, RegState::Kill)
7278 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7279 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7280 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7285 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7287 .addReg(ARM::SP).addReg(ARM::R4)));
7289 MI->eraseFromParent();
7294 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7295 MachineBasicBlock *BB) const {
7296 const TargetInstrInfo *TII =
7297 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7298 DebugLoc dl = MI->getDebugLoc();
7299 bool isThumb2 = Subtarget->isThumb2();
7300 switch (MI->getOpcode()) {
7303 llvm_unreachable("Unexpected instr type to insert");
7305 // The Thumb2 pre-indexed stores have the same MI operands, they just
7306 // define them differently in the .td files from the isel patterns, so
7307 // they need pseudos.
7308 case ARM::t2STR_preidx:
7309 MI->setDesc(TII->get(ARM::t2STR_PRE));
7311 case ARM::t2STRB_preidx:
7312 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7314 case ARM::t2STRH_preidx:
7315 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7318 case ARM::STRi_preidx:
7319 case ARM::STRBi_preidx: {
7320 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7321 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7322 // Decode the offset.
7323 unsigned Offset = MI->getOperand(4).getImm();
7324 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7325 Offset = ARM_AM::getAM2Offset(Offset);
7329 MachineMemOperand *MMO = *MI->memoperands_begin();
7330 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7331 .addOperand(MI->getOperand(0)) // Rn_wb
7332 .addOperand(MI->getOperand(1)) // Rt
7333 .addOperand(MI->getOperand(2)) // Rn
7334 .addImm(Offset) // offset (skip GPR==zero_reg)
7335 .addOperand(MI->getOperand(5)) // pred
7336 .addOperand(MI->getOperand(6))
7337 .addMemOperand(MMO);
7338 MI->eraseFromParent();
7341 case ARM::STRr_preidx:
7342 case ARM::STRBr_preidx:
7343 case ARM::STRH_preidx: {
7345 switch (MI->getOpcode()) {
7346 default: llvm_unreachable("unexpected opcode!");
7347 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7348 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7349 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7351 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7352 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7353 MIB.addOperand(MI->getOperand(i));
7354 MI->eraseFromParent();
7358 case ARM::tMOVCCr_pseudo: {
7359 // To "insert" a SELECT_CC instruction, we actually have to insert the
7360 // diamond control-flow pattern. The incoming instruction knows the
7361 // destination vreg to set, the condition code register to branch on, the
7362 // true/false values to select between, and a branch opcode to use.
7363 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7364 MachineFunction::iterator It = BB;
7370 // cmpTY ccX, r1, r2
7372 // fallthrough --> copy0MBB
7373 MachineBasicBlock *thisMBB = BB;
7374 MachineFunction *F = BB->getParent();
7375 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7376 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7377 F->insert(It, copy0MBB);
7378 F->insert(It, sinkMBB);
7380 // Transfer the remainder of BB and its successor edges to sinkMBB.
7381 sinkMBB->splice(sinkMBB->begin(), BB,
7382 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7383 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7385 BB->addSuccessor(copy0MBB);
7386 BB->addSuccessor(sinkMBB);
7388 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7389 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7392 // %FalseValue = ...
7393 // # fallthrough to sinkMBB
7396 // Update machine-CFG edges
7397 BB->addSuccessor(sinkMBB);
7400 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7403 BuildMI(*BB, BB->begin(), dl,
7404 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7405 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7406 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7408 MI->eraseFromParent(); // The pseudo instruction is gone now.
7413 case ARM::BCCZi64: {
7414 // If there is an unconditional branch to the other successor, remove it.
7415 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7417 // Compare both parts that make up the double comparison separately for
7419 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7421 unsigned LHS1 = MI->getOperand(1).getReg();
7422 unsigned LHS2 = MI->getOperand(2).getReg();
7424 AddDefaultPred(BuildMI(BB, dl,
7425 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7426 .addReg(LHS1).addImm(0));
7427 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7428 .addReg(LHS2).addImm(0)
7429 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7431 unsigned RHS1 = MI->getOperand(3).getReg();
7432 unsigned RHS2 = MI->getOperand(4).getReg();
7433 AddDefaultPred(BuildMI(BB, dl,
7434 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7435 .addReg(LHS1).addReg(RHS1));
7436 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7437 .addReg(LHS2).addReg(RHS2)
7438 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7441 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7442 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7443 if (MI->getOperand(0).getImm() == ARMCC::NE)
7444 std::swap(destMBB, exitMBB);
7446 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7447 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7449 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7451 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7453 MI->eraseFromParent(); // The pseudo instruction is gone now.
7457 case ARM::Int_eh_sjlj_setjmp:
7458 case ARM::Int_eh_sjlj_setjmp_nofp:
7459 case ARM::tInt_eh_sjlj_setjmp:
7460 case ARM::t2Int_eh_sjlj_setjmp:
7461 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7462 EmitSjLjDispatchBlock(MI, BB);
7467 // To insert an ABS instruction, we have to insert the
7468 // diamond control-flow pattern. The incoming instruction knows the
7469 // source vreg to test against 0, the destination vreg to set,
7470 // the condition code register to branch on, the
7471 // true/false values to select between, and a branch opcode to use.
7476 // BCC (branch to SinkBB if V0 >= 0)
7477 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7478 // SinkBB: V1 = PHI(V2, V3)
7479 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7480 MachineFunction::iterator BBI = BB;
7482 MachineFunction *Fn = BB->getParent();
7483 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7484 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7485 Fn->insert(BBI, RSBBB);
7486 Fn->insert(BBI, SinkBB);
7488 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7489 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7490 bool isThumb2 = Subtarget->isThumb2();
7491 MachineRegisterInfo &MRI = Fn->getRegInfo();
7492 // In Thumb mode S must not be specified if source register is the SP or
7493 // PC and if destination register is the SP, so restrict register class
7494 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7495 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7496 (const TargetRegisterClass*)&ARM::GPRRegClass);
7498 // Transfer the remainder of BB and its successor edges to sinkMBB.
7499 SinkBB->splice(SinkBB->begin(), BB,
7500 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7501 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7503 BB->addSuccessor(RSBBB);
7504 BB->addSuccessor(SinkBB);
7506 // fall through to SinkMBB
7507 RSBBB->addSuccessor(SinkBB);
7509 // insert a cmp at the end of BB
7510 AddDefaultPred(BuildMI(BB, dl,
7511 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7512 .addReg(ABSSrcReg).addImm(0));
7514 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7516 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7517 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7519 // insert rsbri in RSBBB
7520 // Note: BCC and rsbri will be converted into predicated rsbmi
7521 // by if-conversion pass
7522 BuildMI(*RSBBB, RSBBB->begin(), dl,
7523 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7524 .addReg(ABSSrcReg, RegState::Kill)
7525 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7527 // insert PHI in SinkBB,
7528 // reuse ABSDstReg to not change uses of ABS instruction
7529 BuildMI(*SinkBB, SinkBB->begin(), dl,
7530 TII->get(ARM::PHI), ABSDstReg)
7531 .addReg(NewRsbDstReg).addMBB(RSBBB)
7532 .addReg(ABSSrcReg).addMBB(BB);
7534 // remove ABS instruction
7535 MI->eraseFromParent();
7537 // return last added BB
7540 case ARM::COPY_STRUCT_BYVAL_I32:
7542 return EmitStructByval(MI, BB);
7543 case ARM::WIN__CHKSTK:
7544 return EmitLowered__chkstk(MI, BB);
7548 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7549 SDNode *Node) const {
7550 if (!MI->hasPostISelHook()) {
7551 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7552 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7556 const MCInstrDesc *MCID = &MI->getDesc();
7557 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7558 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7559 // operand is still set to noreg. If needed, set the optional operand's
7560 // register to CPSR, and remove the redundant implicit def.
7562 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7564 // Rename pseudo opcodes.
7565 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7567 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7568 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7569 MCID = &TII->get(NewOpc);
7571 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7572 "converted opcode should be the same except for cc_out");
7576 // Add the optional cc_out operand
7577 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7579 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7581 // Any ARM instruction that sets the 's' bit should specify an optional
7582 // "cc_out" operand in the last operand position.
7583 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7584 assert(!NewOpc && "Optional cc_out operand required");
7587 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7588 // since we already have an optional CPSR def.
7589 bool definesCPSR = false;
7590 bool deadCPSR = false;
7591 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7593 const MachineOperand &MO = MI->getOperand(i);
7594 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7598 MI->RemoveOperand(i);
7603 assert(!NewOpc && "Optional cc_out operand required");
7606 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7608 assert(!MI->getOperand(ccOutIdx).getReg() &&
7609 "expect uninitialized optional cc_out operand");
7613 // If this instruction was defined with an optional CPSR def and its dag node
7614 // had a live implicit CPSR def, then activate the optional CPSR def.
7615 MachineOperand &MO = MI->getOperand(ccOutIdx);
7616 MO.setReg(ARM::CPSR);
7620 //===----------------------------------------------------------------------===//
7621 // ARM Optimization Hooks
7622 //===----------------------------------------------------------------------===//
7624 // Helper function that checks if N is a null or all ones constant.
7625 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7626 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7629 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7632 // Return true if N is conditionally 0 or all ones.
7633 // Detects these expressions where cc is an i1 value:
7635 // (select cc 0, y) [AllOnes=0]
7636 // (select cc y, 0) [AllOnes=0]
7637 // (zext cc) [AllOnes=0]
7638 // (sext cc) [AllOnes=0/1]
7639 // (select cc -1, y) [AllOnes=1]
7640 // (select cc y, -1) [AllOnes=1]
7642 // Invert is set when N is the null/all ones constant when CC is false.
7643 // OtherOp is set to the alternative value of N.
7644 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7645 SDValue &CC, bool &Invert,
7647 SelectionDAG &DAG) {
7648 switch (N->getOpcode()) {
7649 default: return false;
7651 CC = N->getOperand(0);
7652 SDValue N1 = N->getOperand(1);
7653 SDValue N2 = N->getOperand(2);
7654 if (isZeroOrAllOnes(N1, AllOnes)) {
7659 if (isZeroOrAllOnes(N2, AllOnes)) {
7666 case ISD::ZERO_EXTEND:
7667 // (zext cc) can never be the all ones value.
7671 case ISD::SIGN_EXTEND: {
7672 EVT VT = N->getValueType(0);
7673 CC = N->getOperand(0);
7674 if (CC.getValueType() != MVT::i1)
7678 // When looking for an AllOnes constant, N is an sext, and the 'other'
7680 OtherOp = DAG.getConstant(0, VT);
7681 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7682 // When looking for a 0 constant, N can be zext or sext.
7683 OtherOp = DAG.getConstant(1, VT);
7685 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7691 // Combine a constant select operand into its use:
7693 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7694 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7695 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7696 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7697 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7699 // The transform is rejected if the select doesn't have a constant operand that
7700 // is null, or all ones when AllOnes is set.
7702 // Also recognize sext/zext from i1:
7704 // (add (zext cc), x) -> (select cc (add x, 1), x)
7705 // (add (sext cc), x) -> (select cc (add x, -1), x)
7707 // These transformations eventually create predicated instructions.
7709 // @param N The node to transform.
7710 // @param Slct The N operand that is a select.
7711 // @param OtherOp The other N operand (x above).
7712 // @param DCI Context.
7713 // @param AllOnes Require the select constant to be all ones instead of null.
7714 // @returns The new node, or SDValue() on failure.
7716 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7717 TargetLowering::DAGCombinerInfo &DCI,
7718 bool AllOnes = false) {
7719 SelectionDAG &DAG = DCI.DAG;
7720 EVT VT = N->getValueType(0);
7721 SDValue NonConstantVal;
7724 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7725 NonConstantVal, DAG))
7728 // Slct is now know to be the desired identity constant when CC is true.
7729 SDValue TrueVal = OtherOp;
7730 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7731 OtherOp, NonConstantVal);
7732 // Unless SwapSelectOps says CC should be false.
7734 std::swap(TrueVal, FalseVal);
7736 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7737 CCOp, TrueVal, FalseVal);
7740 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7742 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7743 TargetLowering::DAGCombinerInfo &DCI) {
7744 SDValue N0 = N->getOperand(0);
7745 SDValue N1 = N->getOperand(1);
7746 if (N0.getNode()->hasOneUse()) {
7747 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7748 if (Result.getNode())
7751 if (N1.getNode()->hasOneUse()) {
7752 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7753 if (Result.getNode())
7759 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7760 // (only after legalization).
7761 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7762 TargetLowering::DAGCombinerInfo &DCI,
7763 const ARMSubtarget *Subtarget) {
7765 // Only perform optimization if after legalize, and if NEON is available. We
7766 // also expected both operands to be BUILD_VECTORs.
7767 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7768 || N0.getOpcode() != ISD::BUILD_VECTOR
7769 || N1.getOpcode() != ISD::BUILD_VECTOR)
7772 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7773 EVT VT = N->getValueType(0);
7774 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7777 // Check that the vector operands are of the right form.
7778 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7779 // operands, where N is the size of the formed vector.
7780 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7781 // index such that we have a pair wise add pattern.
7783 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7784 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7786 SDValue Vec = N0->getOperand(0)->getOperand(0);
7787 SDNode *V = Vec.getNode();
7788 unsigned nextIndex = 0;
7790 // For each operands to the ADD which are BUILD_VECTORs,
7791 // check to see if each of their operands are an EXTRACT_VECTOR with
7792 // the same vector and appropriate index.
7793 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7794 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7795 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7797 SDValue ExtVec0 = N0->getOperand(i);
7798 SDValue ExtVec1 = N1->getOperand(i);
7800 // First operand is the vector, verify its the same.
7801 if (V != ExtVec0->getOperand(0).getNode() ||
7802 V != ExtVec1->getOperand(0).getNode())
7805 // Second is the constant, verify its correct.
7806 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7807 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7809 // For the constant, we want to see all the even or all the odd.
7810 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7811 || C1->getZExtValue() != nextIndex+1)
7820 // Create VPADDL node.
7821 SelectionDAG &DAG = DCI.DAG;
7822 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7824 // Build operand list.
7825 SmallVector<SDValue, 8> Ops;
7826 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7827 TLI.getPointerTy()));
7829 // Input is the vector.
7832 // Get widened type and narrowed type.
7834 unsigned numElem = VT.getVectorNumElements();
7836 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7837 switch (inputLaneType.getSimpleVT().SimpleTy) {
7838 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7839 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7840 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7842 llvm_unreachable("Invalid vector element type for padd optimization.");
7845 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7846 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7847 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7850 static SDValue findMUL_LOHI(SDValue V) {
7851 if (V->getOpcode() == ISD::UMUL_LOHI ||
7852 V->getOpcode() == ISD::SMUL_LOHI)
7857 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7858 TargetLowering::DAGCombinerInfo &DCI,
7859 const ARMSubtarget *Subtarget) {
7861 if (Subtarget->isThumb1Only()) return SDValue();
7863 // Only perform the checks after legalize when the pattern is available.
7864 if (DCI.isBeforeLegalize()) return SDValue();
7866 // Look for multiply add opportunities.
7867 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7868 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7869 // a glue link from the first add to the second add.
7870 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7871 // a S/UMLAL instruction.
7874 // \ / \ [no multiline comment]
7880 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7881 SDValue AddcOp0 = AddcNode->getOperand(0);
7882 SDValue AddcOp1 = AddcNode->getOperand(1);
7884 // Check if the two operands are from the same mul_lohi node.
7885 if (AddcOp0.getNode() == AddcOp1.getNode())
7888 assert(AddcNode->getNumValues() == 2 &&
7889 AddcNode->getValueType(0) == MVT::i32 &&
7890 "Expect ADDC with two result values. First: i32");
7892 // Check that we have a glued ADDC node.
7893 if (AddcNode->getValueType(1) != MVT::Glue)
7896 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7897 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7898 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7899 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7900 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7903 // Look for the glued ADDE.
7904 SDNode* AddeNode = AddcNode->getGluedUser();
7908 // Make sure it is really an ADDE.
7909 if (AddeNode->getOpcode() != ISD::ADDE)
7912 assert(AddeNode->getNumOperands() == 3 &&
7913 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7914 "ADDE node has the wrong inputs");
7916 // Check for the triangle shape.
7917 SDValue AddeOp0 = AddeNode->getOperand(0);
7918 SDValue AddeOp1 = AddeNode->getOperand(1);
7920 // Make sure that the ADDE operands are not coming from the same node.
7921 if (AddeOp0.getNode() == AddeOp1.getNode())
7924 // Find the MUL_LOHI node walking up ADDE's operands.
7925 bool IsLeftOperandMUL = false;
7926 SDValue MULOp = findMUL_LOHI(AddeOp0);
7927 if (MULOp == SDValue())
7928 MULOp = findMUL_LOHI(AddeOp1);
7930 IsLeftOperandMUL = true;
7931 if (MULOp == SDValue())
7934 // Figure out the right opcode.
7935 unsigned Opc = MULOp->getOpcode();
7936 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7938 // Figure out the high and low input values to the MLAL node.
7939 SDValue* HiMul = &MULOp;
7940 SDValue* HiAdd = nullptr;
7941 SDValue* LoMul = nullptr;
7942 SDValue* LowAdd = nullptr;
7944 if (IsLeftOperandMUL)
7950 if (AddcOp0->getOpcode() == Opc) {
7954 if (AddcOp1->getOpcode() == Opc) {
7962 if (LoMul->getNode() != HiMul->getNode())
7965 // Create the merged node.
7966 SelectionDAG &DAG = DCI.DAG;
7968 // Build operand list.
7969 SmallVector<SDValue, 8> Ops;
7970 Ops.push_back(LoMul->getOperand(0));
7971 Ops.push_back(LoMul->getOperand(1));
7972 Ops.push_back(*LowAdd);
7973 Ops.push_back(*HiAdd);
7975 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7976 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7978 // Replace the ADDs' nodes uses by the MLA node's values.
7979 SDValue HiMLALResult(MLALNode.getNode(), 1);
7980 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7982 SDValue LoMLALResult(MLALNode.getNode(), 0);
7983 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7985 // Return original node to notify the driver to stop replacing.
7986 SDValue resNode(AddcNode, 0);
7990 /// PerformADDCCombine - Target-specific dag combine transform from
7991 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7992 static SDValue PerformADDCCombine(SDNode *N,
7993 TargetLowering::DAGCombinerInfo &DCI,
7994 const ARMSubtarget *Subtarget) {
7996 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8000 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8001 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8002 /// called with the default operands, and if that fails, with commuted
8004 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8005 TargetLowering::DAGCombinerInfo &DCI,
8006 const ARMSubtarget *Subtarget){
8008 // Attempt to create vpaddl for this add.
8009 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8010 if (Result.getNode())
8013 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8014 if (N0.getNode()->hasOneUse()) {
8015 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8016 if (Result.getNode()) return Result;
8021 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8023 static SDValue PerformADDCombine(SDNode *N,
8024 TargetLowering::DAGCombinerInfo &DCI,
8025 const ARMSubtarget *Subtarget) {
8026 SDValue N0 = N->getOperand(0);
8027 SDValue N1 = N->getOperand(1);
8029 // First try with the default operand order.
8030 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8031 if (Result.getNode())
8034 // If that didn't work, try again with the operands commuted.
8035 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8038 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8040 static SDValue PerformSUBCombine(SDNode *N,
8041 TargetLowering::DAGCombinerInfo &DCI) {
8042 SDValue N0 = N->getOperand(0);
8043 SDValue N1 = N->getOperand(1);
8045 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8046 if (N1.getNode()->hasOneUse()) {
8047 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8048 if (Result.getNode()) return Result;
8054 /// PerformVMULCombine
8055 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8056 /// special multiplier accumulator forwarding.
8062 // However, for (A + B) * (A + B),
8069 static SDValue PerformVMULCombine(SDNode *N,
8070 TargetLowering::DAGCombinerInfo &DCI,
8071 const ARMSubtarget *Subtarget) {
8072 if (!Subtarget->hasVMLxForwarding())
8075 SelectionDAG &DAG = DCI.DAG;
8076 SDValue N0 = N->getOperand(0);
8077 SDValue N1 = N->getOperand(1);
8078 unsigned Opcode = N0.getOpcode();
8079 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8080 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8081 Opcode = N1.getOpcode();
8082 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8083 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8091 EVT VT = N->getValueType(0);
8093 SDValue N00 = N0->getOperand(0);
8094 SDValue N01 = N0->getOperand(1);
8095 return DAG.getNode(Opcode, DL, VT,
8096 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8097 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8100 static SDValue PerformMULCombine(SDNode *N,
8101 TargetLowering::DAGCombinerInfo &DCI,
8102 const ARMSubtarget *Subtarget) {
8103 SelectionDAG &DAG = DCI.DAG;
8105 if (Subtarget->isThumb1Only())
8108 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8111 EVT VT = N->getValueType(0);
8112 if (VT.is64BitVector() || VT.is128BitVector())
8113 return PerformVMULCombine(N, DCI, Subtarget);
8117 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8121 int64_t MulAmt = C->getSExtValue();
8122 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8124 ShiftAmt = ShiftAmt & (32 - 1);
8125 SDValue V = N->getOperand(0);
8129 MulAmt >>= ShiftAmt;
8132 if (isPowerOf2_32(MulAmt - 1)) {
8133 // (mul x, 2^N + 1) => (add (shl x, N), x)
8134 Res = DAG.getNode(ISD::ADD, DL, VT,
8136 DAG.getNode(ISD::SHL, DL, VT,
8138 DAG.getConstant(Log2_32(MulAmt - 1),
8140 } else if (isPowerOf2_32(MulAmt + 1)) {
8141 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8142 Res = DAG.getNode(ISD::SUB, DL, VT,
8143 DAG.getNode(ISD::SHL, DL, VT,
8145 DAG.getConstant(Log2_32(MulAmt + 1),
8151 uint64_t MulAmtAbs = -MulAmt;
8152 if (isPowerOf2_32(MulAmtAbs + 1)) {
8153 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8154 Res = DAG.getNode(ISD::SUB, DL, VT,
8156 DAG.getNode(ISD::SHL, DL, VT,
8158 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8160 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8161 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8162 Res = DAG.getNode(ISD::ADD, DL, VT,
8164 DAG.getNode(ISD::SHL, DL, VT,
8166 DAG.getConstant(Log2_32(MulAmtAbs-1),
8168 Res = DAG.getNode(ISD::SUB, DL, VT,
8169 DAG.getConstant(0, MVT::i32),Res);
8176 Res = DAG.getNode(ISD::SHL, DL, VT,
8177 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8179 // Do not add new nodes to DAG combiner worklist.
8180 DCI.CombineTo(N, Res, false);
8184 static SDValue PerformANDCombine(SDNode *N,
8185 TargetLowering::DAGCombinerInfo &DCI,
8186 const ARMSubtarget *Subtarget) {
8188 // Attempt to use immediate-form VBIC
8189 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8191 EVT VT = N->getValueType(0);
8192 SelectionDAG &DAG = DCI.DAG;
8194 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8197 APInt SplatBits, SplatUndef;
8198 unsigned SplatBitSize;
8201 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8202 if (SplatBitSize <= 64) {
8204 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8205 SplatUndef.getZExtValue(), SplatBitSize,
8206 DAG, VbicVT, VT.is128BitVector(),
8208 if (Val.getNode()) {
8210 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8211 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8212 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8217 if (!Subtarget->isThumb1Only()) {
8218 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8219 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8220 if (Result.getNode())
8227 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8228 static SDValue PerformORCombine(SDNode *N,
8229 TargetLowering::DAGCombinerInfo &DCI,
8230 const ARMSubtarget *Subtarget) {
8231 // Attempt to use immediate-form VORR
8232 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8234 EVT VT = N->getValueType(0);
8235 SelectionDAG &DAG = DCI.DAG;
8237 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8240 APInt SplatBits, SplatUndef;
8241 unsigned SplatBitSize;
8243 if (BVN && Subtarget->hasNEON() &&
8244 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8245 if (SplatBitSize <= 64) {
8247 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8248 SplatUndef.getZExtValue(), SplatBitSize,
8249 DAG, VorrVT, VT.is128BitVector(),
8251 if (Val.getNode()) {
8253 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8254 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8255 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8260 if (!Subtarget->isThumb1Only()) {
8261 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8262 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8263 if (Result.getNode())
8267 // The code below optimizes (or (and X, Y), Z).
8268 // The AND operand needs to have a single user to make these optimizations
8270 SDValue N0 = N->getOperand(0);
8271 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8273 SDValue N1 = N->getOperand(1);
8275 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8276 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8277 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8279 unsigned SplatBitSize;
8282 APInt SplatBits0, SplatBits1;
8283 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8284 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8285 // Ensure that the second operand of both ands are constants
8286 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8287 HasAnyUndefs) && !HasAnyUndefs) {
8288 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8289 HasAnyUndefs) && !HasAnyUndefs) {
8290 // Ensure that the bit width of the constants are the same and that
8291 // the splat arguments are logical inverses as per the pattern we
8292 // are trying to simplify.
8293 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8294 SplatBits0 == ~SplatBits1) {
8295 // Canonicalize the vector type to make instruction selection
8297 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8298 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8302 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8308 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8311 // BFI is only available on V6T2+
8312 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8316 // 1) or (and A, mask), val => ARMbfi A, val, mask
8317 // iff (val & mask) == val
8319 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8320 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8321 // && mask == ~mask2
8322 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8323 // && ~mask == mask2
8324 // (i.e., copy a bitfield value into another bitfield of the same width)
8329 SDValue N00 = N0.getOperand(0);
8331 // The value and the mask need to be constants so we can verify this is
8332 // actually a bitfield set. If the mask is 0xffff, we can do better
8333 // via a movt instruction, so don't use BFI in that case.
8334 SDValue MaskOp = N0.getOperand(1);
8335 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8338 unsigned Mask = MaskC->getZExtValue();
8342 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8343 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8345 unsigned Val = N1C->getZExtValue();
8346 if ((Val & ~Mask) != Val)
8349 if (ARM::isBitFieldInvertedMask(Mask)) {
8350 Val >>= countTrailingZeros(~Mask);
8352 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8353 DAG.getConstant(Val, MVT::i32),
8354 DAG.getConstant(Mask, MVT::i32));
8356 // Do not add new nodes to DAG combiner worklist.
8357 DCI.CombineTo(N, Res, false);
8360 } else if (N1.getOpcode() == ISD::AND) {
8361 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8362 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8365 unsigned Mask2 = N11C->getZExtValue();
8367 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8369 if (ARM::isBitFieldInvertedMask(Mask) &&
8371 // The pack halfword instruction works better for masks that fit it,
8372 // so use that when it's available.
8373 if (Subtarget->hasT2ExtractPack() &&
8374 (Mask == 0xffff || Mask == 0xffff0000))
8377 unsigned amt = countTrailingZeros(Mask2);
8378 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8379 DAG.getConstant(amt, MVT::i32));
8380 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8381 DAG.getConstant(Mask, MVT::i32));
8382 // Do not add new nodes to DAG combiner worklist.
8383 DCI.CombineTo(N, Res, false);
8385 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8387 // The pack halfword instruction works better for masks that fit it,
8388 // so use that when it's available.
8389 if (Subtarget->hasT2ExtractPack() &&
8390 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8393 unsigned lsb = countTrailingZeros(Mask);
8394 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8395 DAG.getConstant(lsb, MVT::i32));
8396 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8397 DAG.getConstant(Mask2, MVT::i32));
8398 // Do not add new nodes to DAG combiner worklist.
8399 DCI.CombineTo(N, Res, false);
8404 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8405 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8406 ARM::isBitFieldInvertedMask(~Mask)) {
8407 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8408 // where lsb(mask) == #shamt and masked bits of B are known zero.
8409 SDValue ShAmt = N00.getOperand(1);
8410 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8411 unsigned LSB = countTrailingZeros(Mask);
8415 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8416 DAG.getConstant(~Mask, MVT::i32));
8418 // Do not add new nodes to DAG combiner worklist.
8419 DCI.CombineTo(N, Res, false);
8425 static SDValue PerformXORCombine(SDNode *N,
8426 TargetLowering::DAGCombinerInfo &DCI,
8427 const ARMSubtarget *Subtarget) {
8428 EVT VT = N->getValueType(0);
8429 SelectionDAG &DAG = DCI.DAG;
8431 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8434 if (!Subtarget->isThumb1Only()) {
8435 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8436 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8437 if (Result.getNode())
8444 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8445 /// the bits being cleared by the AND are not demanded by the BFI.
8446 static SDValue PerformBFICombine(SDNode *N,
8447 TargetLowering::DAGCombinerInfo &DCI) {
8448 SDValue N1 = N->getOperand(1);
8449 if (N1.getOpcode() == ISD::AND) {
8450 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8453 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8454 unsigned LSB = countTrailingZeros(~InvMask);
8455 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8456 unsigned Mask = (1 << Width)-1;
8457 unsigned Mask2 = N11C->getZExtValue();
8458 if ((Mask & (~Mask2)) == 0)
8459 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8460 N->getOperand(0), N1.getOperand(0),
8466 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8467 /// ARMISD::VMOVRRD.
8468 static SDValue PerformVMOVRRDCombine(SDNode *N,
8469 TargetLowering::DAGCombinerInfo &DCI) {
8470 // vmovrrd(vmovdrr x, y) -> x,y
8471 SDValue InDouble = N->getOperand(0);
8472 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8473 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8475 // vmovrrd(load f64) -> (load i32), (load i32)
8476 SDNode *InNode = InDouble.getNode();
8477 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8478 InNode->getValueType(0) == MVT::f64 &&
8479 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8480 !cast<LoadSDNode>(InNode)->isVolatile()) {
8481 // TODO: Should this be done for non-FrameIndex operands?
8482 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8484 SelectionDAG &DAG = DCI.DAG;
8486 SDValue BasePtr = LD->getBasePtr();
8487 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8488 LD->getPointerInfo(), LD->isVolatile(),
8489 LD->isNonTemporal(), LD->isInvariant(),
8490 LD->getAlignment());
8492 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8493 DAG.getConstant(4, MVT::i32));
8494 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8495 LD->getPointerInfo(), LD->isVolatile(),
8496 LD->isNonTemporal(), LD->isInvariant(),
8497 std::min(4U, LD->getAlignment() / 2));
8499 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8500 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8501 std::swap (NewLD1, NewLD2);
8502 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8509 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8510 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8511 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8512 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8513 SDValue Op0 = N->getOperand(0);
8514 SDValue Op1 = N->getOperand(1);
8515 if (Op0.getOpcode() == ISD::BITCAST)
8516 Op0 = Op0.getOperand(0);
8517 if (Op1.getOpcode() == ISD::BITCAST)
8518 Op1 = Op1.getOperand(0);
8519 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8520 Op0.getNode() == Op1.getNode() &&
8521 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8522 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8523 N->getValueType(0), Op0.getOperand(0));
8527 /// PerformSTORECombine - Target-specific dag combine xforms for
8529 static SDValue PerformSTORECombine(SDNode *N,
8530 TargetLowering::DAGCombinerInfo &DCI) {
8531 StoreSDNode *St = cast<StoreSDNode>(N);
8532 if (St->isVolatile())
8535 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8536 // pack all of the elements in one place. Next, store to memory in fewer
8538 SDValue StVal = St->getValue();
8539 EVT VT = StVal.getValueType();
8540 if (St->isTruncatingStore() && VT.isVector()) {
8541 SelectionDAG &DAG = DCI.DAG;
8542 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8543 EVT StVT = St->getMemoryVT();
8544 unsigned NumElems = VT.getVectorNumElements();
8545 assert(StVT != VT && "Cannot truncate to the same type");
8546 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8547 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8549 // From, To sizes and ElemCount must be pow of two
8550 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8552 // We are going to use the original vector elt for storing.
8553 // Accumulated smaller vector elements must be a multiple of the store size.
8554 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8556 unsigned SizeRatio = FromEltSz / ToEltSz;
8557 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8559 // Create a type on which we perform the shuffle.
8560 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8561 NumElems*SizeRatio);
8562 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8565 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8566 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8567 for (unsigned i = 0; i < NumElems; ++i)
8568 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8570 // Can't shuffle using an illegal type.
8571 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8573 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8574 DAG.getUNDEF(WideVec.getValueType()),
8576 // At this point all of the data is stored at the bottom of the
8577 // register. We now need to save it to mem.
8579 // Find the largest store unit
8580 MVT StoreType = MVT::i8;
8581 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8582 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8583 MVT Tp = (MVT::SimpleValueType)tp;
8584 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8587 // Didn't find a legal store type.
8588 if (!TLI.isTypeLegal(StoreType))
8591 // Bitcast the original vector into a vector of store-size units
8592 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8593 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8594 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8595 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8596 SmallVector<SDValue, 8> Chains;
8597 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8598 TLI.getPointerTy());
8599 SDValue BasePtr = St->getBasePtr();
8601 // Perform one or more big stores into memory.
8602 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8603 for (unsigned I = 0; I < E; I++) {
8604 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8605 StoreType, ShuffWide,
8606 DAG.getIntPtrConstant(I));
8607 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8608 St->getPointerInfo(), St->isVolatile(),
8609 St->isNonTemporal(), St->getAlignment());
8610 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8612 Chains.push_back(Ch);
8614 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8617 if (!ISD::isNormalStore(St))
8620 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8621 // ARM stores of arguments in the same cache line.
8622 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8623 StVal.getNode()->hasOneUse()) {
8624 SelectionDAG &DAG = DCI.DAG;
8625 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8627 SDValue BasePtr = St->getBasePtr();
8628 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8629 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8630 BasePtr, St->getPointerInfo(), St->isVolatile(),
8631 St->isNonTemporal(), St->getAlignment());
8633 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8634 DAG.getConstant(4, MVT::i32));
8635 return DAG.getStore(NewST1.getValue(0), DL,
8636 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8637 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8638 St->isNonTemporal(),
8639 std::min(4U, St->getAlignment() / 2));
8642 if (StVal.getValueType() != MVT::i64 ||
8643 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8646 // Bitcast an i64 store extracted from a vector to f64.
8647 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8648 SelectionDAG &DAG = DCI.DAG;
8650 SDValue IntVec = StVal.getOperand(0);
8651 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8652 IntVec.getValueType().getVectorNumElements());
8653 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8654 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8655 Vec, StVal.getOperand(1));
8657 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8658 // Make the DAGCombiner fold the bitcasts.
8659 DCI.AddToWorklist(Vec.getNode());
8660 DCI.AddToWorklist(ExtElt.getNode());
8661 DCI.AddToWorklist(V.getNode());
8662 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8663 St->getPointerInfo(), St->isVolatile(),
8664 St->isNonTemporal(), St->getAlignment(),
8668 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8669 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8670 /// i64 vector to have f64 elements, since the value can then be loaded
8671 /// directly into a VFP register.
8672 static bool hasNormalLoadOperand(SDNode *N) {
8673 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8674 for (unsigned i = 0; i < NumElts; ++i) {
8675 SDNode *Elt = N->getOperand(i).getNode();
8676 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8682 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8683 /// ISD::BUILD_VECTOR.
8684 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8685 TargetLowering::DAGCombinerInfo &DCI){
8686 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8687 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8688 // into a pair of GPRs, which is fine when the value is used as a scalar,
8689 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8690 SelectionDAG &DAG = DCI.DAG;
8691 if (N->getNumOperands() == 2) {
8692 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8697 // Load i64 elements as f64 values so that type legalization does not split
8698 // them up into i32 values.
8699 EVT VT = N->getValueType(0);
8700 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8703 SmallVector<SDValue, 8> Ops;
8704 unsigned NumElts = VT.getVectorNumElements();
8705 for (unsigned i = 0; i < NumElts; ++i) {
8706 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8708 // Make the DAGCombiner fold the bitcast.
8709 DCI.AddToWorklist(V.getNode());
8711 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8712 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8713 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8716 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8718 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8719 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8720 // At that time, we may have inserted bitcasts from integer to float.
8721 // If these bitcasts have survived DAGCombine, change the lowering of this
8722 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8723 // force to use floating point types.
8725 // Make sure we can change the type of the vector.
8726 // This is possible iff:
8727 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8728 // 1.1. Vector is used only once.
8729 // 1.2. Use is a bit convert to an integer type.
8730 // 2. The size of its operands are 32-bits (64-bits are not legal).
8731 EVT VT = N->getValueType(0);
8732 EVT EltVT = VT.getVectorElementType();
8734 // Check 1.1. and 2.
8735 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8738 // By construction, the input type must be float.
8739 assert(EltVT == MVT::f32 && "Unexpected type!");
8742 SDNode *Use = *N->use_begin();
8743 if (Use->getOpcode() != ISD::BITCAST ||
8744 Use->getValueType(0).isFloatingPoint())
8747 // Check profitability.
8748 // Model is, if more than half of the relevant operands are bitcast from
8749 // i32, turn the build_vector into a sequence of insert_vector_elt.
8750 // Relevant operands are everything that is not statically
8751 // (i.e., at compile time) bitcasted.
8752 unsigned NumOfBitCastedElts = 0;
8753 unsigned NumElts = VT.getVectorNumElements();
8754 unsigned NumOfRelevantElts = NumElts;
8755 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8756 SDValue Elt = N->getOperand(Idx);
8757 if (Elt->getOpcode() == ISD::BITCAST) {
8758 // Assume only bit cast to i32 will go away.
8759 if (Elt->getOperand(0).getValueType() == MVT::i32)
8760 ++NumOfBitCastedElts;
8761 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8762 // Constants are statically casted, thus do not count them as
8763 // relevant operands.
8764 --NumOfRelevantElts;
8767 // Check if more than half of the elements require a non-free bitcast.
8768 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8771 SelectionDAG &DAG = DCI.DAG;
8772 // Create the new vector type.
8773 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8774 // Check if the type is legal.
8775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8776 if (!TLI.isTypeLegal(VecVT))
8780 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8781 // => BITCAST INSERT_VECTOR_ELT
8782 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8784 SDValue Vec = DAG.getUNDEF(VecVT);
8786 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8787 SDValue V = N->getOperand(Idx);
8788 if (V.getOpcode() == ISD::UNDEF)
8790 if (V.getOpcode() == ISD::BITCAST &&
8791 V->getOperand(0).getValueType() == MVT::i32)
8792 // Fold obvious case.
8793 V = V.getOperand(0);
8795 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8796 // Make the DAGCombiner fold the bitcasts.
8797 DCI.AddToWorklist(V.getNode());
8799 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8800 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8802 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8803 // Make the DAGCombiner fold the bitcasts.
8804 DCI.AddToWorklist(Vec.getNode());
8808 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8809 /// ISD::INSERT_VECTOR_ELT.
8810 static SDValue PerformInsertEltCombine(SDNode *N,
8811 TargetLowering::DAGCombinerInfo &DCI) {
8812 // Bitcast an i64 load inserted into a vector to f64.
8813 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8814 EVT VT = N->getValueType(0);
8815 SDNode *Elt = N->getOperand(1).getNode();
8816 if (VT.getVectorElementType() != MVT::i64 ||
8817 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8820 SelectionDAG &DAG = DCI.DAG;
8822 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8823 VT.getVectorNumElements());
8824 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8825 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8826 // Make the DAGCombiner fold the bitcasts.
8827 DCI.AddToWorklist(Vec.getNode());
8828 DCI.AddToWorklist(V.getNode());
8829 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8830 Vec, V, N->getOperand(2));
8831 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8834 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8835 /// ISD::VECTOR_SHUFFLE.
8836 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8837 // The LLVM shufflevector instruction does not require the shuffle mask
8838 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8839 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8840 // operands do not match the mask length, they are extended by concatenating
8841 // them with undef vectors. That is probably the right thing for other
8842 // targets, but for NEON it is better to concatenate two double-register
8843 // size vector operands into a single quad-register size vector. Do that
8844 // transformation here:
8845 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8846 // shuffle(concat(v1, v2), undef)
8847 SDValue Op0 = N->getOperand(0);
8848 SDValue Op1 = N->getOperand(1);
8849 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8850 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8851 Op0.getNumOperands() != 2 ||
8852 Op1.getNumOperands() != 2)
8854 SDValue Concat0Op1 = Op0.getOperand(1);
8855 SDValue Concat1Op1 = Op1.getOperand(1);
8856 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8857 Concat1Op1.getOpcode() != ISD::UNDEF)
8859 // Skip the transformation if any of the types are illegal.
8860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8861 EVT VT = N->getValueType(0);
8862 if (!TLI.isTypeLegal(VT) ||
8863 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8864 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8867 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8868 Op0.getOperand(0), Op1.getOperand(0));
8869 // Translate the shuffle mask.
8870 SmallVector<int, 16> NewMask;
8871 unsigned NumElts = VT.getVectorNumElements();
8872 unsigned HalfElts = NumElts/2;
8873 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8874 for (unsigned n = 0; n < NumElts; ++n) {
8875 int MaskElt = SVN->getMaskElt(n);
8877 if (MaskElt < (int)HalfElts)
8879 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8880 NewElt = HalfElts + MaskElt - NumElts;
8881 NewMask.push_back(NewElt);
8883 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8884 DAG.getUNDEF(VT), NewMask.data());
8887 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8888 /// NEON load/store intrinsics to merge base address updates.
8889 static SDValue CombineBaseUpdate(SDNode *N,
8890 TargetLowering::DAGCombinerInfo &DCI) {
8891 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8894 SelectionDAG &DAG = DCI.DAG;
8895 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8896 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8897 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8898 SDValue Addr = N->getOperand(AddrOpIdx);
8900 // Search for a use of the address operand that is an increment.
8901 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8902 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8904 if (User->getOpcode() != ISD::ADD ||
8905 UI.getUse().getResNo() != Addr.getResNo())
8908 // Check that the add is independent of the load/store. Otherwise, folding
8909 // it would create a cycle.
8910 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8913 // Find the new opcode for the updating load/store.
8915 bool isLaneOp = false;
8916 unsigned NewOpc = 0;
8917 unsigned NumVecs = 0;
8919 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8921 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8922 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8924 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8926 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8928 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8930 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8931 NumVecs = 2; isLaneOp = true; break;
8932 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8933 NumVecs = 3; isLaneOp = true; break;
8934 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8935 NumVecs = 4; isLaneOp = true; break;
8936 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8937 NumVecs = 1; isLoad = false; break;
8938 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8939 NumVecs = 2; isLoad = false; break;
8940 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8941 NumVecs = 3; isLoad = false; break;
8942 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8943 NumVecs = 4; isLoad = false; break;
8944 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8945 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8946 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8947 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8948 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8949 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8953 switch (N->getOpcode()) {
8954 default: llvm_unreachable("unexpected opcode for Neon base update");
8955 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8956 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8957 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8961 // Find the size of memory referenced by the load/store.
8964 VecTy = N->getValueType(0);
8966 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8967 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8969 NumBytes /= VecTy.getVectorNumElements();
8971 // If the increment is a constant, it must match the memory ref size.
8972 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8973 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8974 uint64_t IncVal = CInc->getZExtValue();
8975 if (IncVal != NumBytes)
8977 } else if (NumBytes >= 3 * 16) {
8978 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8979 // separate instructions that make it harder to use a non-constant update.
8983 // Create the new updating load/store node.
8985 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8987 for (n = 0; n < NumResultVecs; ++n)
8989 Tys[n++] = MVT::i32;
8990 Tys[n] = MVT::Other;
8991 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8992 SmallVector<SDValue, 8> Ops;
8993 Ops.push_back(N->getOperand(0)); // incoming chain
8994 Ops.push_back(N->getOperand(AddrOpIdx));
8996 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8997 Ops.push_back(N->getOperand(i));
8999 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9000 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9001 Ops, MemInt->getMemoryVT(),
9002 MemInt->getMemOperand());
9005 std::vector<SDValue> NewResults;
9006 for (unsigned i = 0; i < NumResultVecs; ++i) {
9007 NewResults.push_back(SDValue(UpdN.getNode(), i));
9009 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9010 DCI.CombineTo(N, NewResults);
9011 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9018 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9019 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9020 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9022 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9023 SelectionDAG &DAG = DCI.DAG;
9024 EVT VT = N->getValueType(0);
9025 // vldN-dup instructions only support 64-bit vectors for N > 1.
9026 if (!VT.is64BitVector())
9029 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9030 SDNode *VLD = N->getOperand(0).getNode();
9031 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9033 unsigned NumVecs = 0;
9034 unsigned NewOpc = 0;
9035 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9036 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9038 NewOpc = ARMISD::VLD2DUP;
9039 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9041 NewOpc = ARMISD::VLD3DUP;
9042 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9044 NewOpc = ARMISD::VLD4DUP;
9049 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9050 // numbers match the load.
9051 unsigned VLDLaneNo =
9052 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9053 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9055 // Ignore uses of the chain result.
9056 if (UI.getUse().getResNo() == NumVecs)
9059 if (User->getOpcode() != ARMISD::VDUPLANE ||
9060 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9064 // Create the vldN-dup node.
9067 for (n = 0; n < NumVecs; ++n)
9069 Tys[n] = MVT::Other;
9070 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9071 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9072 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9073 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9074 Ops, VLDMemInt->getMemoryVT(),
9075 VLDMemInt->getMemOperand());
9078 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9080 unsigned ResNo = UI.getUse().getResNo();
9081 // Ignore uses of the chain result.
9082 if (ResNo == NumVecs)
9085 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9088 // Now the vldN-lane intrinsic is dead except for its chain result.
9089 // Update uses of the chain.
9090 std::vector<SDValue> VLDDupResults;
9091 for (unsigned n = 0; n < NumVecs; ++n)
9092 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9093 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9094 DCI.CombineTo(VLD, VLDDupResults);
9099 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9100 /// ARMISD::VDUPLANE.
9101 static SDValue PerformVDUPLANECombine(SDNode *N,
9102 TargetLowering::DAGCombinerInfo &DCI) {
9103 SDValue Op = N->getOperand(0);
9105 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9106 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9107 if (CombineVLDDUP(N, DCI))
9108 return SDValue(N, 0);
9110 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9111 // redundant. Ignore bit_converts for now; element sizes are checked below.
9112 while (Op.getOpcode() == ISD::BITCAST)
9113 Op = Op.getOperand(0);
9114 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9117 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9118 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9119 // The canonical VMOV for a zero vector uses a 32-bit element size.
9120 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9122 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9124 EVT VT = N->getValueType(0);
9125 if (EltSize > VT.getVectorElementType().getSizeInBits())
9128 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9131 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9132 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9133 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9137 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9139 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9144 APFloat APF = C->getValueAPF();
9145 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9146 != APFloat::opOK || !isExact)
9149 c0 = (I == 0) ? cN : c0;
9150 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9157 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9158 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9159 /// when the VMUL has a constant operand that is a power of 2.
9161 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9162 /// vmul.f32 d16, d17, d16
9163 /// vcvt.s32.f32 d16, d16
9165 /// vcvt.s32.f32 d16, d16, #3
9166 static SDValue PerformVCVTCombine(SDNode *N,
9167 TargetLowering::DAGCombinerInfo &DCI,
9168 const ARMSubtarget *Subtarget) {
9169 SelectionDAG &DAG = DCI.DAG;
9170 SDValue Op = N->getOperand(0);
9172 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9173 Op.getOpcode() != ISD::FMUL)
9177 SDValue N0 = Op->getOperand(0);
9178 SDValue ConstVec = Op->getOperand(1);
9179 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9181 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9182 !isConstVecPow2(ConstVec, isSigned, C))
9185 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9186 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9187 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9188 // These instructions only exist converting from f32 to i32. We can handle
9189 // smaller integers by generating an extra truncate, but larger ones would
9194 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9195 Intrinsic::arm_neon_vcvtfp2fxu;
9196 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9197 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9198 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9199 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9200 DAG.getConstant(Log2_64(C), MVT::i32));
9202 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9203 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9208 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9209 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9210 /// when the VDIV has a constant operand that is a power of 2.
9212 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9213 /// vcvt.f32.s32 d16, d16
9214 /// vdiv.f32 d16, d17, d16
9216 /// vcvt.f32.s32 d16, d16, #3
9217 static SDValue PerformVDIVCombine(SDNode *N,
9218 TargetLowering::DAGCombinerInfo &DCI,
9219 const ARMSubtarget *Subtarget) {
9220 SelectionDAG &DAG = DCI.DAG;
9221 SDValue Op = N->getOperand(0);
9222 unsigned OpOpcode = Op.getNode()->getOpcode();
9224 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9225 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9229 SDValue ConstVec = N->getOperand(1);
9230 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9232 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9233 !isConstVecPow2(ConstVec, isSigned, C))
9236 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9237 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9238 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9239 // These instructions only exist converting from i32 to f32. We can handle
9240 // smaller integers by generating an extra extend, but larger ones would
9245 SDValue ConvInput = Op.getOperand(0);
9246 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9247 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9248 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9249 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9252 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9253 Intrinsic::arm_neon_vcvtfxu2fp;
9254 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9256 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9257 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9260 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9261 /// operand of a vector shift operation, where all the elements of the
9262 /// build_vector must have the same constant integer value.
9263 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9264 // Ignore bit_converts.
9265 while (Op.getOpcode() == ISD::BITCAST)
9266 Op = Op.getOperand(0);
9267 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9268 APInt SplatBits, SplatUndef;
9269 unsigned SplatBitSize;
9271 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9272 HasAnyUndefs, ElementBits) ||
9273 SplatBitSize > ElementBits)
9275 Cnt = SplatBits.getSExtValue();
9279 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9280 /// operand of a vector shift left operation. That value must be in the range:
9281 /// 0 <= Value < ElementBits for a left shift; or
9282 /// 0 <= Value <= ElementBits for a long left shift.
9283 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9284 assert(VT.isVector() && "vector shift count is not a vector type");
9285 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9286 if (! getVShiftImm(Op, ElementBits, Cnt))
9288 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9291 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9292 /// operand of a vector shift right operation. For a shift opcode, the value
9293 /// is positive, but for an intrinsic the value count must be negative. The
9294 /// absolute value must be in the range:
9295 /// 1 <= |Value| <= ElementBits for a right shift; or
9296 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9297 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9299 assert(VT.isVector() && "vector shift count is not a vector type");
9300 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9301 if (! getVShiftImm(Op, ElementBits, Cnt))
9305 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9308 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9309 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9310 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9313 // Don't do anything for most intrinsics.
9316 // Vector shifts: check for immediate versions and lower them.
9317 // Note: This is done during DAG combining instead of DAG legalizing because
9318 // the build_vectors for 64-bit vector element shift counts are generally
9319 // not legal, and it is hard to see their values after they get legalized to
9320 // loads from a constant pool.
9321 case Intrinsic::arm_neon_vshifts:
9322 case Intrinsic::arm_neon_vshiftu:
9323 case Intrinsic::arm_neon_vrshifts:
9324 case Intrinsic::arm_neon_vrshiftu:
9325 case Intrinsic::arm_neon_vrshiftn:
9326 case Intrinsic::arm_neon_vqshifts:
9327 case Intrinsic::arm_neon_vqshiftu:
9328 case Intrinsic::arm_neon_vqshiftsu:
9329 case Intrinsic::arm_neon_vqshiftns:
9330 case Intrinsic::arm_neon_vqshiftnu:
9331 case Intrinsic::arm_neon_vqshiftnsu:
9332 case Intrinsic::arm_neon_vqrshiftns:
9333 case Intrinsic::arm_neon_vqrshiftnu:
9334 case Intrinsic::arm_neon_vqrshiftnsu: {
9335 EVT VT = N->getOperand(1).getValueType();
9337 unsigned VShiftOpc = 0;
9340 case Intrinsic::arm_neon_vshifts:
9341 case Intrinsic::arm_neon_vshiftu:
9342 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9343 VShiftOpc = ARMISD::VSHL;
9346 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9347 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9348 ARMISD::VSHRs : ARMISD::VSHRu);
9353 case Intrinsic::arm_neon_vrshifts:
9354 case Intrinsic::arm_neon_vrshiftu:
9355 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9359 case Intrinsic::arm_neon_vqshifts:
9360 case Intrinsic::arm_neon_vqshiftu:
9361 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9365 case Intrinsic::arm_neon_vqshiftsu:
9366 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9368 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9370 case Intrinsic::arm_neon_vrshiftn:
9371 case Intrinsic::arm_neon_vqshiftns:
9372 case Intrinsic::arm_neon_vqshiftnu:
9373 case Intrinsic::arm_neon_vqshiftnsu:
9374 case Intrinsic::arm_neon_vqrshiftns:
9375 case Intrinsic::arm_neon_vqrshiftnu:
9376 case Intrinsic::arm_neon_vqrshiftnsu:
9377 // Narrowing shifts require an immediate right shift.
9378 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9380 llvm_unreachable("invalid shift count for narrowing vector shift "
9384 llvm_unreachable("unhandled vector shift");
9388 case Intrinsic::arm_neon_vshifts:
9389 case Intrinsic::arm_neon_vshiftu:
9390 // Opcode already set above.
9392 case Intrinsic::arm_neon_vrshifts:
9393 VShiftOpc = ARMISD::VRSHRs; break;
9394 case Intrinsic::arm_neon_vrshiftu:
9395 VShiftOpc = ARMISD::VRSHRu; break;
9396 case Intrinsic::arm_neon_vrshiftn:
9397 VShiftOpc = ARMISD::VRSHRN; break;
9398 case Intrinsic::arm_neon_vqshifts:
9399 VShiftOpc = ARMISD::VQSHLs; break;
9400 case Intrinsic::arm_neon_vqshiftu:
9401 VShiftOpc = ARMISD::VQSHLu; break;
9402 case Intrinsic::arm_neon_vqshiftsu:
9403 VShiftOpc = ARMISD::VQSHLsu; break;
9404 case Intrinsic::arm_neon_vqshiftns:
9405 VShiftOpc = ARMISD::VQSHRNs; break;
9406 case Intrinsic::arm_neon_vqshiftnu:
9407 VShiftOpc = ARMISD::VQSHRNu; break;
9408 case Intrinsic::arm_neon_vqshiftnsu:
9409 VShiftOpc = ARMISD::VQSHRNsu; break;
9410 case Intrinsic::arm_neon_vqrshiftns:
9411 VShiftOpc = ARMISD::VQRSHRNs; break;
9412 case Intrinsic::arm_neon_vqrshiftnu:
9413 VShiftOpc = ARMISD::VQRSHRNu; break;
9414 case Intrinsic::arm_neon_vqrshiftnsu:
9415 VShiftOpc = ARMISD::VQRSHRNsu; break;
9418 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9419 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9422 case Intrinsic::arm_neon_vshiftins: {
9423 EVT VT = N->getOperand(1).getValueType();
9425 unsigned VShiftOpc = 0;
9427 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9428 VShiftOpc = ARMISD::VSLI;
9429 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9430 VShiftOpc = ARMISD::VSRI;
9432 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9435 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9436 N->getOperand(1), N->getOperand(2),
9437 DAG.getConstant(Cnt, MVT::i32));
9440 case Intrinsic::arm_neon_vqrshifts:
9441 case Intrinsic::arm_neon_vqrshiftu:
9442 // No immediate versions of these to check for.
9449 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9450 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9451 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9452 /// vector element shift counts are generally not legal, and it is hard to see
9453 /// their values after they get legalized to loads from a constant pool.
9454 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9455 const ARMSubtarget *ST) {
9456 EVT VT = N->getValueType(0);
9457 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9458 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9459 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9460 SDValue N1 = N->getOperand(1);
9461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9462 SDValue N0 = N->getOperand(0);
9463 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9464 DAG.MaskedValueIsZero(N0.getOperand(0),
9465 APInt::getHighBitsSet(32, 16)))
9466 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9470 // Nothing to be done for scalar shifts.
9471 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9472 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9475 assert(ST->hasNEON() && "unexpected vector shift");
9478 switch (N->getOpcode()) {
9479 default: llvm_unreachable("unexpected shift opcode");
9482 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9483 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9484 DAG.getConstant(Cnt, MVT::i32));
9489 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9490 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9491 ARMISD::VSHRs : ARMISD::VSHRu);
9492 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9493 DAG.getConstant(Cnt, MVT::i32));
9499 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9500 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9501 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9502 const ARMSubtarget *ST) {
9503 SDValue N0 = N->getOperand(0);
9505 // Check for sign- and zero-extensions of vector extract operations of 8-
9506 // and 16-bit vector elements. NEON supports these directly. They are
9507 // handled during DAG combining because type legalization will promote them
9508 // to 32-bit types and it is messy to recognize the operations after that.
9509 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9510 SDValue Vec = N0.getOperand(0);
9511 SDValue Lane = N0.getOperand(1);
9512 EVT VT = N->getValueType(0);
9513 EVT EltVT = N0.getValueType();
9514 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9516 if (VT == MVT::i32 &&
9517 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9518 TLI.isTypeLegal(Vec.getValueType()) &&
9519 isa<ConstantSDNode>(Lane)) {
9522 switch (N->getOpcode()) {
9523 default: llvm_unreachable("unexpected opcode");
9524 case ISD::SIGN_EXTEND:
9525 Opc = ARMISD::VGETLANEs;
9527 case ISD::ZERO_EXTEND:
9528 case ISD::ANY_EXTEND:
9529 Opc = ARMISD::VGETLANEu;
9532 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9539 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9540 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9541 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9542 const ARMSubtarget *ST) {
9543 // If the target supports NEON, try to use vmax/vmin instructions for f32
9544 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9545 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9546 // a NaN; only do the transformation when it matches that behavior.
9548 // For now only do this when using NEON for FP operations; if using VFP, it
9549 // is not obvious that the benefit outweighs the cost of switching to the
9551 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9552 N->getValueType(0) != MVT::f32)
9555 SDValue CondLHS = N->getOperand(0);
9556 SDValue CondRHS = N->getOperand(1);
9557 SDValue LHS = N->getOperand(2);
9558 SDValue RHS = N->getOperand(3);
9559 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9561 unsigned Opcode = 0;
9563 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9564 IsReversed = false; // x CC y ? x : y
9565 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9566 IsReversed = true ; // x CC y ? y : x
9580 // If LHS is NaN, an ordered comparison will be false and the result will
9581 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9582 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9583 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9584 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9586 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9587 // will return -0, so vmin can only be used for unsafe math or if one of
9588 // the operands is known to be nonzero.
9589 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9590 !DAG.getTarget().Options.UnsafeFPMath &&
9591 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9593 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9602 // If LHS is NaN, an ordered comparison will be false and the result will
9603 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9604 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9605 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9606 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9608 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9609 // will return +0, so vmax can only be used for unsafe math or if one of
9610 // the operands is known to be nonzero.
9611 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9612 !DAG.getTarget().Options.UnsafeFPMath &&
9613 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9615 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9621 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9624 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9626 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9627 SDValue Cmp = N->getOperand(4);
9628 if (Cmp.getOpcode() != ARMISD::CMPZ)
9629 // Only looking at EQ and NE cases.
9632 EVT VT = N->getValueType(0);
9634 SDValue LHS = Cmp.getOperand(0);
9635 SDValue RHS = Cmp.getOperand(1);
9636 SDValue FalseVal = N->getOperand(0);
9637 SDValue TrueVal = N->getOperand(1);
9638 SDValue ARMcc = N->getOperand(2);
9639 ARMCC::CondCodes CC =
9640 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9658 /// FIXME: Turn this into a target neutral optimization?
9660 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9661 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9662 N->getOperand(3), Cmp);
9663 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9665 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9666 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9667 N->getOperand(3), NewCmp);
9670 if (Res.getNode()) {
9671 APInt KnownZero, KnownOne;
9672 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9673 // Capture demanded bits information that would be otherwise lost.
9674 if (KnownZero == 0xfffffffe)
9675 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9676 DAG.getValueType(MVT::i1));
9677 else if (KnownZero == 0xffffff00)
9678 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9679 DAG.getValueType(MVT::i8));
9680 else if (KnownZero == 0xffff0000)
9681 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9682 DAG.getValueType(MVT::i16));
9688 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9689 DAGCombinerInfo &DCI) const {
9690 switch (N->getOpcode()) {
9692 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9693 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9694 case ISD::SUB: return PerformSUBCombine(N, DCI);
9695 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9696 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9697 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9698 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9699 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9700 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9701 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9702 case ISD::STORE: return PerformSTORECombine(N, DCI);
9703 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9704 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9705 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9706 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9707 case ISD::FP_TO_SINT:
9708 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9709 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9710 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9713 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9714 case ISD::SIGN_EXTEND:
9715 case ISD::ZERO_EXTEND:
9716 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9717 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9718 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9719 case ARMISD::VLD2DUP:
9720 case ARMISD::VLD3DUP:
9721 case ARMISD::VLD4DUP:
9722 return CombineBaseUpdate(N, DCI);
9723 case ARMISD::BUILD_VECTOR:
9724 return PerformARMBUILD_VECTORCombine(N, DCI);
9725 case ISD::INTRINSIC_VOID:
9726 case ISD::INTRINSIC_W_CHAIN:
9727 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9728 case Intrinsic::arm_neon_vld1:
9729 case Intrinsic::arm_neon_vld2:
9730 case Intrinsic::arm_neon_vld3:
9731 case Intrinsic::arm_neon_vld4:
9732 case Intrinsic::arm_neon_vld2lane:
9733 case Intrinsic::arm_neon_vld3lane:
9734 case Intrinsic::arm_neon_vld4lane:
9735 case Intrinsic::arm_neon_vst1:
9736 case Intrinsic::arm_neon_vst2:
9737 case Intrinsic::arm_neon_vst3:
9738 case Intrinsic::arm_neon_vst4:
9739 case Intrinsic::arm_neon_vst2lane:
9740 case Intrinsic::arm_neon_vst3lane:
9741 case Intrinsic::arm_neon_vst4lane:
9742 return CombineBaseUpdate(N, DCI);
9750 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9752 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9755 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9759 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9760 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9762 switch (VT.getSimpleVT().SimpleTy) {
9768 // Unaligned access can use (for example) LRDB, LRDH, LDR
9769 if (AllowsUnaligned) {
9771 *Fast = Subtarget->hasV7Ops();
9778 // For any little-endian targets with neon, we can support unaligned ld/st
9779 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9780 // A big-endian target may also explicitly support unaligned accesses
9781 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9791 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9792 unsigned AlignCheck) {
9793 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9794 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9797 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9798 unsigned DstAlign, unsigned SrcAlign,
9799 bool IsMemset, bool ZeroMemset,
9801 MachineFunction &MF) const {
9802 const Function *F = MF.getFunction();
9804 // See if we can use NEON instructions for this...
9805 if ((!IsMemset || ZeroMemset) &&
9806 Subtarget->hasNEON() &&
9807 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9808 Attribute::NoImplicitFloat)) {
9811 (memOpAlign(SrcAlign, DstAlign, 16) ||
9812 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9814 } else if (Size >= 8 &&
9815 (memOpAlign(SrcAlign, DstAlign, 8) ||
9816 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9822 // Lowering to i32/i16 if the size permits.
9828 // Let the target-independent logic figure it out.
9832 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9833 if (Val.getOpcode() != ISD::LOAD)
9836 EVT VT1 = Val.getValueType();
9837 if (!VT1.isSimple() || !VT1.isInteger() ||
9838 !VT2.isSimple() || !VT2.isInteger())
9841 switch (VT1.getSimpleVT().SimpleTy) {
9846 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9853 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9854 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9857 if (!isTypeLegal(EVT::getEVT(Ty1)))
9860 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9862 // Assuming the caller doesn't have a zeroext or signext return parameter,
9863 // truncation all the way down to i1 is valid.
9868 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9873 switch (VT.getSimpleVT().SimpleTy) {
9874 default: return false;
9889 if ((V & (Scale - 1)) != 0)
9892 return V == (V & ((1LL << 5) - 1));
9895 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9896 const ARMSubtarget *Subtarget) {
9903 switch (VT.getSimpleVT().SimpleTy) {
9904 default: return false;
9909 // + imm12 or - imm8
9911 return V == (V & ((1LL << 8) - 1));
9912 return V == (V & ((1LL << 12) - 1));
9915 // Same as ARM mode. FIXME: NEON?
9916 if (!Subtarget->hasVFP2())
9921 return V == (V & ((1LL << 8) - 1));
9925 /// isLegalAddressImmediate - Return true if the integer value can be used
9926 /// as the offset of the target addressing mode for load / store of the
9928 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9929 const ARMSubtarget *Subtarget) {
9936 if (Subtarget->isThumb1Only())
9937 return isLegalT1AddressImmediate(V, VT);
9938 else if (Subtarget->isThumb2())
9939 return isLegalT2AddressImmediate(V, VT, Subtarget);
9944 switch (VT.getSimpleVT().SimpleTy) {
9945 default: return false;
9950 return V == (V & ((1LL << 12) - 1));
9953 return V == (V & ((1LL << 8) - 1));
9956 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9961 return V == (V & ((1LL << 8) - 1));
9965 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9967 int Scale = AM.Scale;
9971 switch (VT.getSimpleVT().SimpleTy) {
9972 default: return false;
9981 return Scale == 2 || Scale == 4 || Scale == 8;
9984 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9988 // Note, we allow "void" uses (basically, uses that aren't loads or
9989 // stores), because arm allows folding a scale into many arithmetic
9990 // operations. This should be made more precise and revisited later.
9992 // Allow r << imm, but the imm has to be a multiple of two.
9993 if (Scale & 1) return false;
9994 return isPowerOf2_32(Scale);
9998 /// isLegalAddressingMode - Return true if the addressing mode represented
9999 /// by AM is legal for this target, for a load/store of the specified type.
10000 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10002 EVT VT = getValueType(Ty, true);
10003 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10006 // Can never fold addr of global into load/store.
10010 switch (AM.Scale) {
10011 case 0: // no scale reg, must be "r+i" or "r", or "i".
10014 if (Subtarget->isThumb1Only())
10018 // ARM doesn't support any R+R*scale+imm addr modes.
10022 if (!VT.isSimple())
10025 if (Subtarget->isThumb2())
10026 return isLegalT2ScaledAddressingMode(AM, VT);
10028 int Scale = AM.Scale;
10029 switch (VT.getSimpleVT().SimpleTy) {
10030 default: return false;
10034 if (Scale < 0) Scale = -Scale;
10038 return isPowerOf2_32(Scale & ~1);
10042 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10047 // Note, we allow "void" uses (basically, uses that aren't loads or
10048 // stores), because arm allows folding a scale into many arithmetic
10049 // operations. This should be made more precise and revisited later.
10051 // Allow r << imm, but the imm has to be a multiple of two.
10052 if (Scale & 1) return false;
10053 return isPowerOf2_32(Scale);
10059 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10060 /// icmp immediate, that is the target has icmp instructions which can compare
10061 /// a register against the immediate without having to materialize the
10062 /// immediate into a register.
10063 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10064 // Thumb2 and ARM modes can use cmn for negative immediates.
10065 if (!Subtarget->isThumb())
10066 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10067 if (Subtarget->isThumb2())
10068 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10069 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10070 return Imm >= 0 && Imm <= 255;
10073 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10074 /// *or sub* immediate, that is the target has add or sub instructions which can
10075 /// add a register with the immediate without having to materialize the
10076 /// immediate into a register.
10077 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10078 // Same encoding for add/sub, just flip the sign.
10079 int64_t AbsImm = llvm::abs64(Imm);
10080 if (!Subtarget->isThumb())
10081 return ARM_AM::getSOImmVal(AbsImm) != -1;
10082 if (Subtarget->isThumb2())
10083 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10084 // Thumb1 only has 8-bit unsigned immediate.
10085 return AbsImm >= 0 && AbsImm <= 255;
10088 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10089 bool isSEXTLoad, SDValue &Base,
10090 SDValue &Offset, bool &isInc,
10091 SelectionDAG &DAG) {
10092 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10095 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10096 // AddressingMode 3
10097 Base = Ptr->getOperand(0);
10098 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10099 int RHSC = (int)RHS->getZExtValue();
10100 if (RHSC < 0 && RHSC > -256) {
10101 assert(Ptr->getOpcode() == ISD::ADD);
10103 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10107 isInc = (Ptr->getOpcode() == ISD::ADD);
10108 Offset = Ptr->getOperand(1);
10110 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10111 // AddressingMode 2
10112 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10113 int RHSC = (int)RHS->getZExtValue();
10114 if (RHSC < 0 && RHSC > -0x1000) {
10115 assert(Ptr->getOpcode() == ISD::ADD);
10117 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10118 Base = Ptr->getOperand(0);
10123 if (Ptr->getOpcode() == ISD::ADD) {
10125 ARM_AM::ShiftOpc ShOpcVal=
10126 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10127 if (ShOpcVal != ARM_AM::no_shift) {
10128 Base = Ptr->getOperand(1);
10129 Offset = Ptr->getOperand(0);
10131 Base = Ptr->getOperand(0);
10132 Offset = Ptr->getOperand(1);
10137 isInc = (Ptr->getOpcode() == ISD::ADD);
10138 Base = Ptr->getOperand(0);
10139 Offset = Ptr->getOperand(1);
10143 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10147 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10148 bool isSEXTLoad, SDValue &Base,
10149 SDValue &Offset, bool &isInc,
10150 SelectionDAG &DAG) {
10151 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10154 Base = Ptr->getOperand(0);
10155 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10156 int RHSC = (int)RHS->getZExtValue();
10157 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10158 assert(Ptr->getOpcode() == ISD::ADD);
10160 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10162 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10163 isInc = Ptr->getOpcode() == ISD::ADD;
10164 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10172 /// getPreIndexedAddressParts - returns true by value, base pointer and
10173 /// offset pointer and addressing mode by reference if the node's address
10174 /// can be legally represented as pre-indexed load / store address.
10176 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10178 ISD::MemIndexedMode &AM,
10179 SelectionDAG &DAG) const {
10180 if (Subtarget->isThumb1Only())
10185 bool isSEXTLoad = false;
10186 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10187 Ptr = LD->getBasePtr();
10188 VT = LD->getMemoryVT();
10189 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10190 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10191 Ptr = ST->getBasePtr();
10192 VT = ST->getMemoryVT();
10197 bool isLegal = false;
10198 if (Subtarget->isThumb2())
10199 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10200 Offset, isInc, DAG);
10202 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10203 Offset, isInc, DAG);
10207 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10211 /// getPostIndexedAddressParts - returns true by value, base pointer and
10212 /// offset pointer and addressing mode by reference if this node can be
10213 /// combined with a load / store to form a post-indexed load / store.
10214 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10217 ISD::MemIndexedMode &AM,
10218 SelectionDAG &DAG) const {
10219 if (Subtarget->isThumb1Only())
10224 bool isSEXTLoad = false;
10225 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10226 VT = LD->getMemoryVT();
10227 Ptr = LD->getBasePtr();
10228 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10229 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10230 VT = ST->getMemoryVT();
10231 Ptr = ST->getBasePtr();
10236 bool isLegal = false;
10237 if (Subtarget->isThumb2())
10238 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10241 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10247 // Swap base ptr and offset to catch more post-index load / store when
10248 // it's legal. In Thumb2 mode, offset must be an immediate.
10249 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10250 !Subtarget->isThumb2())
10251 std::swap(Base, Offset);
10253 // Post-indexed load / store update the base pointer.
10258 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10262 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10265 const SelectionDAG &DAG,
10266 unsigned Depth) const {
10267 unsigned BitWidth = KnownOne.getBitWidth();
10268 KnownZero = KnownOne = APInt(BitWidth, 0);
10269 switch (Op.getOpcode()) {
10275 // These nodes' second result is a boolean
10276 if (Op.getResNo() == 0)
10278 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10280 case ARMISD::CMOV: {
10281 // Bits are known zero/one if known on the LHS and RHS.
10282 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10283 if (KnownZero == 0 && KnownOne == 0) return;
10285 APInt KnownZeroRHS, KnownOneRHS;
10286 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10287 KnownZero &= KnownZeroRHS;
10288 KnownOne &= KnownOneRHS;
10291 case ISD::INTRINSIC_W_CHAIN: {
10292 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10293 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10296 case Intrinsic::arm_ldaex:
10297 case Intrinsic::arm_ldrex: {
10298 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10299 unsigned MemBits = VT.getScalarType().getSizeInBits();
10300 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10308 //===----------------------------------------------------------------------===//
10309 // ARM Inline Assembly Support
10310 //===----------------------------------------------------------------------===//
10312 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10313 // Looking for "rev" which is V6+.
10314 if (!Subtarget->hasV6Ops())
10317 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10318 std::string AsmStr = IA->getAsmString();
10319 SmallVector<StringRef, 4> AsmPieces;
10320 SplitString(AsmStr, AsmPieces, ";\n");
10322 switch (AsmPieces.size()) {
10323 default: return false;
10325 AsmStr = AsmPieces[0];
10327 SplitString(AsmStr, AsmPieces, " \t,");
10330 if (AsmPieces.size() == 3 &&
10331 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10332 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10333 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10334 if (Ty && Ty->getBitWidth() == 32)
10335 return IntrinsicLowering::LowerToByteSwap(CI);
10343 /// getConstraintType - Given a constraint letter, return the type of
10344 /// constraint it is for this target.
10345 ARMTargetLowering::ConstraintType
10346 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10347 if (Constraint.size() == 1) {
10348 switch (Constraint[0]) {
10350 case 'l': return C_RegisterClass;
10351 case 'w': return C_RegisterClass;
10352 case 'h': return C_RegisterClass;
10353 case 'x': return C_RegisterClass;
10354 case 't': return C_RegisterClass;
10355 case 'j': return C_Other; // Constant for movw.
10356 // An address with a single base register. Due to the way we
10357 // currently handle addresses it is the same as an 'r' memory constraint.
10358 case 'Q': return C_Memory;
10360 } else if (Constraint.size() == 2) {
10361 switch (Constraint[0]) {
10363 // All 'U+' constraints are addresses.
10364 case 'U': return C_Memory;
10367 return TargetLowering::getConstraintType(Constraint);
10370 /// Examine constraint type and operand type and determine a weight value.
10371 /// This object must already have been set up with the operand type
10372 /// and the current alternative constraint selected.
10373 TargetLowering::ConstraintWeight
10374 ARMTargetLowering::getSingleConstraintMatchWeight(
10375 AsmOperandInfo &info, const char *constraint) const {
10376 ConstraintWeight weight = CW_Invalid;
10377 Value *CallOperandVal = info.CallOperandVal;
10378 // If we don't have a value, we can't do a match,
10379 // but allow it at the lowest weight.
10380 if (!CallOperandVal)
10382 Type *type = CallOperandVal->getType();
10383 // Look at the constraint type.
10384 switch (*constraint) {
10386 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10389 if (type->isIntegerTy()) {
10390 if (Subtarget->isThumb())
10391 weight = CW_SpecificReg;
10393 weight = CW_Register;
10397 if (type->isFloatingPointTy())
10398 weight = CW_Register;
10404 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10406 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10408 if (Constraint.size() == 1) {
10409 // GCC ARM Constraint Letters
10410 switch (Constraint[0]) {
10411 case 'l': // Low regs or general regs.
10412 if (Subtarget->isThumb())
10413 return RCPair(0U, &ARM::tGPRRegClass);
10414 return RCPair(0U, &ARM::GPRRegClass);
10415 case 'h': // High regs or no regs.
10416 if (Subtarget->isThumb())
10417 return RCPair(0U, &ARM::hGPRRegClass);
10420 return RCPair(0U, &ARM::GPRRegClass);
10422 if (VT == MVT::Other)
10424 if (VT == MVT::f32)
10425 return RCPair(0U, &ARM::SPRRegClass);
10426 if (VT.getSizeInBits() == 64)
10427 return RCPair(0U, &ARM::DPRRegClass);
10428 if (VT.getSizeInBits() == 128)
10429 return RCPair(0U, &ARM::QPRRegClass);
10432 if (VT == MVT::Other)
10434 if (VT == MVT::f32)
10435 return RCPair(0U, &ARM::SPR_8RegClass);
10436 if (VT.getSizeInBits() == 64)
10437 return RCPair(0U, &ARM::DPR_8RegClass);
10438 if (VT.getSizeInBits() == 128)
10439 return RCPair(0U, &ARM::QPR_8RegClass);
10442 if (VT == MVT::f32)
10443 return RCPair(0U, &ARM::SPRRegClass);
10447 if (StringRef("{cc}").equals_lower(Constraint))
10448 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10450 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10453 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10454 /// vector. If it is invalid, don't add anything to Ops.
10455 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10456 std::string &Constraint,
10457 std::vector<SDValue>&Ops,
10458 SelectionDAG &DAG) const {
10461 // Currently only support length 1 constraints.
10462 if (Constraint.length() != 1) return;
10464 char ConstraintLetter = Constraint[0];
10465 switch (ConstraintLetter) {
10468 case 'I': case 'J': case 'K': case 'L':
10469 case 'M': case 'N': case 'O':
10470 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10474 int64_t CVal64 = C->getSExtValue();
10475 int CVal = (int) CVal64;
10476 // None of these constraints allow values larger than 32 bits. Check
10477 // that the value fits in an int.
10478 if (CVal != CVal64)
10481 switch (ConstraintLetter) {
10483 // Constant suitable for movw, must be between 0 and
10485 if (Subtarget->hasV6T2Ops())
10486 if (CVal >= 0 && CVal <= 65535)
10490 if (Subtarget->isThumb1Only()) {
10491 // This must be a constant between 0 and 255, for ADD
10493 if (CVal >= 0 && CVal <= 255)
10495 } else if (Subtarget->isThumb2()) {
10496 // A constant that can be used as an immediate value in a
10497 // data-processing instruction.
10498 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10501 // A constant that can be used as an immediate value in a
10502 // data-processing instruction.
10503 if (ARM_AM::getSOImmVal(CVal) != -1)
10509 if (Subtarget->isThumb()) { // FIXME thumb2
10510 // This must be a constant between -255 and -1, for negated ADD
10511 // immediates. This can be used in GCC with an "n" modifier that
10512 // prints the negated value, for use with SUB instructions. It is
10513 // not useful otherwise but is implemented for compatibility.
10514 if (CVal >= -255 && CVal <= -1)
10517 // This must be a constant between -4095 and 4095. It is not clear
10518 // what this constraint is intended for. Implemented for
10519 // compatibility with GCC.
10520 if (CVal >= -4095 && CVal <= 4095)
10526 if (Subtarget->isThumb1Only()) {
10527 // A 32-bit value where only one byte has a nonzero value. Exclude
10528 // zero to match GCC. This constraint is used by GCC internally for
10529 // constants that can be loaded with a move/shift combination.
10530 // It is not useful otherwise but is implemented for compatibility.
10531 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10533 } else if (Subtarget->isThumb2()) {
10534 // A constant whose bitwise inverse can be used as an immediate
10535 // value in a data-processing instruction. This can be used in GCC
10536 // with a "B" modifier that prints the inverted value, for use with
10537 // BIC and MVN instructions. It is not useful otherwise but is
10538 // implemented for compatibility.
10539 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10542 // A constant whose bitwise inverse can be used as an immediate
10543 // value in a data-processing instruction. This can be used in GCC
10544 // with a "B" modifier that prints the inverted value, for use with
10545 // BIC and MVN instructions. It is not useful otherwise but is
10546 // implemented for compatibility.
10547 if (ARM_AM::getSOImmVal(~CVal) != -1)
10553 if (Subtarget->isThumb1Only()) {
10554 // This must be a constant between -7 and 7,
10555 // for 3-operand ADD/SUB immediate instructions.
10556 if (CVal >= -7 && CVal < 7)
10558 } else if (Subtarget->isThumb2()) {
10559 // A constant whose negation can be used as an immediate value in a
10560 // data-processing instruction. This can be used in GCC with an "n"
10561 // modifier that prints the negated value, for use with SUB
10562 // instructions. It is not useful otherwise but is implemented for
10564 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10567 // A constant whose negation can be used as an immediate value in a
10568 // data-processing instruction. This can be used in GCC with an "n"
10569 // modifier that prints the negated value, for use with SUB
10570 // instructions. It is not useful otherwise but is implemented for
10572 if (ARM_AM::getSOImmVal(-CVal) != -1)
10578 if (Subtarget->isThumb()) { // FIXME thumb2
10579 // This must be a multiple of 4 between 0 and 1020, for
10580 // ADD sp + immediate.
10581 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10584 // A power of two or a constant between 0 and 32. This is used in
10585 // GCC for the shift amount on shifted register operands, but it is
10586 // useful in general for any shift amounts.
10587 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10593 if (Subtarget->isThumb()) { // FIXME thumb2
10594 // This must be a constant between 0 and 31, for shift amounts.
10595 if (CVal >= 0 && CVal <= 31)
10601 if (Subtarget->isThumb()) { // FIXME thumb2
10602 // This must be a multiple of 4 between -508 and 508, for
10603 // ADD/SUB sp = sp + immediate.
10604 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10609 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10613 if (Result.getNode()) {
10614 Ops.push_back(Result);
10617 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10620 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10621 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10622 unsigned Opcode = Op->getOpcode();
10623 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10624 "Invalid opcode for Div/Rem lowering");
10625 bool isSigned = (Opcode == ISD::SDIVREM);
10626 EVT VT = Op->getValueType(0);
10627 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10630 switch (VT.getSimpleVT().SimpleTy) {
10631 default: llvm_unreachable("Unexpected request for libcall!");
10632 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10633 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10634 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10635 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10638 SDValue InChain = DAG.getEntryNode();
10640 TargetLowering::ArgListTy Args;
10641 TargetLowering::ArgListEntry Entry;
10642 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10643 EVT ArgVT = Op->getOperand(i).getValueType();
10644 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10645 Entry.Node = Op->getOperand(i);
10647 Entry.isSExt = isSigned;
10648 Entry.isZExt = !isSigned;
10649 Args.push_back(Entry);
10652 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10655 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10658 TargetLowering::CallLoweringInfo CLI(DAG);
10659 CLI.setDebugLoc(dl).setChain(InChain)
10660 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10661 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10663 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10664 return CallInfo.first;
10668 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10669 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10673 SDValue Chain = Op.getOperand(0);
10674 SDValue Size = Op.getOperand(1);
10676 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10677 DAG.getConstant(2, MVT::i32));
10680 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10681 Flag = Chain.getValue(1);
10683 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10684 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10686 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10687 Chain = NewSP.getValue(1);
10689 SDValue Ops[2] = { NewSP, Chain };
10690 return DAG.getMergeValues(Ops, DL);
10694 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10695 // The ARM target isn't yet aware of offsets.
10699 bool ARM::isBitFieldInvertedMask(unsigned v) {
10700 if (v == 0xffffffff)
10703 // there can be 1's on either or both "outsides", all the "inside"
10704 // bits must be 0's
10705 unsigned TO = CountTrailingOnes_32(v);
10706 unsigned LO = CountLeadingOnes_32(v);
10707 v = (v >> TO) << TO;
10708 v = (v << LO) >> LO;
10712 /// isFPImmLegal - Returns true if the target can instruction select the
10713 /// specified FP immediate natively. If false, the legalizer will
10714 /// materialize the FP immediate as a load from a constant pool.
10715 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10716 if (!Subtarget->hasVFP3())
10718 if (VT == MVT::f32)
10719 return ARM_AM::getFP32Imm(Imm) != -1;
10720 if (VT == MVT::f64)
10721 return ARM_AM::getFP64Imm(Imm) != -1;
10725 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10726 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10727 /// specified in the intrinsic calls.
10728 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10730 unsigned Intrinsic) const {
10731 switch (Intrinsic) {
10732 case Intrinsic::arm_neon_vld1:
10733 case Intrinsic::arm_neon_vld2:
10734 case Intrinsic::arm_neon_vld3:
10735 case Intrinsic::arm_neon_vld4:
10736 case Intrinsic::arm_neon_vld2lane:
10737 case Intrinsic::arm_neon_vld3lane:
10738 case Intrinsic::arm_neon_vld4lane: {
10739 Info.opc = ISD::INTRINSIC_W_CHAIN;
10740 // Conservatively set memVT to the entire set of vectors loaded.
10741 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10742 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10743 Info.ptrVal = I.getArgOperand(0);
10745 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10746 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10747 Info.vol = false; // volatile loads with NEON intrinsics not supported
10748 Info.readMem = true;
10749 Info.writeMem = false;
10752 case Intrinsic::arm_neon_vst1:
10753 case Intrinsic::arm_neon_vst2:
10754 case Intrinsic::arm_neon_vst3:
10755 case Intrinsic::arm_neon_vst4:
10756 case Intrinsic::arm_neon_vst2lane:
10757 case Intrinsic::arm_neon_vst3lane:
10758 case Intrinsic::arm_neon_vst4lane: {
10759 Info.opc = ISD::INTRINSIC_VOID;
10760 // Conservatively set memVT to the entire set of vectors stored.
10761 unsigned NumElts = 0;
10762 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10763 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10764 if (!ArgTy->isVectorTy())
10766 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10768 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10769 Info.ptrVal = I.getArgOperand(0);
10771 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10772 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10773 Info.vol = false; // volatile stores with NEON intrinsics not supported
10774 Info.readMem = false;
10775 Info.writeMem = true;
10778 case Intrinsic::arm_ldaex:
10779 case Intrinsic::arm_ldrex: {
10780 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10781 Info.opc = ISD::INTRINSIC_W_CHAIN;
10782 Info.memVT = MVT::getVT(PtrTy->getElementType());
10783 Info.ptrVal = I.getArgOperand(0);
10785 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10787 Info.readMem = true;
10788 Info.writeMem = false;
10791 case Intrinsic::arm_stlex:
10792 case Intrinsic::arm_strex: {
10793 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10794 Info.opc = ISD::INTRINSIC_W_CHAIN;
10795 Info.memVT = MVT::getVT(PtrTy->getElementType());
10796 Info.ptrVal = I.getArgOperand(1);
10798 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10800 Info.readMem = false;
10801 Info.writeMem = true;
10804 case Intrinsic::arm_stlexd:
10805 case Intrinsic::arm_strexd: {
10806 Info.opc = ISD::INTRINSIC_W_CHAIN;
10807 Info.memVT = MVT::i64;
10808 Info.ptrVal = I.getArgOperand(2);
10812 Info.readMem = false;
10813 Info.writeMem = true;
10816 case Intrinsic::arm_ldaexd:
10817 case Intrinsic::arm_ldrexd: {
10818 Info.opc = ISD::INTRINSIC_W_CHAIN;
10819 Info.memVT = MVT::i64;
10820 Info.ptrVal = I.getArgOperand(0);
10824 Info.readMem = true;
10825 Info.writeMem = false;
10835 /// \brief Returns true if it is beneficial to convert a load of a constant
10836 /// to just the constant itself.
10837 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10839 assert(Ty->isIntegerTy());
10841 unsigned Bits = Ty->getPrimitiveSizeInBits();
10842 if (Bits == 0 || Bits > 32)
10847 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10848 // Loads and stores less than 64-bits are already atomic; ones above that
10849 // are doomed anyway, so defer to the default libcall and blame the OS when
10850 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10851 // anything for those.
10852 bool IsMClass = Subtarget->isMClass();
10853 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10854 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10855 return Size == 64 && !IsMClass;
10856 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10857 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10860 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10861 // and up to 64 bits on the non-M profiles
10862 unsigned AtomicLimit = IsMClass ? 32 : 64;
10863 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10866 // This has so far only been implemented for MachO.
10867 bool ARMTargetLowering::useLoadStackGuardNode() const {
10868 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10871 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10872 AtomicOrdering Ord) const {
10873 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10874 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10876 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10878 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10879 // intrinsic must return {i32, i32} and we have to recombine them into a
10880 // single i64 here.
10881 if (ValTy->getPrimitiveSizeInBits() == 64) {
10882 Intrinsic::ID Int =
10883 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10884 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10886 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10887 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10889 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10890 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10891 if (!Subtarget->isLittle())
10892 std::swap (Lo, Hi);
10893 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10894 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10895 return Builder.CreateOr(
10896 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10899 Type *Tys[] = { Addr->getType() };
10900 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10901 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10903 return Builder.CreateTruncOrBitCast(
10904 Builder.CreateCall(Ldrex, Addr),
10905 cast<PointerType>(Addr->getType())->getElementType());
10908 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10910 AtomicOrdering Ord) const {
10911 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10913 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10915 // Since the intrinsics must have legal type, the i64 intrinsics take two
10916 // parameters: "i32, i32". We must marshal Val into the appropriate form
10917 // before the call.
10918 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10919 Intrinsic::ID Int =
10920 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10921 Function *Strex = Intrinsic::getDeclaration(M, Int);
10922 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10924 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10925 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10926 if (!Subtarget->isLittle())
10927 std::swap (Lo, Hi);
10928 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10929 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10932 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10933 Type *Tys[] = { Addr->getType() };
10934 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10936 return Builder.CreateCall2(
10937 Strex, Builder.CreateZExtOrBitCast(
10938 Val, Strex->getFunctionType()->getParamType(0)),
10950 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10951 uint64_t &Members) {
10952 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10953 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10954 uint64_t SubMembers = 0;
10955 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10957 Members += SubMembers;
10959 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10960 uint64_t SubMembers = 0;
10961 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10963 Members += SubMembers * AT->getNumElements();
10964 } else if (Ty->isFloatTy()) {
10965 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10969 } else if (Ty->isDoubleTy()) {
10970 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10974 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10981 return VT->getBitWidth() == 64;
10983 return VT->getBitWidth() == 128;
10985 switch (VT->getBitWidth()) {
10998 return (Members > 0 && Members <= 4);
11001 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11002 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11003 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11004 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11005 CallingConv::ARM_AAPCS_VFP)
11008 HABaseType Base = HA_UNKNOWN;
11009 uint64_t Members = 0;
11010 bool result = isHomogeneousAggregate(Ty, Base, Members);
11011 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());