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 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
451 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
452 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
453 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
454 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
455 setTruncStoreAction((MVT::SimpleValueType)VT,
456 (MVT::SimpleValueType)InnerVT, Expand);
457 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
458 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
461 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
462 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
463 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
464 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
466 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
469 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
470 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
472 if (Subtarget->hasNEON()) {
473 addDRTypeForNEON(MVT::v2f32);
474 addDRTypeForNEON(MVT::v8i8);
475 addDRTypeForNEON(MVT::v4i16);
476 addDRTypeForNEON(MVT::v2i32);
477 addDRTypeForNEON(MVT::v1i64);
479 addQRTypeForNEON(MVT::v4f32);
480 addQRTypeForNEON(MVT::v2f64);
481 addQRTypeForNEON(MVT::v16i8);
482 addQRTypeForNEON(MVT::v8i16);
483 addQRTypeForNEON(MVT::v4i32);
484 addQRTypeForNEON(MVT::v2i64);
486 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
487 // neither Neon nor VFP support any arithmetic operations on it.
488 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
489 // supported for v4f32.
490 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
491 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
492 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
493 // FIXME: Code duplication: FDIV and FREM are expanded always, see
494 // ARMTargetLowering::addTypeForNEON method for details.
495 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
496 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
497 // FIXME: Create unittest.
498 // In another words, find a way when "copysign" appears in DAG with vector
500 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
501 // FIXME: Code duplication: SETCC has custom operation action, see
502 // ARMTargetLowering::addTypeForNEON method for details.
503 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FNEG and for FABS.
505 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
506 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
507 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
509 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
510 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
511 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
512 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
513 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
514 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
515 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
516 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
517 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
518 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
519 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
520 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
521 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
522 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
523 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
525 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
527 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
528 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
529 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
530 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
531 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
532 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
533 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
534 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
535 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
536 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
537 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
538 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
539 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
541 // Mark v2f32 intrinsics.
542 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
544 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
545 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
546 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
547 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
548 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
549 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
550 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
551 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
552 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
553 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
554 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
555 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
556 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
558 // Neon does not support some operations on v1i64 and v2i64 types.
559 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
560 // Custom handling for some quad-vector types to detect VMULL.
561 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
562 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
563 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
564 // Custom handling for some vector types to avoid expensive expansions
565 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
566 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
567 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
568 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
569 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
570 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
571 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
572 // a destination type that is wider than the source, and nor does
573 // it have a FP_TO_[SU]INT instruction with a narrower destination than
575 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
576 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
577 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
578 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
580 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
581 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
583 // NEON does not have single instruction CTPOP for vectors with element
584 // types wider than 8-bits. However, custom lowering can leverage the
585 // v8i8/v16i8 vcnt instruction.
586 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
587 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
588 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
589 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
591 // NEON only has FMA instructions as of VFP4.
592 if (!Subtarget->hasVFP4()) {
593 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
594 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
597 setTargetDAGCombine(ISD::INTRINSIC_VOID);
598 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
599 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
600 setTargetDAGCombine(ISD::SHL);
601 setTargetDAGCombine(ISD::SRL);
602 setTargetDAGCombine(ISD::SRA);
603 setTargetDAGCombine(ISD::SIGN_EXTEND);
604 setTargetDAGCombine(ISD::ZERO_EXTEND);
605 setTargetDAGCombine(ISD::ANY_EXTEND);
606 setTargetDAGCombine(ISD::SELECT_CC);
607 setTargetDAGCombine(ISD::BUILD_VECTOR);
608 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
609 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
610 setTargetDAGCombine(ISD::STORE);
611 setTargetDAGCombine(ISD::FP_TO_SINT);
612 setTargetDAGCombine(ISD::FP_TO_UINT);
613 setTargetDAGCombine(ISD::FDIV);
615 // It is legal to extload from v4i8 to v4i16 or v4i32.
616 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
617 MVT::v4i16, MVT::v2i16,
619 for (unsigned i = 0; i < 6; ++i) {
620 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
621 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
622 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
626 // ARM and Thumb2 support UMLAL/SMLAL.
627 if (!Subtarget->isThumb1Only())
628 setTargetDAGCombine(ISD::ADDC);
630 if (Subtarget->isFPOnlySP()) {
631 // When targetting a floating-point unit with only single-precision
632 // operations, f64 is legal for the few double-precision instructions which
633 // are present However, no double-precision operations other than moves,
634 // loads and stores are provided by the hardware.
635 setOperationAction(ISD::FADD, MVT::f64, Expand);
636 setOperationAction(ISD::FSUB, MVT::f64, Expand);
637 setOperationAction(ISD::FMUL, MVT::f64, Expand);
638 setOperationAction(ISD::FMA, MVT::f64, Expand);
639 setOperationAction(ISD::FDIV, MVT::f64, Expand);
640 setOperationAction(ISD::FREM, MVT::f64, Expand);
641 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
642 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
643 setOperationAction(ISD::FNEG, MVT::f64, Expand);
644 setOperationAction(ISD::FABS, MVT::f64, Expand);
645 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
646 setOperationAction(ISD::FSIN, MVT::f64, Expand);
647 setOperationAction(ISD::FCOS, MVT::f64, Expand);
648 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
649 setOperationAction(ISD::FPOW, MVT::f64, Expand);
650 setOperationAction(ISD::FLOG, MVT::f64, Expand);
651 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
652 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
653 setOperationAction(ISD::FEXP, MVT::f64, Expand);
654 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
655 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
656 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
657 setOperationAction(ISD::FRINT, MVT::f64, Expand);
658 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
659 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
660 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
661 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
664 computeRegisterProperties();
666 // ARM does not have floating-point extending loads.
667 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
668 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
670 // ... or truncating stores
671 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
672 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
673 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
675 // ARM does not have i1 sign extending load.
676 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
678 // ARM supports all 4 flavors of integer indexed load / store.
679 if (!Subtarget->isThumb1Only()) {
680 for (unsigned im = (unsigned)ISD::PRE_INC;
681 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
682 setIndexedLoadAction(im, MVT::i1, Legal);
683 setIndexedLoadAction(im, MVT::i8, Legal);
684 setIndexedLoadAction(im, MVT::i16, Legal);
685 setIndexedLoadAction(im, MVT::i32, Legal);
686 setIndexedStoreAction(im, MVT::i1, Legal);
687 setIndexedStoreAction(im, MVT::i8, Legal);
688 setIndexedStoreAction(im, MVT::i16, Legal);
689 setIndexedStoreAction(im, MVT::i32, Legal);
693 setOperationAction(ISD::SADDO, MVT::i32, Custom);
694 setOperationAction(ISD::UADDO, MVT::i32, Custom);
695 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
696 setOperationAction(ISD::USUBO, MVT::i32, Custom);
698 // i64 operation support.
699 setOperationAction(ISD::MUL, MVT::i64, Expand);
700 setOperationAction(ISD::MULHU, MVT::i32, Expand);
701 if (Subtarget->isThumb1Only()) {
702 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
703 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
705 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
706 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
707 setOperationAction(ISD::MULHS, MVT::i32, Expand);
709 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
710 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
711 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
712 setOperationAction(ISD::SRL, MVT::i64, Custom);
713 setOperationAction(ISD::SRA, MVT::i64, Custom);
715 if (!Subtarget->isThumb1Only()) {
716 // FIXME: We should do this for Thumb1 as well.
717 setOperationAction(ISD::ADDC, MVT::i32, Custom);
718 setOperationAction(ISD::ADDE, MVT::i32, Custom);
719 setOperationAction(ISD::SUBC, MVT::i32, Custom);
720 setOperationAction(ISD::SUBE, MVT::i32, Custom);
723 // ARM does not have ROTL.
724 setOperationAction(ISD::ROTL, MVT::i32, Expand);
725 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
726 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
727 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
728 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
730 // These just redirect to CTTZ and CTLZ on ARM.
731 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
732 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
734 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
736 // Only ARMv6 has BSWAP.
737 if (!Subtarget->hasV6Ops())
738 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
740 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
741 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
742 // These are expanded into libcalls if the cpu doesn't have HW divider.
743 setOperationAction(ISD::SDIV, MVT::i32, Expand);
744 setOperationAction(ISD::UDIV, MVT::i32, Expand);
747 // FIXME: Also set divmod for SREM on EABI
748 setOperationAction(ISD::SREM, MVT::i32, Expand);
749 setOperationAction(ISD::UREM, MVT::i32, Expand);
750 if (!Subtarget->isTargetAEABI()) {
751 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
752 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
755 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
756 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
757 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
758 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
759 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
761 setOperationAction(ISD::TRAP, MVT::Other, Legal);
763 // Use the default implementation.
764 setOperationAction(ISD::VASTART, MVT::Other, Custom);
765 setOperationAction(ISD::VAARG, MVT::Other, Expand);
766 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
767 setOperationAction(ISD::VAEND, MVT::Other, Expand);
768 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
769 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
771 if (!Subtarget->isTargetMachO()) {
772 // Non-MachO platforms may return values in these registers via the
773 // personality function.
774 setExceptionPointerRegister(ARM::R0);
775 setExceptionSelectorRegister(ARM::R1);
778 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
779 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
781 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
783 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
784 // the default expansion. If we are targeting a single threaded system,
785 // then set them all for expand so we can lower them later into their
787 if (TM.Options.ThreadModel == ThreadModel::Single)
788 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
789 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
790 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
791 // to ldrex/strex loops already.
792 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
794 // On v8, we have particularly efficient implementations of atomic fences
795 // if they can be combined with nearby atomic loads and stores.
796 if (!Subtarget->hasV8Ops()) {
797 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
798 setInsertFencesForAtomic(true);
801 // If there's anything we can use as a barrier, go through custom lowering
803 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
804 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
806 // Set them all for expansion, which will force libcalls.
807 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
808 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
809 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
810 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
811 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
812 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
813 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
814 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
815 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
816 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
817 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
818 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
819 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
820 // Unordered/Monotonic case.
821 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
822 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
825 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
827 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
828 if (!Subtarget->hasV6Ops()) {
829 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
830 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
832 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
834 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
835 !Subtarget->isThumb1Only()) {
836 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
837 // iff target supports vfp2.
838 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
839 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
842 // We want to custom lower some of our intrinsics.
843 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
844 if (Subtarget->isTargetDarwin()) {
845 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
846 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
847 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
850 setOperationAction(ISD::SETCC, MVT::i32, Expand);
851 setOperationAction(ISD::SETCC, MVT::f32, Expand);
852 setOperationAction(ISD::SETCC, MVT::f64, Expand);
853 setOperationAction(ISD::SELECT, MVT::i32, Custom);
854 setOperationAction(ISD::SELECT, MVT::f32, Custom);
855 setOperationAction(ISD::SELECT, MVT::f64, Custom);
856 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
857 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
858 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
860 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
861 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
862 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
863 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
864 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
866 // We don't support sin/cos/fmod/copysign/pow
867 setOperationAction(ISD::FSIN, MVT::f64, Expand);
868 setOperationAction(ISD::FSIN, MVT::f32, Expand);
869 setOperationAction(ISD::FCOS, MVT::f32, Expand);
870 setOperationAction(ISD::FCOS, MVT::f64, Expand);
871 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
872 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
873 setOperationAction(ISD::FREM, MVT::f64, Expand);
874 setOperationAction(ISD::FREM, MVT::f32, Expand);
875 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
876 !Subtarget->isThumb1Only()) {
877 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
878 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
880 setOperationAction(ISD::FPOW, MVT::f64, Expand);
881 setOperationAction(ISD::FPOW, MVT::f32, Expand);
883 if (!Subtarget->hasVFP4()) {
884 setOperationAction(ISD::FMA, MVT::f64, Expand);
885 setOperationAction(ISD::FMA, MVT::f32, Expand);
888 // Various VFP goodness
889 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
890 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
891 if (Subtarget->hasVFP2()) {
892 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
893 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
894 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
895 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
898 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
899 if (!Subtarget->hasV8Ops()) {
900 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
901 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
904 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
905 if (!Subtarget->hasFP16()) {
906 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
907 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
911 // Combine sin / cos into one node or libcall if possible.
912 if (Subtarget->hasSinCos()) {
913 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
914 setLibcallName(RTLIB::SINCOS_F64, "sincos");
915 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
916 // For iOS, we don't want to the normal expansion of a libcall to
917 // sincos. We want to issue a libcall to __sincos_stret.
918 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
919 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
923 // ARMv8 implements a lot of rounding-like FP operations.
924 if (Subtarget->hasV8Ops()) {
925 static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
926 for (const auto Ty : RoundingTypes) {
927 setOperationAction(ISD::FFLOOR, Ty, Legal);
928 setOperationAction(ISD::FCEIL, Ty, Legal);
929 setOperationAction(ISD::FROUND, Ty, Legal);
930 setOperationAction(ISD::FTRUNC, Ty, Legal);
931 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
932 setOperationAction(ISD::FRINT, Ty, Legal);
935 // We have target-specific dag combine patterns for the following nodes:
936 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
937 setTargetDAGCombine(ISD::ADD);
938 setTargetDAGCombine(ISD::SUB);
939 setTargetDAGCombine(ISD::MUL);
940 setTargetDAGCombine(ISD::AND);
941 setTargetDAGCombine(ISD::OR);
942 setTargetDAGCombine(ISD::XOR);
944 if (Subtarget->hasV6Ops())
945 setTargetDAGCombine(ISD::SRL);
947 setStackPointerRegisterToSaveRestore(ARM::SP);
949 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
950 !Subtarget->hasVFP2())
951 setSchedulingPreference(Sched::RegPressure);
953 setSchedulingPreference(Sched::Hybrid);
955 //// temporary - rewrite interface to use type
956 MaxStoresPerMemset = 8;
957 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
958 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
959 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
960 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
961 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
963 // On ARM arguments smaller than 4 bytes are extended, so all arguments
964 // are at least 4 bytes aligned.
965 setMinStackArgumentAlignment(4);
967 // Prefer likely predicted branches to selects on out-of-order cores.
968 PredictableSelectIsExpensive = Subtarget->isLikeA9();
970 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
973 // FIXME: It might make sense to define the representative register class as the
974 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
975 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
976 // SPR's representative would be DPR_VFP2. This should work well if register
977 // pressure tracking were modified such that a register use would increment the
978 // pressure of the register class's representative and all of it's super
979 // classes' representatives transitively. We have not implemented this because
980 // of the difficulty prior to coalescing of modeling operand register classes
981 // due to the common occurrence of cross class copies and subregister insertions
983 std::pair<const TargetRegisterClass*, uint8_t>
984 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
985 const TargetRegisterClass *RRC = nullptr;
987 switch (VT.SimpleTy) {
989 return TargetLowering::findRepresentativeClass(VT);
990 // Use DPR as representative register class for all floating point
991 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
992 // the cost is 1 for both f32 and f64.
993 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
994 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
995 RRC = &ARM::DPRRegClass;
996 // When NEON is used for SP, only half of the register file is available
997 // because operations that define both SP and DP results will be constrained
998 // to the VFP2 class (D0-D15). We currently model this constraint prior to
999 // coalescing by double-counting the SP regs. See the FIXME above.
1000 if (Subtarget->useNEONForSinglePrecisionFP())
1003 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1004 case MVT::v4f32: case MVT::v2f64:
1005 RRC = &ARM::DPRRegClass;
1009 RRC = &ARM::DPRRegClass;
1013 RRC = &ARM::DPRRegClass;
1017 return std::make_pair(RRC, Cost);
1020 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1022 default: return nullptr;
1023 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1024 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1025 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1026 case ARMISD::CALL: return "ARMISD::CALL";
1027 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1028 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1029 case ARMISD::tCALL: return "ARMISD::tCALL";
1030 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1031 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1032 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1033 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1034 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1035 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1036 case ARMISD::CMP: return "ARMISD::CMP";
1037 case ARMISD::CMN: return "ARMISD::CMN";
1038 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1039 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1040 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1041 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1042 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1044 case ARMISD::CMOV: return "ARMISD::CMOV";
1046 case ARMISD::RBIT: return "ARMISD::RBIT";
1048 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1049 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1050 case ARMISD::SITOF: return "ARMISD::SITOF";
1051 case ARMISD::UITOF: return "ARMISD::UITOF";
1053 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1054 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1055 case ARMISD::RRX: return "ARMISD::RRX";
1057 case ARMISD::ADDC: return "ARMISD::ADDC";
1058 case ARMISD::ADDE: return "ARMISD::ADDE";
1059 case ARMISD::SUBC: return "ARMISD::SUBC";
1060 case ARMISD::SUBE: return "ARMISD::SUBE";
1062 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1063 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1065 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1066 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1068 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1070 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1072 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1074 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1076 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1078 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1080 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1081 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1082 case ARMISD::VCGE: return "ARMISD::VCGE";
1083 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1084 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1085 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1086 case ARMISD::VCGT: return "ARMISD::VCGT";
1087 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1088 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1089 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1090 case ARMISD::VTST: return "ARMISD::VTST";
1092 case ARMISD::VSHL: return "ARMISD::VSHL";
1093 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1094 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1095 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1096 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1097 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1098 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1099 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1100 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1101 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1102 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1103 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1104 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1105 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1106 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1107 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1108 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1109 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1110 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1111 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1112 case ARMISD::VDUP: return "ARMISD::VDUP";
1113 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1114 case ARMISD::VEXT: return "ARMISD::VEXT";
1115 case ARMISD::VREV64: return "ARMISD::VREV64";
1116 case ARMISD::VREV32: return "ARMISD::VREV32";
1117 case ARMISD::VREV16: return "ARMISD::VREV16";
1118 case ARMISD::VZIP: return "ARMISD::VZIP";
1119 case ARMISD::VUZP: return "ARMISD::VUZP";
1120 case ARMISD::VTRN: return "ARMISD::VTRN";
1121 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1122 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1123 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1124 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1125 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1126 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1127 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1128 case ARMISD::FMAX: return "ARMISD::FMAX";
1129 case ARMISD::FMIN: return "ARMISD::FMIN";
1130 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1131 case ARMISD::VMINNM: return "ARMISD::VMIN";
1132 case ARMISD::BFI: return "ARMISD::BFI";
1133 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1134 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1135 case ARMISD::VBSL: return "ARMISD::VBSL";
1136 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1137 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1138 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1139 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1140 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1141 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1142 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1143 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1144 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1145 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1146 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1147 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1148 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1149 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1150 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1151 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1152 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1153 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1154 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1155 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1159 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1160 if (!VT.isVector()) return getPointerTy();
1161 return VT.changeVectorElementTypeToInteger();
1164 /// getRegClassFor - Return the register class that should be used for the
1165 /// specified value type.
1166 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1167 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1168 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1169 // load / store 4 to 8 consecutive D registers.
1170 if (Subtarget->hasNEON()) {
1171 if (VT == MVT::v4i64)
1172 return &ARM::QQPRRegClass;
1173 if (VT == MVT::v8i64)
1174 return &ARM::QQQQPRRegClass;
1176 return TargetLowering::getRegClassFor(VT);
1179 // Create a fast isel object.
1181 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1182 const TargetLibraryInfo *libInfo) const {
1183 return ARM::createFastISel(funcInfo, libInfo);
1186 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1187 /// be used for loads / stores from the global.
1188 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1189 return (Subtarget->isThumb1Only() ? 127 : 4095);
1192 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1193 unsigned NumVals = N->getNumValues();
1195 return Sched::RegPressure;
1197 for (unsigned i = 0; i != NumVals; ++i) {
1198 EVT VT = N->getValueType(i);
1199 if (VT == MVT::Glue || VT == MVT::Other)
1201 if (VT.isFloatingPoint() || VT.isVector())
1205 if (!N->isMachineOpcode())
1206 return Sched::RegPressure;
1208 // Load are scheduled for latency even if there instruction itinerary
1209 // is not available.
1210 const TargetInstrInfo *TII =
1211 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1212 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1214 if (MCID.getNumDefs() == 0)
1215 return Sched::RegPressure;
1216 if (!Itins->isEmpty() &&
1217 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1220 return Sched::RegPressure;
1223 //===----------------------------------------------------------------------===//
1225 //===----------------------------------------------------------------------===//
1227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1230 default: llvm_unreachable("Unknown condition code!");
1231 case ISD::SETNE: return ARMCC::NE;
1232 case ISD::SETEQ: return ARMCC::EQ;
1233 case ISD::SETGT: return ARMCC::GT;
1234 case ISD::SETGE: return ARMCC::GE;
1235 case ISD::SETLT: return ARMCC::LT;
1236 case ISD::SETLE: return ARMCC::LE;
1237 case ISD::SETUGT: return ARMCC::HI;
1238 case ISD::SETUGE: return ARMCC::HS;
1239 case ISD::SETULT: return ARMCC::LO;
1240 case ISD::SETULE: return ARMCC::LS;
1244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1246 ARMCC::CondCodes &CondCode2) {
1247 CondCode2 = ARMCC::AL;
1249 default: llvm_unreachable("Unknown FP condition!");
1251 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1253 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1255 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1256 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1257 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1258 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1259 case ISD::SETO: CondCode = ARMCC::VC; break;
1260 case ISD::SETUO: CondCode = ARMCC::VS; break;
1261 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1262 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1263 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1265 case ISD::SETULT: CondCode = ARMCC::LT; break;
1267 case ISD::SETULE: CondCode = ARMCC::LE; break;
1269 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1273 //===----------------------------------------------------------------------===//
1274 // Calling Convention Implementation
1275 //===----------------------------------------------------------------------===//
1277 #include "ARMGenCallingConv.inc"
1279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1280 /// account presence of floating point hardware and calling convention
1281 /// limitations, such as support for variadic functions.
1283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1284 bool isVarArg) const {
1287 llvm_unreachable("Unsupported calling convention");
1288 case CallingConv::ARM_AAPCS:
1289 case CallingConv::ARM_APCS:
1290 case CallingConv::GHC:
1292 case CallingConv::ARM_AAPCS_VFP:
1293 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1294 case CallingConv::C:
1295 if (!Subtarget->isAAPCS_ABI())
1296 return CallingConv::ARM_APCS;
1297 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1298 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1300 return CallingConv::ARM_AAPCS_VFP;
1302 return CallingConv::ARM_AAPCS;
1303 case CallingConv::Fast:
1304 if (!Subtarget->isAAPCS_ABI()) {
1305 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306 return CallingConv::Fast;
1307 return CallingConv::ARM_APCS;
1308 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1309 return CallingConv::ARM_AAPCS_VFP;
1311 return CallingConv::ARM_AAPCS;
1315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1316 /// CallingConvention.
1317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1319 bool isVarArg) const {
1320 switch (getEffectiveCallingConv(CC, isVarArg)) {
1322 llvm_unreachable("Unsupported calling convention");
1323 case CallingConv::ARM_APCS:
1324 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1325 case CallingConv::ARM_AAPCS:
1326 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1327 case CallingConv::ARM_AAPCS_VFP:
1328 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1329 case CallingConv::Fast:
1330 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1331 case CallingConv::GHC:
1332 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1336 /// LowerCallResult - Lower the result values of a call into the
1337 /// appropriate copies out of appropriate physical registers.
1339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1340 CallingConv::ID CallConv, bool isVarArg,
1341 const SmallVectorImpl<ISD::InputArg> &Ins,
1342 SDLoc dl, SelectionDAG &DAG,
1343 SmallVectorImpl<SDValue> &InVals,
1344 bool isThisReturn, SDValue ThisVal) const {
1346 // Assign locations to each value returned by this call.
1347 SmallVector<CCValAssign, 16> RVLocs;
1348 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1349 *DAG.getContext(), Call);
1350 CCInfo.AnalyzeCallResult(Ins,
1351 CCAssignFnForNode(CallConv, /* Return*/ true,
1354 // Copy all of the result registers out of their specified physreg.
1355 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356 CCValAssign VA = RVLocs[i];
1358 // Pass 'this' value directly from the argument to return value, to avoid
1359 // reg unit interference
1360 if (i == 0 && isThisReturn) {
1361 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1362 "unexpected return calling convention register assignment");
1363 InVals.push_back(ThisVal);
1368 if (VA.needsCustom()) {
1369 // Handle f64 or half of a v2f64.
1370 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1372 Chain = Lo.getValue(1);
1373 InFlag = Lo.getValue(2);
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1377 Chain = Hi.getValue(1);
1378 InFlag = Hi.getValue(2);
1379 if (!Subtarget->isLittle())
1381 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1383 if (VA.getLocVT() == MVT::v2f64) {
1384 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1385 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(0, MVT::i32));
1388 VA = RVLocs[++i]; // skip ahead to next loc
1389 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1390 Chain = Lo.getValue(1);
1391 InFlag = Lo.getValue(2);
1392 VA = RVLocs[++i]; // skip ahead to next loc
1393 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1394 Chain = Hi.getValue(1);
1395 InFlag = Hi.getValue(2);
1396 if (!Subtarget->isLittle())
1398 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1399 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1400 DAG.getConstant(1, MVT::i32));
1403 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1405 Chain = Val.getValue(1);
1406 InFlag = Val.getValue(2);
1409 switch (VA.getLocInfo()) {
1410 default: llvm_unreachable("Unknown loc info!");
1411 case CCValAssign::Full: break;
1412 case CCValAssign::BCvt:
1413 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1417 InVals.push_back(Val);
1423 /// LowerMemOpCallTo - Store the argument to the stack.
1425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1426 SDValue StackPtr, SDValue Arg,
1427 SDLoc dl, SelectionDAG &DAG,
1428 const CCValAssign &VA,
1429 ISD::ArgFlagsTy Flags) const {
1430 unsigned LocMemOffset = VA.getLocMemOffset();
1431 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1432 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1433 return DAG.getStore(Chain, dl, Arg, PtrOff,
1434 MachinePointerInfo::getStack(LocMemOffset),
1438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1439 SDValue Chain, SDValue &Arg,
1440 RegsToPassVector &RegsToPass,
1441 CCValAssign &VA, CCValAssign &NextVA,
1443 SmallVectorImpl<SDValue> &MemOpChains,
1444 ISD::ArgFlagsTy Flags) const {
1446 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1447 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1448 unsigned id = Subtarget->isLittle() ? 0 : 1;
1449 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1451 if (NextVA.isRegLoc())
1452 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1454 assert(NextVA.isMemLoc());
1455 if (!StackPtr.getNode())
1456 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1458 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1464 /// LowerCall - Lowering a call into a callseq_start <-
1465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469 SmallVectorImpl<SDValue> &InVals) const {
1470 SelectionDAG &DAG = CLI.DAG;
1472 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1473 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1474 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1475 SDValue Chain = CLI.Chain;
1476 SDValue Callee = CLI.Callee;
1477 bool &isTailCall = CLI.IsTailCall;
1478 CallingConv::ID CallConv = CLI.CallConv;
1479 bool doesNotRet = CLI.DoesNotReturn;
1480 bool isVarArg = CLI.IsVarArg;
1482 MachineFunction &MF = DAG.getMachineFunction();
1483 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1484 bool isThisReturn = false;
1485 bool isSibCall = false;
1487 // Disable tail calls if they're not supported.
1488 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1492 // Check if it's really possible to do a tail call.
1493 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1494 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1495 Outs, OutVals, Ins, DAG);
1496 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1497 report_fatal_error("failed to perform tail call elimination on a call "
1498 "site marked musttail");
1499 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1500 // detected sibcalls.
1507 // Analyze operands of the call, assigning locations to each operand.
1508 SmallVector<CCValAssign, 16> ArgLocs;
1509 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1510 *DAG.getContext(), Call);
1511 CCInfo.AnalyzeCallOperands(Outs,
1512 CCAssignFnForNode(CallConv, /* Return*/ false,
1515 // Get a count of how many bytes are to be pushed on the stack.
1516 unsigned NumBytes = CCInfo.getNextStackOffset();
1518 // For tail calls, memory operands are available in our caller's stack.
1522 // Adjust the stack pointer for the new arguments...
1523 // These operations are automatically eliminated by the prolog/epilog pass
1525 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1528 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1530 RegsToPassVector RegsToPass;
1531 SmallVector<SDValue, 8> MemOpChains;
1533 // Walk the register/memloc assignments, inserting copies/loads. In the case
1534 // of tail call optimization, arguments are handled later.
1535 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1537 ++i, ++realArgIdx) {
1538 CCValAssign &VA = ArgLocs[i];
1539 SDValue Arg = OutVals[realArgIdx];
1540 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1541 bool isByVal = Flags.isByVal();
1543 // Promote the value if needed.
1544 switch (VA.getLocInfo()) {
1545 default: llvm_unreachable("Unknown loc info!");
1546 case CCValAssign::Full: break;
1547 case CCValAssign::SExt:
1548 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1550 case CCValAssign::ZExt:
1551 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1553 case CCValAssign::AExt:
1554 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1556 case CCValAssign::BCvt:
1557 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1561 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1562 if (VA.needsCustom()) {
1563 if (VA.getLocVT() == MVT::v2f64) {
1564 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1565 DAG.getConstant(0, MVT::i32));
1566 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1567 DAG.getConstant(1, MVT::i32));
1569 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1570 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1572 VA = ArgLocs[++i]; // skip ahead to next loc
1573 if (VA.isRegLoc()) {
1574 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1575 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1577 assert(VA.isMemLoc());
1579 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1580 dl, DAG, VA, Flags));
1583 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1584 StackPtr, MemOpChains, Flags);
1586 } else if (VA.isRegLoc()) {
1587 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1588 assert(VA.getLocVT() == MVT::i32 &&
1589 "unexpected calling convention register assignment");
1590 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1591 "unexpected use of 'returned'");
1592 isThisReturn = true;
1594 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1595 } else if (isByVal) {
1596 assert(VA.isMemLoc());
1597 unsigned offset = 0;
1599 // True if this byval aggregate will be split between registers
1601 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1602 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1604 if (CurByValIdx < ByValArgsCount) {
1606 unsigned RegBegin, RegEnd;
1607 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1609 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1611 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1612 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1613 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1614 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1615 MachinePointerInfo(),
1616 false, false, false,
1617 DAG.InferPtrAlignment(AddArg));
1618 MemOpChains.push_back(Load.getValue(1));
1619 RegsToPass.push_back(std::make_pair(j, Load));
1622 // If parameter size outsides register area, "offset" value
1623 // helps us to calculate stack slot for remained part properly.
1624 offset = RegEnd - RegBegin;
1626 CCInfo.nextInRegsParam();
1629 if (Flags.getByValSize() > 4*offset) {
1630 unsigned LocMemOffset = VA.getLocMemOffset();
1631 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1632 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1634 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1635 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1636 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1638 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1640 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1641 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1642 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1645 } else if (!isSibCall) {
1646 assert(VA.isMemLoc());
1648 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1649 dl, DAG, VA, Flags));
1653 if (!MemOpChains.empty())
1654 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1656 // Build a sequence of copy-to-reg nodes chained together with token chain
1657 // and flag operands which copy the outgoing args into the appropriate regs.
1659 // Tail call byval lowering might overwrite argument registers so in case of
1660 // tail call optimization the copies to registers are lowered later.
1662 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1663 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1664 RegsToPass[i].second, InFlag);
1665 InFlag = Chain.getValue(1);
1668 // For tail calls lower the arguments to the 'real' stack slot.
1670 // Force all the incoming stack arguments to be loaded from the stack
1671 // before any new outgoing arguments are stored to the stack, because the
1672 // outgoing stack slots may alias the incoming argument stack slots, and
1673 // the alias isn't otherwise explicit. This is slightly more conservative
1674 // than necessary, because it means that each store effectively depends
1675 // on every argument instead of just those arguments it would clobber.
1677 // Do not flag preceding copytoreg stuff together with the following stuff.
1679 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1680 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1681 RegsToPass[i].second, InFlag);
1682 InFlag = Chain.getValue(1);
1687 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1688 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1689 // node so that legalize doesn't hack it.
1690 bool isDirect = false;
1691 bool isARMFunc = false;
1692 bool isLocalARMFunc = false;
1693 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1695 if (EnableARMLongCalls) {
1696 assert((Subtarget->isTargetWindows() ||
1697 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1698 "long-calls with non-static relocation model!");
1699 // Handle a global address or an external symbol. If it's not one of
1700 // those, the target's already in a register, so we don't need to do
1702 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1703 const GlobalValue *GV = G->getGlobal();
1704 // Create a constant pool entry for the callee address
1705 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706 ARMConstantPoolValue *CPV =
1707 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1709 // Get the address of the callee into a register
1710 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1711 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1712 Callee = DAG.getLoad(getPointerTy(), dl,
1713 DAG.getEntryNode(), CPAddr,
1714 MachinePointerInfo::getConstantPool(),
1715 false, false, false, 0);
1716 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1717 const char *Sym = S->getSymbol();
1719 // Create a constant pool entry for the callee address
1720 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1721 ARMConstantPoolValue *CPV =
1722 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1723 ARMPCLabelIndex, 0);
1724 // Get the address of the callee into a register
1725 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1726 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1727 Callee = DAG.getLoad(getPointerTy(), dl,
1728 DAG.getEntryNode(), CPAddr,
1729 MachinePointerInfo::getConstantPool(),
1730 false, false, false, 0);
1732 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1733 const GlobalValue *GV = G->getGlobal();
1735 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1736 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1737 getTargetMachine().getRelocationModel() != Reloc::Static;
1738 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1739 // ARM call to a local ARM function is predicable.
1740 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1741 // tBX takes a register source operand.
1742 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1743 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1744 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1745 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1746 0, ARMII::MO_NONLAZY));
1747 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1748 MachinePointerInfo::getGOT(), false, false, true, 0);
1749 } else if (Subtarget->isTargetCOFF()) {
1750 assert(Subtarget->isTargetWindows() &&
1751 "Windows is the only supported COFF target");
1752 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1753 ? ARMII::MO_DLLIMPORT
1754 : ARMII::MO_NO_FLAG;
1755 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1757 if (GV->hasDLLImportStorageClass())
1758 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1759 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1760 Callee), MachinePointerInfo::getGOT(),
1761 false, false, false, 0);
1763 // On ELF targets for PIC code, direct calls should go through the PLT
1764 unsigned OpFlags = 0;
1765 if (Subtarget->isTargetELF() &&
1766 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1767 OpFlags = ARMII::MO_PLT;
1768 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1770 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1772 bool isStub = Subtarget->isTargetMachO() &&
1773 getTargetMachine().getRelocationModel() != Reloc::Static;
1774 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1775 // tBX takes a register source operand.
1776 const char *Sym = S->getSymbol();
1777 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1778 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1779 ARMConstantPoolValue *CPV =
1780 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1781 ARMPCLabelIndex, 4);
1782 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1783 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1784 Callee = DAG.getLoad(getPointerTy(), dl,
1785 DAG.getEntryNode(), CPAddr,
1786 MachinePointerInfo::getConstantPool(),
1787 false, false, false, 0);
1788 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1789 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1790 getPointerTy(), Callee, PICLabel);
1792 unsigned OpFlags = 0;
1793 // On ELF targets for PIC code, direct calls should go through the PLT
1794 if (Subtarget->isTargetELF() &&
1795 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1796 OpFlags = ARMII::MO_PLT;
1797 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1801 // FIXME: handle tail calls differently.
1803 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1804 AttributeSet::FunctionIndex, Attribute::MinSize);
1805 if (Subtarget->isThumb()) {
1806 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1807 CallOpc = ARMISD::CALL_NOLINK;
1809 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1811 if (!isDirect && !Subtarget->hasV5TOps())
1812 CallOpc = ARMISD::CALL_NOLINK;
1813 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1814 // Emit regular call when code size is the priority
1816 // "mov lr, pc; b _foo" to avoid confusing the RSP
1817 CallOpc = ARMISD::CALL_NOLINK;
1819 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1822 std::vector<SDValue> Ops;
1823 Ops.push_back(Chain);
1824 Ops.push_back(Callee);
1826 // Add argument registers to the end of the list so that they are known live
1828 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1829 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1830 RegsToPass[i].second.getValueType()));
1832 // Add a register mask operand representing the call-preserved registers.
1834 const uint32_t *Mask;
1835 const TargetRegisterInfo *TRI =
1836 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1837 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1839 // For 'this' returns, use the R0-preserving mask if applicable
1840 Mask = ARI->getThisReturnPreservedMask(CallConv);
1842 // Set isThisReturn to false if the calling convention is not one that
1843 // allows 'returned' to be modeled in this way, so LowerCallResult does
1844 // not try to pass 'this' straight through
1845 isThisReturn = false;
1846 Mask = ARI->getCallPreservedMask(CallConv);
1849 Mask = ARI->getCallPreservedMask(CallConv);
1851 assert(Mask && "Missing call preserved mask for calling convention");
1852 Ops.push_back(DAG.getRegisterMask(Mask));
1855 if (InFlag.getNode())
1856 Ops.push_back(InFlag);
1858 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1860 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1862 // Returns a chain and a flag for retval copy to use.
1863 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1864 InFlag = Chain.getValue(1);
1866 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1867 DAG.getIntPtrConstant(0, true), InFlag, dl);
1869 InFlag = Chain.getValue(1);
1871 // Handle result values, copying them out of physregs into vregs that we
1873 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1874 InVals, isThisReturn,
1875 isThisReturn ? OutVals[0] : SDValue());
1878 /// HandleByVal - Every parameter *after* a byval parameter is passed
1879 /// on the stack. Remember the next parameter register to allocate,
1880 /// and then confiscate the rest of the parameter registers to insure
1883 ARMTargetLowering::HandleByVal(
1884 CCState *State, unsigned &size, unsigned Align) const {
1885 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1886 assert((State->getCallOrPrologue() == Prologue ||
1887 State->getCallOrPrologue() == Call) &&
1888 "unhandled ParmContext");
1890 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1891 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1892 unsigned AlignInRegs = Align / 4;
1893 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1894 for (unsigned i = 0; i < Waste; ++i)
1895 reg = State->AllocateReg(GPRArgRegs, 4);
1898 unsigned excess = 4 * (ARM::R4 - reg);
1900 // Special case when NSAA != SP and parameter size greater than size of
1901 // all remained GPR regs. In that case we can't split parameter, we must
1902 // send it to stack. We also must set NCRN to R4, so waste all
1903 // remained registers.
1904 const unsigned NSAAOffset = State->getNextStackOffset();
1905 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1906 while (State->AllocateReg(GPRArgRegs, 4))
1911 // First register for byval parameter is the first register that wasn't
1912 // allocated before this method call, so it would be "reg".
1913 // If parameter is small enough to be saved in range [reg, r4), then
1914 // the end (first after last) register would be reg + param-size-in-regs,
1915 // else parameter would be splitted between registers and stack,
1916 // end register would be r4 in this case.
1917 unsigned ByValRegBegin = reg;
1918 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1919 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1920 // Note, first register is allocated in the beginning of function already,
1921 // allocate remained amount of registers we need.
1922 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1923 State->AllocateReg(GPRArgRegs, 4);
1924 // A byval parameter that is split between registers and memory needs its
1925 // size truncated here.
1926 // In the case where the entire structure fits in registers, we set the
1927 // size in memory to zero.
1936 /// MatchingStackOffset - Return true if the given stack call argument is
1937 /// already available in the same position (relatively) of the caller's
1938 /// incoming argument stack.
1940 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1941 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1942 const TargetInstrInfo *TII) {
1943 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1945 if (Arg.getOpcode() == ISD::CopyFromReg) {
1946 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1947 if (!TargetRegisterInfo::isVirtualRegister(VR))
1949 MachineInstr *Def = MRI->getVRegDef(VR);
1952 if (!Flags.isByVal()) {
1953 if (!TII->isLoadFromStackSlot(Def, FI))
1958 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1959 if (Flags.isByVal())
1960 // ByVal argument is passed in as a pointer but it's now being
1961 // dereferenced. e.g.
1962 // define @foo(%struct.X* %A) {
1963 // tail call @bar(%struct.X* byval %A)
1966 SDValue Ptr = Ld->getBasePtr();
1967 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1970 FI = FINode->getIndex();
1974 assert(FI != INT_MAX);
1975 if (!MFI->isFixedObjectIndex(FI))
1977 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1980 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1981 /// for tail call optimization. Targets which want to do tail call
1982 /// optimization should implement this function.
1984 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1985 CallingConv::ID CalleeCC,
1987 bool isCalleeStructRet,
1988 bool isCallerStructRet,
1989 const SmallVectorImpl<ISD::OutputArg> &Outs,
1990 const SmallVectorImpl<SDValue> &OutVals,
1991 const SmallVectorImpl<ISD::InputArg> &Ins,
1992 SelectionDAG& DAG) const {
1993 const Function *CallerF = DAG.getMachineFunction().getFunction();
1994 CallingConv::ID CallerCC = CallerF->getCallingConv();
1995 bool CCMatch = CallerCC == CalleeCC;
1997 // Look for obvious safe cases to perform tail call optimization that do not
1998 // require ABI changes. This is what gcc calls sibcall.
2000 // Do not sibcall optimize vararg calls unless the call site is not passing
2002 if (isVarArg && !Outs.empty())
2005 // Exception-handling functions need a special set of instructions to indicate
2006 // a return to the hardware. Tail-calling another function would probably
2008 if (CallerF->hasFnAttribute("interrupt"))
2011 // Also avoid sibcall optimization if either caller or callee uses struct
2012 // return semantics.
2013 if (isCalleeStructRet || isCallerStructRet)
2016 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2017 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2018 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2019 // support in the assembler and linker to be used. This would need to be
2020 // fixed to fully support tail calls in Thumb1.
2022 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2023 // LR. This means if we need to reload LR, it takes an extra instructions,
2024 // which outweighs the value of the tail call; but here we don't know yet
2025 // whether LR is going to be used. Probably the right approach is to
2026 // generate the tail call here and turn it back into CALL/RET in
2027 // emitEpilogue if LR is used.
2029 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2030 // but we need to make sure there are enough registers; the only valid
2031 // registers are the 4 used for parameters. We don't currently do this
2033 if (Subtarget->isThumb1Only())
2036 // Externally-defined functions with weak linkage should not be
2037 // tail-called on ARM when the OS does not support dynamic
2038 // pre-emption of symbols, as the AAELF spec requires normal calls
2039 // to undefined weak functions to be replaced with a NOP or jump to the
2040 // next instruction. The behaviour of branch instructions in this
2041 // situation (as used for tail calls) is implementation-defined, so we
2042 // cannot rely on the linker replacing the tail call with a return.
2043 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2044 const GlobalValue *GV = G->getGlobal();
2045 if (GV->hasExternalWeakLinkage())
2049 // If the calling conventions do not match, then we'd better make sure the
2050 // results are returned in the same way as what the caller expects.
2052 SmallVector<CCValAssign, 16> RVLocs1;
2053 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2054 *DAG.getContext(), Call);
2055 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2057 SmallVector<CCValAssign, 16> RVLocs2;
2058 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2059 *DAG.getContext(), Call);
2060 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2062 if (RVLocs1.size() != RVLocs2.size())
2064 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2065 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2067 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2069 if (RVLocs1[i].isRegLoc()) {
2070 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2073 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2079 // If Caller's vararg or byval argument has been split between registers and
2080 // stack, do not perform tail call, since part of the argument is in caller's
2082 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2083 getInfo<ARMFunctionInfo>();
2084 if (AFI_Caller->getArgRegsSaveSize())
2087 // If the callee takes no arguments then go on to check the results of the
2089 if (!Outs.empty()) {
2090 // Check if stack adjustment is needed. For now, do not do this if any
2091 // argument is passed on the stack.
2092 SmallVector<CCValAssign, 16> ArgLocs;
2093 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2094 *DAG.getContext(), Call);
2095 CCInfo.AnalyzeCallOperands(Outs,
2096 CCAssignFnForNode(CalleeCC, false, isVarArg));
2097 if (CCInfo.getNextStackOffset()) {
2098 MachineFunction &MF = DAG.getMachineFunction();
2100 // Check if the arguments are already laid out in the right way as
2101 // the caller's fixed stack objects.
2102 MachineFrameInfo *MFI = MF.getFrameInfo();
2103 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2104 const TargetInstrInfo *TII =
2105 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2106 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2108 ++i, ++realArgIdx) {
2109 CCValAssign &VA = ArgLocs[i];
2110 EVT RegVT = VA.getLocVT();
2111 SDValue Arg = OutVals[realArgIdx];
2112 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2113 if (VA.getLocInfo() == CCValAssign::Indirect)
2115 if (VA.needsCustom()) {
2116 // f64 and vector types are split into multiple registers or
2117 // register/stack-slot combinations. The types will not match
2118 // the registers; give up on memory f64 refs until we figure
2119 // out what to do about this.
2122 if (!ArgLocs[++i].isRegLoc())
2124 if (RegVT == MVT::v2f64) {
2125 if (!ArgLocs[++i].isRegLoc())
2127 if (!ArgLocs[++i].isRegLoc())
2130 } else if (!VA.isRegLoc()) {
2131 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2143 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2144 MachineFunction &MF, bool isVarArg,
2145 const SmallVectorImpl<ISD::OutputArg> &Outs,
2146 LLVMContext &Context) const {
2147 SmallVector<CCValAssign, 16> RVLocs;
2148 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2149 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2153 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2154 SDLoc DL, SelectionDAG &DAG) {
2155 const MachineFunction &MF = DAG.getMachineFunction();
2156 const Function *F = MF.getFunction();
2158 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2160 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2161 // version of the "preferred return address". These offsets affect the return
2162 // instruction if this is a return from PL1 without hypervisor extensions.
2163 // IRQ/FIQ: +4 "subs pc, lr, #4"
2164 // SWI: 0 "subs pc, lr, #0"
2165 // ABORT: +4 "subs pc, lr, #4"
2166 // UNDEF: +4/+2 "subs pc, lr, #0"
2167 // UNDEF varies depending on where the exception came from ARM or Thumb
2168 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2171 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2174 else if (IntKind == "SWI" || IntKind == "UNDEF")
2177 report_fatal_error("Unsupported interrupt attribute. If present, value "
2178 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2180 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2182 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2186 ARMTargetLowering::LowerReturn(SDValue Chain,
2187 CallingConv::ID CallConv, bool isVarArg,
2188 const SmallVectorImpl<ISD::OutputArg> &Outs,
2189 const SmallVectorImpl<SDValue> &OutVals,
2190 SDLoc dl, SelectionDAG &DAG) const {
2192 // CCValAssign - represent the assignment of the return value to a location.
2193 SmallVector<CCValAssign, 16> RVLocs;
2195 // CCState - Info about the registers and stack slots.
2196 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2197 *DAG.getContext(), Call);
2199 // Analyze outgoing return values.
2200 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2204 SmallVector<SDValue, 4> RetOps;
2205 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2206 bool isLittleEndian = Subtarget->isLittle();
2208 MachineFunction &MF = DAG.getMachineFunction();
2209 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2210 AFI->setReturnRegsCount(RVLocs.size());
2212 // Copy the result values into the output registers.
2213 for (unsigned i = 0, realRVLocIdx = 0;
2215 ++i, ++realRVLocIdx) {
2216 CCValAssign &VA = RVLocs[i];
2217 assert(VA.isRegLoc() && "Can only return in registers!");
2219 SDValue Arg = OutVals[realRVLocIdx];
2221 switch (VA.getLocInfo()) {
2222 default: llvm_unreachable("Unknown loc info!");
2223 case CCValAssign::Full: break;
2224 case CCValAssign::BCvt:
2225 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2229 if (VA.needsCustom()) {
2230 if (VA.getLocVT() == MVT::v2f64) {
2231 // Extract the first half and return it in two registers.
2232 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2233 DAG.getConstant(0, MVT::i32));
2234 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2235 DAG.getVTList(MVT::i32, MVT::i32), Half);
2237 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2238 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2240 Flag = Chain.getValue(1);
2241 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2242 VA = RVLocs[++i]; // skip ahead to next loc
2243 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2246 Flag = Chain.getValue(1);
2247 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2248 VA = RVLocs[++i]; // skip ahead to next loc
2250 // Extract the 2nd half and fall through to handle it as an f64 value.
2251 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2252 DAG.getConstant(1, MVT::i32));
2254 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2256 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2257 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2258 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2259 fmrrd.getValue(isLittleEndian ? 0 : 1),
2261 Flag = Chain.getValue(1);
2262 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2263 VA = RVLocs[++i]; // skip ahead to next loc
2264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2265 fmrrd.getValue(isLittleEndian ? 1 : 0),
2268 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2270 // Guarantee that all emitted copies are
2271 // stuck together, avoiding something bad.
2272 Flag = Chain.getValue(1);
2273 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2276 // Update chain and glue.
2279 RetOps.push_back(Flag);
2281 // CPUs which aren't M-class use a special sequence to return from
2282 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2283 // though we use "subs pc, lr, #N").
2285 // M-class CPUs actually use a normal return sequence with a special
2286 // (hardware-provided) value in LR, so the normal code path works.
2287 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2288 !Subtarget->isMClass()) {
2289 if (Subtarget->isThumb1Only())
2290 report_fatal_error("interrupt attribute is not supported in Thumb1");
2291 return LowerInterruptReturn(RetOps, dl, DAG);
2294 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2297 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2298 if (N->getNumValues() != 1)
2300 if (!N->hasNUsesOfValue(1, 0))
2303 SDValue TCChain = Chain;
2304 SDNode *Copy = *N->use_begin();
2305 if (Copy->getOpcode() == ISD::CopyToReg) {
2306 // If the copy has a glue operand, we conservatively assume it isn't safe to
2307 // perform a tail call.
2308 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2310 TCChain = Copy->getOperand(0);
2311 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2312 SDNode *VMov = Copy;
2313 // f64 returned in a pair of GPRs.
2314 SmallPtrSet<SDNode*, 2> Copies;
2315 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2317 if (UI->getOpcode() != ISD::CopyToReg)
2321 if (Copies.size() > 2)
2324 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2326 SDValue UseChain = UI->getOperand(0);
2327 if (Copies.count(UseChain.getNode()))
2334 } else if (Copy->getOpcode() == ISD::BITCAST) {
2335 // f32 returned in a single GPR.
2336 if (!Copy->hasOneUse())
2338 Copy = *Copy->use_begin();
2339 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2341 TCChain = Copy->getOperand(0);
2346 bool HasRet = false;
2347 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2349 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2350 UI->getOpcode() != ARMISD::INTRET_FLAG)
2362 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2363 if (!Subtarget->supportsTailCall())
2366 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2369 return !Subtarget->isThumb1Only();
2372 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2373 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2374 // one of the above mentioned nodes. It has to be wrapped because otherwise
2375 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2376 // be used to form addressing mode. These wrapped nodes will be selected
2378 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2379 EVT PtrVT = Op.getValueType();
2380 // FIXME there is no actual debug info here
2382 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2384 if (CP->isMachineConstantPoolEntry())
2385 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2386 CP->getAlignment());
2388 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2389 CP->getAlignment());
2390 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2393 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2394 return MachineJumpTableInfo::EK_Inline;
2397 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2398 SelectionDAG &DAG) const {
2399 MachineFunction &MF = DAG.getMachineFunction();
2400 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2401 unsigned ARMPCLabelIndex = 0;
2403 EVT PtrVT = getPointerTy();
2404 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2405 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2407 if (RelocM == Reloc::Static) {
2408 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2410 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2411 ARMPCLabelIndex = AFI->createPICLabelUId();
2412 ARMConstantPoolValue *CPV =
2413 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2414 ARMCP::CPBlockAddress, PCAdj);
2415 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2418 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2419 MachinePointerInfo::getConstantPool(),
2420 false, false, false, 0);
2421 if (RelocM == Reloc::Static)
2423 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2424 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2427 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2429 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2430 SelectionDAG &DAG) const {
2432 EVT PtrVT = getPointerTy();
2433 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2434 MachineFunction &MF = DAG.getMachineFunction();
2435 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2436 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2437 ARMConstantPoolValue *CPV =
2438 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2439 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2440 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2441 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2442 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2443 MachinePointerInfo::getConstantPool(),
2444 false, false, false, 0);
2445 SDValue Chain = Argument.getValue(1);
2447 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2448 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2450 // call __tls_get_addr.
2453 Entry.Node = Argument;
2454 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2455 Args.push_back(Entry);
2457 // FIXME: is there useful debug info available here?
2458 TargetLowering::CallLoweringInfo CLI(DAG);
2459 CLI.setDebugLoc(dl).setChain(Chain)
2460 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2461 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2464 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2465 return CallResult.first;
2468 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2469 // "local exec" model.
2471 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2473 TLSModel::Model model) const {
2474 const GlobalValue *GV = GA->getGlobal();
2477 SDValue Chain = DAG.getEntryNode();
2478 EVT PtrVT = getPointerTy();
2479 // Get the Thread Pointer
2480 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2482 if (model == TLSModel::InitialExec) {
2483 MachineFunction &MF = DAG.getMachineFunction();
2484 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2485 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2486 // Initial exec model.
2487 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2488 ARMConstantPoolValue *CPV =
2489 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2490 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2492 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2493 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2494 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2495 MachinePointerInfo::getConstantPool(),
2496 false, false, false, 0);
2497 Chain = Offset.getValue(1);
2499 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2500 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2502 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2503 MachinePointerInfo::getConstantPool(),
2504 false, false, false, 0);
2507 assert(model == TLSModel::LocalExec);
2508 ARMConstantPoolValue *CPV =
2509 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2510 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2511 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2512 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2513 MachinePointerInfo::getConstantPool(),
2514 false, false, false, 0);
2517 // The address of the thread local variable is the add of the thread
2518 // pointer with the offset of the variable.
2519 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2523 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2524 // TODO: implement the "local dynamic" model
2525 assert(Subtarget->isTargetELF() &&
2526 "TLS not implemented for non-ELF targets");
2527 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2529 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2532 case TLSModel::GeneralDynamic:
2533 case TLSModel::LocalDynamic:
2534 return LowerToTLSGeneralDynamicModel(GA, DAG);
2535 case TLSModel::InitialExec:
2536 case TLSModel::LocalExec:
2537 return LowerToTLSExecModels(GA, DAG, model);
2539 llvm_unreachable("bogus TLS model");
2542 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2543 SelectionDAG &DAG) const {
2544 EVT PtrVT = getPointerTy();
2546 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2547 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2548 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2549 ARMConstantPoolValue *CPV =
2550 ARMConstantPoolConstant::Create(GV,
2551 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2552 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2553 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2554 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2556 MachinePointerInfo::getConstantPool(),
2557 false, false, false, 0);
2558 SDValue Chain = Result.getValue(1);
2559 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2560 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2562 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2563 MachinePointerInfo::getGOT(),
2564 false, false, false, 0);
2568 // If we have T2 ops, we can materialize the address directly via movt/movw
2569 // pair. This is always cheaper.
2570 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2572 // FIXME: Once remat is capable of dealing with instructions with register
2573 // operands, expand this into two nodes.
2574 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2575 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2577 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2578 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2579 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2580 MachinePointerInfo::getConstantPool(),
2581 false, false, false, 0);
2585 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2586 SelectionDAG &DAG) const {
2587 EVT PtrVT = getPointerTy();
2589 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2590 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2592 if (Subtarget->useMovt(DAG.getMachineFunction()))
2595 // FIXME: Once remat is capable of dealing with instructions with register
2596 // operands, expand this into multiple nodes
2598 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2600 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2601 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2603 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2604 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2605 MachinePointerInfo::getGOT(), false, false, false, 0);
2609 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2610 SelectionDAG &DAG) const {
2611 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2612 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2613 "Windows on ARM expects to use movw/movt");
2615 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2616 const ARMII::TOF TargetFlags =
2617 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2618 EVT PtrVT = getPointerTy();
2624 // FIXME: Once remat is capable of dealing with instructions with register
2625 // operands, expand this into two nodes.
2626 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2627 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2629 if (GV->hasDLLImportStorageClass())
2630 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2631 MachinePointerInfo::getGOT(), false, false, false, 0);
2635 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2636 SelectionDAG &DAG) const {
2637 assert(Subtarget->isTargetELF() &&
2638 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2639 MachineFunction &MF = DAG.getMachineFunction();
2640 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2641 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2642 EVT PtrVT = getPointerTy();
2644 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2645 ARMConstantPoolValue *CPV =
2646 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2647 ARMPCLabelIndex, PCAdj);
2648 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2649 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651 MachinePointerInfo::getConstantPool(),
2652 false, false, false, 0);
2653 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2654 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2658 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2660 SDValue Val = DAG.getConstant(0, MVT::i32);
2661 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2662 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2663 Op.getOperand(1), Val);
2667 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2669 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2670 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2674 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2675 const ARMSubtarget *Subtarget) const {
2676 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2679 default: return SDValue(); // Don't custom lower most intrinsics.
2680 case Intrinsic::arm_rbit: {
2681 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2682 "RBIT intrinsic must have i32 type!");
2683 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2685 case Intrinsic::arm_thread_pointer: {
2686 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2687 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2689 case Intrinsic::eh_sjlj_lsda: {
2690 MachineFunction &MF = DAG.getMachineFunction();
2691 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2692 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2693 EVT PtrVT = getPointerTy();
2694 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2696 unsigned PCAdj = (RelocM != Reloc::PIC_)
2697 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2698 ARMConstantPoolValue *CPV =
2699 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2700 ARMCP::CPLSDA, PCAdj);
2701 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2702 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2704 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2705 MachinePointerInfo::getConstantPool(),
2706 false, false, false, 0);
2708 if (RelocM == Reloc::PIC_) {
2709 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2710 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2714 case Intrinsic::arm_neon_vmulls:
2715 case Intrinsic::arm_neon_vmullu: {
2716 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2717 ? ARMISD::VMULLs : ARMISD::VMULLu;
2718 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2719 Op.getOperand(1), Op.getOperand(2));
2724 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2725 const ARMSubtarget *Subtarget) {
2726 // FIXME: handle "fence singlethread" more efficiently.
2728 if (!Subtarget->hasDataBarrier()) {
2729 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2730 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2732 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2733 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2734 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2735 DAG.getConstant(0, MVT::i32));
2738 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2739 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2740 unsigned Domain = ARM_MB::ISH;
2741 if (Subtarget->isMClass()) {
2742 // Only a full system barrier exists in the M-class architectures.
2743 Domain = ARM_MB::SY;
2744 } else if (Subtarget->isSwift() && Ord == Release) {
2745 // Swift happens to implement ISHST barriers in a way that's compatible with
2746 // Release semantics but weaker than ISH so we'd be fools not to use
2747 // it. Beware: other processors probably don't!
2748 Domain = ARM_MB::ISHST;
2751 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2752 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2753 DAG.getConstant(Domain, MVT::i32));
2756 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2757 const ARMSubtarget *Subtarget) {
2758 // ARM pre v5TE and Thumb1 does not have preload instructions.
2759 if (!(Subtarget->isThumb2() ||
2760 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2761 // Just preserve the chain.
2762 return Op.getOperand(0);
2765 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2767 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2768 // ARMv7 with MP extension has PLDW.
2769 return Op.getOperand(0);
2771 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2772 if (Subtarget->isThumb()) {
2774 isRead = ~isRead & 1;
2775 isData = ~isData & 1;
2778 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2779 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2780 DAG.getConstant(isData, MVT::i32));
2783 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2784 MachineFunction &MF = DAG.getMachineFunction();
2785 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2787 // vastart just stores the address of the VarArgsFrameIndex slot into the
2788 // memory location argument.
2790 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2791 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2792 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2793 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2794 MachinePointerInfo(SV), false, false, 0);
2798 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2799 SDValue &Root, SelectionDAG &DAG,
2801 MachineFunction &MF = DAG.getMachineFunction();
2802 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2804 const TargetRegisterClass *RC;
2805 if (AFI->isThumb1OnlyFunction())
2806 RC = &ARM::tGPRRegClass;
2808 RC = &ARM::GPRRegClass;
2810 // Transform the arguments stored in physical registers into virtual ones.
2811 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2812 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2815 if (NextVA.isMemLoc()) {
2816 MachineFrameInfo *MFI = MF.getFrameInfo();
2817 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2819 // Create load node to retrieve arguments from the stack.
2820 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2821 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2822 MachinePointerInfo::getFixedStack(FI),
2823 false, false, false, 0);
2825 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2826 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2828 if (!Subtarget->isLittle())
2829 std::swap (ArgValue, ArgValue2);
2830 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2834 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2835 unsigned InRegsParamRecordIdx,
2837 unsigned &ArgRegsSize,
2838 unsigned &ArgRegsSaveSize)
2841 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2842 unsigned RBegin, REnd;
2843 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2844 NumGPRs = REnd - RBegin;
2846 unsigned int firstUnalloced;
2847 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2848 sizeof(GPRArgRegs) /
2849 sizeof(GPRArgRegs[0]));
2850 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2853 unsigned Align = MF.getTarget()
2855 ->getFrameLowering()
2856 ->getStackAlignment();
2857 ArgRegsSize = NumGPRs * 4;
2859 // If parameter is split between stack and GPRs...
2860 if (NumGPRs && Align > 4 &&
2861 (ArgRegsSize < ArgSize ||
2862 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2863 // Add padding for part of param recovered from GPRs. For example,
2864 // if Align == 8, its last byte must be at address K*8 - 1.
2865 // We need to do it, since remained (stack) part of parameter has
2866 // stack alignment, and we need to "attach" "GPRs head" without gaps
2869 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2870 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2872 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2874 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2875 ArgRegsSaveSize = ArgRegsSize + Padding;
2877 // We don't need to extend regs save size for byval parameters if they
2878 // are passed via GPRs only.
2879 ArgRegsSaveSize = ArgRegsSize;
2882 // The remaining GPRs hold either the beginning of variable-argument
2883 // data, or the beginning of an aggregate passed by value (usually
2884 // byval). Either way, we allocate stack slots adjacent to the data
2885 // provided by our caller, and store the unallocated registers there.
2886 // If this is a variadic function, the va_list pointer will begin with
2887 // these values; otherwise, this reassembles a (byval) structure that
2888 // was split between registers and memory.
2889 // Return: The frame index registers were stored into.
2891 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2892 SDLoc dl, SDValue &Chain,
2893 const Value *OrigArg,
2894 unsigned InRegsParamRecordIdx,
2895 unsigned OffsetFromOrigArg,
2899 unsigned ByValStoreOffset,
2900 unsigned TotalArgRegsSaveSize) const {
2902 // Currently, two use-cases possible:
2903 // Case #1. Non-var-args function, and we meet first byval parameter.
2904 // Setup first unallocated register as first byval register;
2905 // eat all remained registers
2906 // (these two actions are performed by HandleByVal method).
2907 // Then, here, we initialize stack frame with
2908 // "store-reg" instructions.
2909 // Case #2. Var-args function, that doesn't contain byval parameters.
2910 // The same: eat all remained unallocated registers,
2911 // initialize stack frame.
2913 MachineFunction &MF = DAG.getMachineFunction();
2914 MachineFrameInfo *MFI = MF.getFrameInfo();
2915 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2916 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2917 unsigned RBegin, REnd;
2918 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2919 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2920 firstRegToSaveIndex = RBegin - ARM::R0;
2921 lastRegToSaveIndex = REnd - ARM::R0;
2923 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2924 (GPRArgRegs, array_lengthof(GPRArgRegs));
2925 lastRegToSaveIndex = 4;
2928 unsigned ArgRegsSize, ArgRegsSaveSize;
2929 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2930 ArgRegsSize, ArgRegsSaveSize);
2932 // Store any by-val regs to their spots on the stack so that they may be
2933 // loaded by deferencing the result of formal parameter pointer or va_next.
2934 // Note: once stack area for byval/varargs registers
2935 // was initialized, it can't be initialized again.
2936 if (ArgRegsSaveSize) {
2937 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2940 assert(AFI->getStoredByValParamsPadding() == 0 &&
2941 "The only parameter may be padded.");
2942 AFI->setStoredByValParamsPadding(Padding);
2945 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2948 (int64_t)TotalArgRegsSaveSize,
2950 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2952 MFI->CreateFixedObject(Padding,
2953 ArgOffset + ByValStoreOffset -
2954 (int64_t)ArgRegsSaveSize,
2958 SmallVector<SDValue, 4> MemOps;
2959 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2960 ++firstRegToSaveIndex, ++i) {
2961 const TargetRegisterClass *RC;
2962 if (AFI->isThumb1OnlyFunction())
2963 RC = &ARM::tGPRRegClass;
2965 RC = &ARM::GPRRegClass;
2967 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2968 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2970 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2971 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2973 MemOps.push_back(Store);
2974 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2975 DAG.getConstant(4, getPointerTy()));
2978 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2980 if (!MemOps.empty())
2981 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2985 // We cannot allocate a zero-byte object for the first variadic argument,
2986 // so just make up a size.
2989 // This will point to the next argument passed via stack.
2990 return MFI->CreateFixedObject(
2991 ArgSize, ArgOffset, !ForceMutable);
2995 // Setup stack frame, the va_list pointer will start from.
2997 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2998 SDLoc dl, SDValue &Chain,
3000 unsigned TotalArgRegsSaveSize,
3001 bool ForceMutable) const {
3002 MachineFunction &MF = DAG.getMachineFunction();
3003 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3005 // Try to store any remaining integer argument regs
3006 // to their spots on the stack so that they may be loaded by deferencing
3007 // the result of va_next.
3008 // If there is no regs to be stored, just point address after last
3009 // argument passed via stack.
3011 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3012 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3013 0, TotalArgRegsSaveSize);
3015 AFI->setVarArgsFrameIndex(FrameIndex);
3019 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3020 CallingConv::ID CallConv, bool isVarArg,
3021 const SmallVectorImpl<ISD::InputArg>
3023 SDLoc dl, SelectionDAG &DAG,
3024 SmallVectorImpl<SDValue> &InVals)
3026 MachineFunction &MF = DAG.getMachineFunction();
3027 MachineFrameInfo *MFI = MF.getFrameInfo();
3029 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3031 // Assign locations to all of the incoming arguments.
3032 SmallVector<CCValAssign, 16> ArgLocs;
3033 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3034 *DAG.getContext(), Prologue);
3035 CCInfo.AnalyzeFormalArguments(Ins,
3036 CCAssignFnForNode(CallConv, /* Return*/ false,
3039 SmallVector<SDValue, 16> ArgValues;
3040 int lastInsIndex = -1;
3042 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3043 unsigned CurArgIdx = 0;
3045 // Initially ArgRegsSaveSize is zero.
3046 // Then we increase this value each time we meet byval parameter.
3047 // We also increase this value in case of varargs function.
3048 AFI->setArgRegsSaveSize(0);
3050 unsigned ByValStoreOffset = 0;
3051 unsigned TotalArgRegsSaveSize = 0;
3052 unsigned ArgRegsSaveSizeMaxAlign = 4;
3054 // Calculate the amount of stack space that we need to allocate to store
3055 // byval and variadic arguments that are passed in registers.
3056 // We need to know this before we allocate the first byval or variadic
3057 // argument, as they will be allocated a stack slot below the CFA (Canonical
3058 // Frame Address, the stack pointer at entry to the function).
3059 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3060 CCValAssign &VA = ArgLocs[i];
3061 if (VA.isMemLoc()) {
3062 int index = VA.getValNo();
3063 if (index != lastInsIndex) {
3064 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3065 if (Flags.isByVal()) {
3066 unsigned ExtraArgRegsSize;
3067 unsigned ExtraArgRegsSaveSize;
3068 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3069 Flags.getByValSize(),
3070 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3072 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3073 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3074 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3075 CCInfo.nextInRegsParam();
3077 lastInsIndex = index;
3081 CCInfo.rewindByValRegsInfo();
3084 unsigned ExtraArgRegsSize;
3085 unsigned ExtraArgRegsSaveSize;
3086 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3087 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3088 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3090 // If the arg regs save area contains N-byte aligned values, the
3091 // bottom of it must be at least N-byte aligned.
3092 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3093 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3095 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3096 CCValAssign &VA = ArgLocs[i];
3097 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3098 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3099 // Arguments stored in registers.
3100 if (VA.isRegLoc()) {
3101 EVT RegVT = VA.getLocVT();
3103 if (VA.needsCustom()) {
3104 // f64 and vector types are split up into multiple registers or
3105 // combinations of registers and stack slots.
3106 if (VA.getLocVT() == MVT::v2f64) {
3107 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3109 VA = ArgLocs[++i]; // skip ahead to next loc
3111 if (VA.isMemLoc()) {
3112 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3113 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3114 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3115 MachinePointerInfo::getFixedStack(FI),
3116 false, false, false, 0);
3118 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3121 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3122 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3123 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3124 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3125 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3127 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3130 const TargetRegisterClass *RC;
3132 if (RegVT == MVT::f32)
3133 RC = &ARM::SPRRegClass;
3134 else if (RegVT == MVT::f64)
3135 RC = &ARM::DPRRegClass;
3136 else if (RegVT == MVT::v2f64)
3137 RC = &ARM::QPRRegClass;
3138 else if (RegVT == MVT::i32)
3139 RC = AFI->isThumb1OnlyFunction() ?
3140 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3141 (const TargetRegisterClass*)&ARM::GPRRegClass;
3143 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3145 // Transform the arguments in physical registers into virtual ones.
3146 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3147 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3150 // If this is an 8 or 16-bit value, it is really passed promoted
3151 // to 32 bits. Insert an assert[sz]ext to capture this, then
3152 // truncate to the right size.
3153 switch (VA.getLocInfo()) {
3154 default: llvm_unreachable("Unknown loc info!");
3155 case CCValAssign::Full: break;
3156 case CCValAssign::BCvt:
3157 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3159 case CCValAssign::SExt:
3160 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3161 DAG.getValueType(VA.getValVT()));
3162 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3164 case CCValAssign::ZExt:
3165 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3166 DAG.getValueType(VA.getValVT()));
3167 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3171 InVals.push_back(ArgValue);
3173 } else { // VA.isRegLoc()
3176 assert(VA.isMemLoc());
3177 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3179 int index = ArgLocs[i].getValNo();
3181 // Some Ins[] entries become multiple ArgLoc[] entries.
3182 // Process them only once.
3183 if (index != lastInsIndex)
3185 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3186 // FIXME: For now, all byval parameter objects are marked mutable.
3187 // This can be changed with more analysis.
3188 // In case of tail call optimization mark all arguments mutable.
3189 // Since they could be overwritten by lowering of arguments in case of
3191 if (Flags.isByVal()) {
3192 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3194 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3195 int FrameIndex = StoreByValRegs(
3196 CCInfo, DAG, dl, Chain, CurOrigArg,
3198 Ins[VA.getValNo()].PartOffset,
3199 VA.getLocMemOffset(),
3200 Flags.getByValSize(),
3201 true /*force mutable frames*/,
3203 TotalArgRegsSaveSize);
3204 ByValStoreOffset += Flags.getByValSize();
3205 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3206 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3207 CCInfo.nextInRegsParam();
3209 unsigned FIOffset = VA.getLocMemOffset();
3210 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3213 // Create load nodes to retrieve arguments from the stack.
3214 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3215 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3216 MachinePointerInfo::getFixedStack(FI),
3217 false, false, false, 0));
3219 lastInsIndex = index;
3226 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3227 CCInfo.getNextStackOffset(),
3228 TotalArgRegsSaveSize);
3230 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3235 /// isFloatingPointZero - Return true if this is +0.0.
3236 static bool isFloatingPointZero(SDValue Op) {
3237 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3238 return CFP->getValueAPF().isPosZero();
3239 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3240 // Maybe this has already been legalized into the constant pool?
3241 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3242 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3243 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3244 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3245 return CFP->getValueAPF().isPosZero();
3251 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3252 /// the given operands.
3254 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3255 SDValue &ARMcc, SelectionDAG &DAG,
3257 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3258 unsigned C = RHSC->getZExtValue();
3259 if (!isLegalICmpImmediate(C)) {
3260 // Constant does not fit, try adjusting it by one?
3265 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3266 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3267 RHS = DAG.getConstant(C-1, MVT::i32);
3272 if (C != 0 && isLegalICmpImmediate(C-1)) {
3273 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3274 RHS = DAG.getConstant(C-1, MVT::i32);
3279 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3280 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3281 RHS = DAG.getConstant(C+1, MVT::i32);
3286 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3287 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3288 RHS = DAG.getConstant(C+1, MVT::i32);
3295 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3296 ARMISD::NodeType CompareType;
3299 CompareType = ARMISD::CMP;
3304 CompareType = ARMISD::CMPZ;
3307 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3308 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3311 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3313 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3315 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3317 if (!isFloatingPointZero(RHS))
3318 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3320 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3321 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3324 /// duplicateCmp - Glue values can have only one use, so this function
3325 /// duplicates a comparison node.
3327 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3328 unsigned Opc = Cmp.getOpcode();
3330 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3331 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3333 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3334 Cmp = Cmp.getOperand(0);
3335 Opc = Cmp.getOpcode();
3336 if (Opc == ARMISD::CMPFP)
3337 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3339 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3340 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3342 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3345 std::pair<SDValue, SDValue>
3346 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3347 SDValue &ARMcc) const {
3348 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3350 SDValue Value, OverflowCmp;
3351 SDValue LHS = Op.getOperand(0);
3352 SDValue RHS = Op.getOperand(1);
3355 // FIXME: We are currently always generating CMPs because we don't support
3356 // generating CMN through the backend. This is not as good as the natural
3357 // CMP case because it causes a register dependency and cannot be folded
3360 switch (Op.getOpcode()) {
3362 llvm_unreachable("Unknown overflow instruction!");
3364 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3365 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3369 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3370 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3371 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3374 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3375 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3376 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3379 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3380 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3381 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3385 return std::make_pair(Value, OverflowCmp);
3390 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3391 // Let legalize expand this if it isn't a legal type yet.
3392 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3395 SDValue Value, OverflowCmp;
3397 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3398 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399 // We use 0 and 1 as false and true values.
3400 SDValue TVal = DAG.getConstant(1, MVT::i32);
3401 SDValue FVal = DAG.getConstant(0, MVT::i32);
3402 EVT VT = Op.getValueType();
3404 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3405 ARMcc, CCR, OverflowCmp);
3407 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3408 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3412 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3413 SDValue Cond = Op.getOperand(0);
3414 SDValue SelectTrue = Op.getOperand(1);
3415 SDValue SelectFalse = Op.getOperand(2);
3417 unsigned Opc = Cond.getOpcode();
3419 if (Cond.getResNo() == 1 &&
3420 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3421 Opc == ISD::USUBO)) {
3422 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3425 SDValue Value, OverflowCmp;
3427 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3428 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3429 EVT VT = Op.getValueType();
3431 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3437 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3438 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3440 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3441 const ConstantSDNode *CMOVTrue =
3442 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3443 const ConstantSDNode *CMOVFalse =
3444 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3446 if (CMOVTrue && CMOVFalse) {
3447 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3448 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3452 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3454 False = SelectFalse;
3455 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3460 if (True.getNode() && False.getNode()) {
3461 EVT VT = Op.getValueType();
3462 SDValue ARMcc = Cond.getOperand(2);
3463 SDValue CCR = Cond.getOperand(3);
3464 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3465 assert(True.getValueType() == VT);
3466 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3471 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3472 // undefined bits before doing a full-word comparison with zero.
3473 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3474 DAG.getConstant(1, Cond.getValueType()));
3476 return DAG.getSelectCC(dl, Cond,
3477 DAG.getConstant(0, Cond.getValueType()),
3478 SelectTrue, SelectFalse, ISD::SETNE);
3481 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3482 if (CC == ISD::SETNE)
3484 return ISD::getSetCCInverse(CC, true);
3487 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3488 bool &swpCmpOps, bool &swpVselOps) {
3489 // Start by selecting the GE condition code for opcodes that return true for
3491 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3493 CondCode = ARMCC::GE;
3495 // and GT for opcodes that return false for 'equality'.
3496 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3498 CondCode = ARMCC::GT;
3500 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3501 // to swap the compare operands.
3502 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3506 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3507 // If we have an unordered opcode, we need to swap the operands to the VSEL
3508 // instruction (effectively negating the condition).
3510 // This also has the effect of swapping which one of 'less' or 'greater'
3511 // returns true, so we also swap the compare operands. It also switches
3512 // whether we return true for 'equality', so we compensate by picking the
3513 // opposite condition code to our original choice.
3514 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3515 CC == ISD::SETUGT) {
3516 swpCmpOps = !swpCmpOps;
3517 swpVselOps = !swpVselOps;
3518 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3521 // 'ordered' is 'anything but unordered', so use the VS condition code and
3522 // swap the VSEL operands.
3523 if (CC == ISD::SETO) {
3524 CondCode = ARMCC::VS;
3528 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3529 // code and swap the VSEL operands.
3530 if (CC == ISD::SETUNE) {
3531 CondCode = ARMCC::EQ;
3536 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3537 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3538 SDValue Cmp, SelectionDAG &DAG) const {
3539 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3540 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3541 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3542 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3543 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3545 SDValue TrueLow = TrueVal.getValue(0);
3546 SDValue TrueHigh = TrueVal.getValue(1);
3547 SDValue FalseLow = FalseVal.getValue(0);
3548 SDValue FalseHigh = FalseVal.getValue(1);
3550 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3552 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3553 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3555 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3557 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3562 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3563 EVT VT = Op.getValueType();
3564 SDValue LHS = Op.getOperand(0);
3565 SDValue RHS = Op.getOperand(1);
3566 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3567 SDValue TrueVal = Op.getOperand(2);
3568 SDValue FalseVal = Op.getOperand(3);
3571 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3572 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3575 // If softenSetCCOperands only returned one value, we should compare it to
3577 if (!RHS.getNode()) {
3578 RHS = DAG.getConstant(0, LHS.getValueType());
3583 if (LHS.getValueType() == MVT::i32) {
3584 // Try to generate VSEL on ARMv8.
3585 // The VSEL instruction can't use all the usual ARM condition
3586 // codes: it only has two bits to select the condition code, so it's
3587 // constrained to use only GE, GT, VS and EQ.
3589 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3590 // swap the operands of the previous compare instruction (effectively
3591 // inverting the compare condition, swapping 'less' and 'greater') and
3592 // sometimes need to swap the operands to the VSEL (which inverts the
3593 // condition in the sense of firing whenever the previous condition didn't)
3594 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3595 TrueVal.getValueType() == MVT::f64)) {
3596 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3597 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3598 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3599 CC = getInverseCCForVSEL(CC);
3600 std::swap(TrueVal, FalseVal);
3605 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3606 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3607 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3610 ARMCC::CondCodes CondCode, CondCode2;
3611 FPCCToARMCC(CC, CondCode, CondCode2);
3613 // Try to generate VSEL on ARMv8.
3614 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3615 TrueVal.getValueType() == MVT::f64)) {
3616 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3617 // same operands, as follows:
3618 // c = fcmp [ogt, olt, ugt, ult] a, b
3620 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3621 // handled differently than the original code sequence.
3622 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3624 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3625 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3626 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3627 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3630 bool swpCmpOps = false;
3631 bool swpVselOps = false;
3632 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3634 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3635 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3637 std::swap(LHS, RHS);
3639 std::swap(TrueVal, FalseVal);
3643 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3644 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3645 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3646 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3647 if (CondCode2 != ARMCC::AL) {
3648 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3649 // FIXME: Needs another CMP because flag can have but one use.
3650 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3651 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3656 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3657 /// to morph to an integer compare sequence.
3658 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3659 const ARMSubtarget *Subtarget) {
3660 SDNode *N = Op.getNode();
3661 if (!N->hasOneUse())
3662 // Otherwise it requires moving the value from fp to integer registers.
3664 if (!N->getNumValues())
3666 EVT VT = Op.getValueType();
3667 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3668 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3669 // vmrs are very slow, e.g. cortex-a8.
3672 if (isFloatingPointZero(Op)) {
3676 return ISD::isNormalLoad(N);
3679 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3680 if (isFloatingPointZero(Op))
3681 return DAG.getConstant(0, MVT::i32);
3683 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3684 return DAG.getLoad(MVT::i32, SDLoc(Op),
3685 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3686 Ld->isVolatile(), Ld->isNonTemporal(),
3687 Ld->isInvariant(), Ld->getAlignment());
3689 llvm_unreachable("Unknown VFP cmp argument!");
3692 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3693 SDValue &RetVal1, SDValue &RetVal2) {
3694 if (isFloatingPointZero(Op)) {
3695 RetVal1 = DAG.getConstant(0, MVT::i32);
3696 RetVal2 = DAG.getConstant(0, MVT::i32);
3700 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3701 SDValue Ptr = Ld->getBasePtr();
3702 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3703 Ld->getChain(), Ptr,
3704 Ld->getPointerInfo(),
3705 Ld->isVolatile(), Ld->isNonTemporal(),
3706 Ld->isInvariant(), Ld->getAlignment());
3708 EVT PtrType = Ptr.getValueType();
3709 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3710 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3711 PtrType, Ptr, DAG.getConstant(4, PtrType));
3712 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3713 Ld->getChain(), NewPtr,
3714 Ld->getPointerInfo().getWithOffset(4),
3715 Ld->isVolatile(), Ld->isNonTemporal(),
3716 Ld->isInvariant(), NewAlign);
3720 llvm_unreachable("Unknown VFP cmp argument!");
3723 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3724 /// f32 and even f64 comparisons to integer ones.
3726 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3727 SDValue Chain = Op.getOperand(0);
3728 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3729 SDValue LHS = Op.getOperand(2);
3730 SDValue RHS = Op.getOperand(3);
3731 SDValue Dest = Op.getOperand(4);
3734 bool LHSSeenZero = false;
3735 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3736 bool RHSSeenZero = false;
3737 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3738 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3739 // If unsafe fp math optimization is enabled and there are no other uses of
3740 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3741 // to an integer comparison.
3742 if (CC == ISD::SETOEQ)
3744 else if (CC == ISD::SETUNE)
3747 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3749 if (LHS.getValueType() == MVT::f32) {
3750 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3751 bitcastf32Toi32(LHS, DAG), Mask);
3752 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3753 bitcastf32Toi32(RHS, DAG), Mask);
3754 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3755 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3756 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3757 Chain, Dest, ARMcc, CCR, Cmp);
3762 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3763 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3764 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3765 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3766 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3767 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3768 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3769 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3770 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3776 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3777 SDValue Chain = Op.getOperand(0);
3778 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3779 SDValue LHS = Op.getOperand(2);
3780 SDValue RHS = Op.getOperand(3);
3781 SDValue Dest = Op.getOperand(4);
3784 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3785 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3788 // If softenSetCCOperands only returned one value, we should compare it to
3790 if (!RHS.getNode()) {
3791 RHS = DAG.getConstant(0, LHS.getValueType());
3796 if (LHS.getValueType() == MVT::i32) {
3798 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3799 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3800 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3801 Chain, Dest, ARMcc, CCR, Cmp);
3804 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3806 if (getTargetMachine().Options.UnsafeFPMath &&
3807 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3808 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3809 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3810 if (Result.getNode())
3814 ARMCC::CondCodes CondCode, CondCode2;
3815 FPCCToARMCC(CC, CondCode, CondCode2);
3817 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3818 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3819 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3820 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3821 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3822 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3823 if (CondCode2 != ARMCC::AL) {
3824 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3825 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3826 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3831 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3832 SDValue Chain = Op.getOperand(0);
3833 SDValue Table = Op.getOperand(1);
3834 SDValue Index = Op.getOperand(2);
3837 EVT PTy = getPointerTy();
3838 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3839 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3840 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3841 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3842 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3843 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3844 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3845 if (Subtarget->isThumb2()) {
3846 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3847 // which does another jump to the destination. This also makes it easier
3848 // to translate it to TBB / TBH later.
3849 // FIXME: This might not work if the function is extremely large.
3850 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3851 Addr, Op.getOperand(2), JTI, UId);
3853 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3854 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3855 MachinePointerInfo::getJumpTable(),
3856 false, false, false, 0);
3857 Chain = Addr.getValue(1);
3858 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3859 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3861 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3862 MachinePointerInfo::getJumpTable(),
3863 false, false, false, 0);
3864 Chain = Addr.getValue(1);
3865 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3869 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3870 EVT VT = Op.getValueType();
3873 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3874 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3876 return DAG.UnrollVectorOp(Op.getNode());
3879 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3880 "Invalid type for custom lowering!");
3881 if (VT != MVT::v4i16)
3882 return DAG.UnrollVectorOp(Op.getNode());
3884 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3885 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3888 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3889 EVT VT = Op.getValueType();
3891 return LowerVectorFP_TO_INT(Op, DAG);
3893 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3895 if (Op.getOpcode() == ISD::FP_TO_SINT)
3896 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3899 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3901 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3902 /*isSigned*/ false, SDLoc(Op)).first;
3908 switch (Op.getOpcode()) {
3909 default: llvm_unreachable("Invalid opcode!");
3910 case ISD::FP_TO_SINT:
3911 Opc = ARMISD::FTOSI;
3913 case ISD::FP_TO_UINT:
3914 Opc = ARMISD::FTOUI;
3917 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3918 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3921 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3922 EVT VT = Op.getValueType();
3925 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3926 if (VT.getVectorElementType() == MVT::f32)
3928 return DAG.UnrollVectorOp(Op.getNode());
3931 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3932 "Invalid type for custom lowering!");
3933 if (VT != MVT::v4f32)
3934 return DAG.UnrollVectorOp(Op.getNode());
3938 switch (Op.getOpcode()) {
3939 default: llvm_unreachable("Invalid opcode!");
3940 case ISD::SINT_TO_FP:
3941 CastOpc = ISD::SIGN_EXTEND;
3942 Opc = ISD::SINT_TO_FP;
3944 case ISD::UINT_TO_FP:
3945 CastOpc = ISD::ZERO_EXTEND;
3946 Opc = ISD::UINT_TO_FP;
3950 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3951 return DAG.getNode(Opc, dl, VT, Op);
3954 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3955 EVT VT = Op.getValueType();
3957 return LowerVectorINT_TO_FP(Op, DAG);
3959 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3961 if (Op.getOpcode() == ISD::SINT_TO_FP)
3962 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3965 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3967 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3968 /*isSigned*/ false, SDLoc(Op)).first;
3974 switch (Op.getOpcode()) {
3975 default: llvm_unreachable("Invalid opcode!");
3976 case ISD::SINT_TO_FP:
3977 Opc = ARMISD::SITOF;
3979 case ISD::UINT_TO_FP:
3980 Opc = ARMISD::UITOF;
3984 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3985 return DAG.getNode(Opc, dl, VT, Op);
3988 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3989 // Implement fcopysign with a fabs and a conditional fneg.
3990 SDValue Tmp0 = Op.getOperand(0);
3991 SDValue Tmp1 = Op.getOperand(1);
3993 EVT VT = Op.getValueType();
3994 EVT SrcVT = Tmp1.getValueType();
3995 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3996 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3997 bool UseNEON = !InGPR && Subtarget->hasNEON();
4000 // Use VBSL to copy the sign bit.
4001 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4002 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4003 DAG.getTargetConstant(EncodedVal, MVT::i32));
4004 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4006 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4007 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4008 DAG.getConstant(32, MVT::i32));
4009 else /*if (VT == MVT::f32)*/
4010 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4011 if (SrcVT == MVT::f32) {
4012 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4014 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4015 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4016 DAG.getConstant(32, MVT::i32));
4017 } else if (VT == MVT::f32)
4018 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4019 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4020 DAG.getConstant(32, MVT::i32));
4021 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4022 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4024 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4026 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4027 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4028 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4030 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4031 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4032 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4033 if (VT == MVT::f32) {
4034 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4035 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4036 DAG.getConstant(0, MVT::i32));
4038 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4044 // Bitcast operand 1 to i32.
4045 if (SrcVT == MVT::f64)
4046 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4048 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4050 // Or in the signbit with integer operations.
4051 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4052 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4053 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4054 if (VT == MVT::f32) {
4055 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4056 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4057 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4058 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4061 // f64: Or the high part with signbit and then combine two parts.
4062 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4064 SDValue Lo = Tmp0.getValue(0);
4065 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4066 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4067 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4070 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4071 MachineFunction &MF = DAG.getMachineFunction();
4072 MachineFrameInfo *MFI = MF.getFrameInfo();
4073 MFI->setReturnAddressIsTaken(true);
4075 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4078 EVT VT = Op.getValueType();
4080 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4082 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4083 SDValue Offset = DAG.getConstant(4, MVT::i32);
4084 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4085 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4086 MachinePointerInfo(), false, false, false, 0);
4089 // Return LR, which contains the return address. Mark it an implicit live-in.
4090 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4091 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4094 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4095 const ARMBaseRegisterInfo &ARI =
4096 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4097 MachineFunction &MF = DAG.getMachineFunction();
4098 MachineFrameInfo *MFI = MF.getFrameInfo();
4099 MFI->setFrameAddressIsTaken(true);
4101 EVT VT = Op.getValueType();
4102 SDLoc dl(Op); // FIXME probably not meaningful
4103 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4104 unsigned FrameReg = ARI.getFrameRegister(MF);
4105 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4107 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4108 MachinePointerInfo(),
4109 false, false, false, 0);
4113 // FIXME? Maybe this could be a TableGen attribute on some registers and
4114 // this table could be generated automatically from RegInfo.
4115 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4117 unsigned Reg = StringSwitch<unsigned>(RegName)
4118 .Case("sp", ARM::SP)
4122 report_fatal_error("Invalid register name global variable");
4125 /// ExpandBITCAST - If the target supports VFP, this function is called to
4126 /// expand a bit convert where either the source or destination type is i64 to
4127 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4128 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4129 /// vectors), since the legalizer won't know what to do with that.
4130 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4131 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4133 SDValue Op = N->getOperand(0);
4135 // This function is only supposed to be called for i64 types, either as the
4136 // source or destination of the bit convert.
4137 EVT SrcVT = Op.getValueType();
4138 EVT DstVT = N->getValueType(0);
4139 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4140 "ExpandBITCAST called for non-i64 type");
4142 // Turn i64->f64 into VMOVDRR.
4143 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4144 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4145 DAG.getConstant(0, MVT::i32));
4146 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4147 DAG.getConstant(1, MVT::i32));
4148 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4149 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4152 // Turn f64->i64 into VMOVRRD.
4153 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4155 if (TLI.isBigEndian() && SrcVT.isVector() &&
4156 SrcVT.getVectorNumElements() > 1)
4157 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4158 DAG.getVTList(MVT::i32, MVT::i32),
4159 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4161 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4162 DAG.getVTList(MVT::i32, MVT::i32), Op);
4163 // Merge the pieces into a single i64 value.
4164 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4170 /// getZeroVector - Returns a vector of specified type with all zero elements.
4171 /// Zero vectors are used to represent vector negation and in those cases
4172 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4173 /// not support i64 elements, so sometimes the zero vectors will need to be
4174 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4176 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4177 assert(VT.isVector() && "Expected a vector type");
4178 // The canonical modified immediate encoding of a zero vector is....0!
4179 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4180 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4181 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4182 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4185 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4186 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4187 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4188 SelectionDAG &DAG) const {
4189 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4190 EVT VT = Op.getValueType();
4191 unsigned VTBits = VT.getSizeInBits();
4193 SDValue ShOpLo = Op.getOperand(0);
4194 SDValue ShOpHi = Op.getOperand(1);
4195 SDValue ShAmt = Op.getOperand(2);
4197 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4199 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4201 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4202 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4203 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4204 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4205 DAG.getConstant(VTBits, MVT::i32));
4206 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4207 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4208 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4210 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4211 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4213 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4214 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4217 SDValue Ops[2] = { Lo, Hi };
4218 return DAG.getMergeValues(Ops, dl);
4221 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4222 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4223 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4224 SelectionDAG &DAG) const {
4225 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4226 EVT VT = Op.getValueType();
4227 unsigned VTBits = VT.getSizeInBits();
4229 SDValue ShOpLo = Op.getOperand(0);
4230 SDValue ShOpHi = Op.getOperand(1);
4231 SDValue ShAmt = Op.getOperand(2);
4234 assert(Op.getOpcode() == ISD::SHL_PARTS);
4235 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4236 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4237 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4238 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4239 DAG.getConstant(VTBits, MVT::i32));
4240 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4241 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4243 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4244 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4245 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4247 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4248 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4251 SDValue Ops[2] = { Lo, Hi };
4252 return DAG.getMergeValues(Ops, dl);
4255 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4256 SelectionDAG &DAG) const {
4257 // The rounding mode is in bits 23:22 of the FPSCR.
4258 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4259 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4260 // so that the shift + and get folded into a bitfield extract.
4262 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4263 DAG.getConstant(Intrinsic::arm_get_fpscr,
4265 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4266 DAG.getConstant(1U << 22, MVT::i32));
4267 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4268 DAG.getConstant(22, MVT::i32));
4269 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4270 DAG.getConstant(3, MVT::i32));
4273 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4274 const ARMSubtarget *ST) {
4275 EVT VT = N->getValueType(0);
4278 if (!ST->hasV6T2Ops())
4281 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4282 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4285 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4286 /// for each 16-bit element from operand, repeated. The basic idea is to
4287 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4289 /// Trace for v4i16:
4290 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4291 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4292 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4293 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4294 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4295 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4296 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4297 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4298 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4299 EVT VT = N->getValueType(0);
4302 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4303 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4304 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4305 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4306 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4307 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4310 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4311 /// bit-count for each 16-bit element from the operand. We need slightly
4312 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4313 /// 64/128-bit registers.
4315 /// Trace for v4i16:
4316 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4317 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4318 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4319 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4320 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4321 EVT VT = N->getValueType(0);
4324 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4325 if (VT.is64BitVector()) {
4326 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4327 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4328 DAG.getIntPtrConstant(0));
4330 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4331 BitCounts, DAG.getIntPtrConstant(0));
4332 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4336 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4337 /// bit-count for each 32-bit element from the operand. The idea here is
4338 /// to split the vector into 16-bit elements, leverage the 16-bit count
4339 /// routine, and then combine the results.
4341 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4342 /// input = [v0 v1 ] (vi: 32-bit elements)
4343 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4344 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4345 /// vrev: N0 = [k1 k0 k3 k2 ]
4347 /// N1 =+[k1 k0 k3 k2 ]
4349 /// N2 =+[k1 k3 k0 k2 ]
4351 /// Extended =+[k1 k3 k0 k2 ]
4353 /// Extracted=+[k1 k3 ]
4355 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4356 EVT VT = N->getValueType(0);
4359 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4361 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4362 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4363 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4364 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4365 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4367 if (VT.is64BitVector()) {
4368 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4369 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4370 DAG.getIntPtrConstant(0));
4372 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4373 DAG.getIntPtrConstant(0));
4374 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4378 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4379 const ARMSubtarget *ST) {
4380 EVT VT = N->getValueType(0);
4382 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4383 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4384 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4385 "Unexpected type for custom ctpop lowering");
4387 if (VT.getVectorElementType() == MVT::i32)
4388 return lowerCTPOP32BitElements(N, DAG);
4390 return lowerCTPOP16BitElements(N, DAG);
4393 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4394 const ARMSubtarget *ST) {
4395 EVT VT = N->getValueType(0);
4401 // Lower vector shifts on NEON to use VSHL.
4402 assert(ST->hasNEON() && "unexpected vector shift");
4404 // Left shifts translate directly to the vshiftu intrinsic.
4405 if (N->getOpcode() == ISD::SHL)
4406 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4407 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4408 N->getOperand(0), N->getOperand(1));
4410 assert((N->getOpcode() == ISD::SRA ||
4411 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4413 // NEON uses the same intrinsics for both left and right shifts. For
4414 // right shifts, the shift amounts are negative, so negate the vector of
4416 EVT ShiftVT = N->getOperand(1).getValueType();
4417 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4418 getZeroVector(ShiftVT, DAG, dl),
4420 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4421 Intrinsic::arm_neon_vshifts :
4422 Intrinsic::arm_neon_vshiftu);
4423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4424 DAG.getConstant(vshiftInt, MVT::i32),
4425 N->getOperand(0), NegatedCount);
4428 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4429 const ARMSubtarget *ST) {
4430 EVT VT = N->getValueType(0);
4433 // We can get here for a node like i32 = ISD::SHL i32, i64
4437 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4438 "Unknown shift to lower!");
4440 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4441 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4442 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4445 // If we are in thumb mode, we don't have RRX.
4446 if (ST->isThumb1Only()) return SDValue();
4448 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4449 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4450 DAG.getConstant(0, MVT::i32));
4451 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4452 DAG.getConstant(1, MVT::i32));
4454 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4455 // captures the result into a carry flag.
4456 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4457 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4459 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4460 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4462 // Merge the pieces into a single i64 value.
4463 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4466 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4467 SDValue TmpOp0, TmpOp1;
4468 bool Invert = false;
4472 SDValue Op0 = Op.getOperand(0);
4473 SDValue Op1 = Op.getOperand(1);
4474 SDValue CC = Op.getOperand(2);
4475 EVT VT = Op.getValueType();
4476 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4479 if (Op1.getValueType().isFloatingPoint()) {
4480 switch (SetCCOpcode) {
4481 default: llvm_unreachable("Illegal FP comparison");
4483 case ISD::SETNE: Invert = true; // Fallthrough
4485 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4487 case ISD::SETLT: Swap = true; // Fallthrough
4489 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4491 case ISD::SETLE: Swap = true; // Fallthrough
4493 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4494 case ISD::SETUGE: Swap = true; // Fallthrough
4495 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4496 case ISD::SETUGT: Swap = true; // Fallthrough
4497 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4498 case ISD::SETUEQ: Invert = true; // Fallthrough
4500 // Expand this to (OLT | OGT).
4504 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4505 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4507 case ISD::SETUO: Invert = true; // Fallthrough
4509 // Expand this to (OLT | OGE).
4513 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4514 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4518 // Integer comparisons.
4519 switch (SetCCOpcode) {
4520 default: llvm_unreachable("Illegal integer comparison");
4521 case ISD::SETNE: Invert = true;
4522 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4523 case ISD::SETLT: Swap = true;
4524 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4525 case ISD::SETLE: Swap = true;
4526 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4527 case ISD::SETULT: Swap = true;
4528 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4529 case ISD::SETULE: Swap = true;
4530 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4533 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4534 if (Opc == ARMISD::VCEQ) {
4537 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4539 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4542 // Ignore bitconvert.
4543 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4544 AndOp = AndOp.getOperand(0);
4546 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4548 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4549 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4556 std::swap(Op0, Op1);
4558 // If one of the operands is a constant vector zero, attempt to fold the
4559 // comparison to a specialized compare-against-zero form.
4561 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4563 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4564 if (Opc == ARMISD::VCGE)
4565 Opc = ARMISD::VCLEZ;
4566 else if (Opc == ARMISD::VCGT)
4567 Opc = ARMISD::VCLTZ;
4572 if (SingleOp.getNode()) {
4575 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4577 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4579 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4581 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4583 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4585 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4588 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4592 Result = DAG.getNOT(dl, Result, VT);
4597 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4598 /// valid vector constant for a NEON instruction with a "modified immediate"
4599 /// operand (e.g., VMOV). If so, return the encoded value.
4600 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4601 unsigned SplatBitSize, SelectionDAG &DAG,
4602 EVT &VT, bool is128Bits, NEONModImmType type) {
4603 unsigned OpCmode, Imm;
4605 // SplatBitSize is set to the smallest size that splats the vector, so a
4606 // zero vector will always have SplatBitSize == 8. However, NEON modified
4607 // immediate instructions others than VMOV do not support the 8-bit encoding
4608 // of a zero vector, and the default encoding of zero is supposed to be the
4613 switch (SplatBitSize) {
4615 if (type != VMOVModImm)
4617 // Any 1-byte value is OK. Op=0, Cmode=1110.
4618 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4621 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4625 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4626 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4627 if ((SplatBits & ~0xff) == 0) {
4628 // Value = 0x00nn: Op=x, Cmode=100x.
4633 if ((SplatBits & ~0xff00) == 0) {
4634 // Value = 0xnn00: Op=x, Cmode=101x.
4636 Imm = SplatBits >> 8;
4642 // NEON's 32-bit VMOV supports splat values where:
4643 // * only one byte is nonzero, or
4644 // * the least significant byte is 0xff and the second byte is nonzero, or
4645 // * the least significant 2 bytes are 0xff and the third is nonzero.
4646 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4647 if ((SplatBits & ~0xff) == 0) {
4648 // Value = 0x000000nn: Op=x, Cmode=000x.
4653 if ((SplatBits & ~0xff00) == 0) {
4654 // Value = 0x0000nn00: Op=x, Cmode=001x.
4656 Imm = SplatBits >> 8;
4659 if ((SplatBits & ~0xff0000) == 0) {
4660 // Value = 0x00nn0000: Op=x, Cmode=010x.
4662 Imm = SplatBits >> 16;
4665 if ((SplatBits & ~0xff000000) == 0) {
4666 // Value = 0xnn000000: Op=x, Cmode=011x.
4668 Imm = SplatBits >> 24;
4672 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4673 if (type == OtherModImm) return SDValue();
4675 if ((SplatBits & ~0xffff) == 0 &&
4676 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4677 // Value = 0x0000nnff: Op=x, Cmode=1100.
4679 Imm = SplatBits >> 8;
4683 if ((SplatBits & ~0xffffff) == 0 &&
4684 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4685 // Value = 0x00nnffff: Op=x, Cmode=1101.
4687 Imm = SplatBits >> 16;
4691 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4692 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4693 // VMOV.I32. A (very) minor optimization would be to replicate the value
4694 // and fall through here to test for a valid 64-bit splat. But, then the
4695 // caller would also need to check and handle the change in size.
4699 if (type != VMOVModImm)
4701 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4702 uint64_t BitMask = 0xff;
4704 unsigned ImmMask = 1;
4706 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4707 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4710 } else if ((SplatBits & BitMask) != 0) {
4717 if (DAG.getTargetLoweringInfo().isBigEndian())
4718 // swap higher and lower 32 bit word
4719 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4721 // Op=1, Cmode=1110.
4723 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4728 llvm_unreachable("unexpected size for isNEONModifiedImm");
4731 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4732 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4735 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4736 const ARMSubtarget *ST) const {
4740 bool IsDouble = Op.getValueType() == MVT::f64;
4741 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4743 // Use the default (constant pool) lowering for double constants when we have
4745 if (IsDouble && Subtarget->isFPOnlySP())
4748 // Try splatting with a VMOV.f32...
4749 APFloat FPVal = CFP->getValueAPF();
4750 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4753 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4754 // We have code in place to select a valid ConstantFP already, no need to
4759 // It's a float and we are trying to use NEON operations where
4760 // possible. Lower it to a splat followed by an extract.
4762 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4763 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4765 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4766 DAG.getConstant(0, MVT::i32));
4769 // The rest of our options are NEON only, make sure that's allowed before
4771 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4775 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4777 // It wouldn't really be worth bothering for doubles except for one very
4778 // important value, which does happen to match: 0.0. So make sure we don't do
4780 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4783 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4784 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4786 if (NewVal != SDValue()) {
4788 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4791 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4793 // It's a float: cast and extract a vector element.
4794 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4796 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4797 DAG.getConstant(0, MVT::i32));
4800 // Finally, try a VMVN.i32
4801 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4803 if (NewVal != SDValue()) {
4805 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4808 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4810 // It's a float: cast and extract a vector element.
4811 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4813 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4814 DAG.getConstant(0, MVT::i32));
4820 // check if an VEXT instruction can handle the shuffle mask when the
4821 // vector sources of the shuffle are the same.
4822 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4823 unsigned NumElts = VT.getVectorNumElements();
4825 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4831 // If this is a VEXT shuffle, the immediate value is the index of the first
4832 // element. The other shuffle indices must be the successive elements after
4834 unsigned ExpectedElt = Imm;
4835 for (unsigned i = 1; i < NumElts; ++i) {
4836 // Increment the expected index. If it wraps around, just follow it
4837 // back to index zero and keep going.
4839 if (ExpectedElt == NumElts)
4842 if (M[i] < 0) continue; // ignore UNDEF indices
4843 if (ExpectedElt != static_cast<unsigned>(M[i]))
4851 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4852 bool &ReverseVEXT, unsigned &Imm) {
4853 unsigned NumElts = VT.getVectorNumElements();
4854 ReverseVEXT = false;
4856 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4862 // If this is a VEXT shuffle, the immediate value is the index of the first
4863 // element. The other shuffle indices must be the successive elements after
4865 unsigned ExpectedElt = Imm;
4866 for (unsigned i = 1; i < NumElts; ++i) {
4867 // Increment the expected index. If it wraps around, it may still be
4868 // a VEXT but the source vectors must be swapped.
4870 if (ExpectedElt == NumElts * 2) {
4875 if (M[i] < 0) continue; // ignore UNDEF indices
4876 if (ExpectedElt != static_cast<unsigned>(M[i]))
4880 // Adjust the index value if the source operands will be swapped.
4887 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4888 /// instruction with the specified blocksize. (The order of the elements
4889 /// within each block of the vector is reversed.)
4890 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4891 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4892 "Only possible block sizes for VREV are: 16, 32, 64");
4894 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4898 unsigned NumElts = VT.getVectorNumElements();
4899 unsigned BlockElts = M[0] + 1;
4900 // If the first shuffle index is UNDEF, be optimistic.
4902 BlockElts = BlockSize / EltSz;
4904 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4907 for (unsigned i = 0; i < NumElts; ++i) {
4908 if (M[i] < 0) continue; // ignore UNDEF indices
4909 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4916 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4917 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4918 // range, then 0 is placed into the resulting vector. So pretty much any mask
4919 // of 8 elements can work here.
4920 return VT == MVT::v8i8 && M.size() == 8;
4923 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4924 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4928 unsigned NumElts = VT.getVectorNumElements();
4929 WhichResult = (M[0] == 0 ? 0 : 1);
4930 for (unsigned i = 0; i < NumElts; i += 2) {
4931 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4932 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4938 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4939 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4940 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4941 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4942 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4946 unsigned NumElts = VT.getVectorNumElements();
4947 WhichResult = (M[0] == 0 ? 0 : 1);
4948 for (unsigned i = 0; i < NumElts; i += 2) {
4949 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4950 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4956 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4957 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4961 unsigned NumElts = VT.getVectorNumElements();
4962 WhichResult = (M[0] == 0 ? 0 : 1);
4963 for (unsigned i = 0; i != NumElts; ++i) {
4964 if (M[i] < 0) continue; // ignore UNDEF indices
4965 if ((unsigned) M[i] != 2 * i + WhichResult)
4969 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4970 if (VT.is64BitVector() && EltSz == 32)
4976 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4977 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4978 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4979 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4980 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4984 unsigned Half = VT.getVectorNumElements() / 2;
4985 WhichResult = (M[0] == 0 ? 0 : 1);
4986 for (unsigned j = 0; j != 2; ++j) {
4987 unsigned Idx = WhichResult;
4988 for (unsigned i = 0; i != Half; ++i) {
4989 int MIdx = M[i + j * Half];
4990 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4996 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4997 if (VT.is64BitVector() && EltSz == 32)
5003 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5004 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5008 unsigned NumElts = VT.getVectorNumElements();
5009 WhichResult = (M[0] == 0 ? 0 : 1);
5010 unsigned Idx = WhichResult * NumElts / 2;
5011 for (unsigned i = 0; i != NumElts; i += 2) {
5012 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5013 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5018 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5019 if (VT.is64BitVector() && EltSz == 32)
5025 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5026 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5027 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5028 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5029 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5033 unsigned NumElts = VT.getVectorNumElements();
5034 WhichResult = (M[0] == 0 ? 0 : 1);
5035 unsigned Idx = WhichResult * NumElts / 2;
5036 for (unsigned i = 0; i != NumElts; i += 2) {
5037 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5038 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5043 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5044 if (VT.is64BitVector() && EltSz == 32)
5050 /// \return true if this is a reverse operation on an vector.
5051 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5052 unsigned NumElts = VT.getVectorNumElements();
5053 // Make sure the mask has the right size.
5054 if (NumElts != M.size())
5057 // Look for <15, ..., 3, -1, 1, 0>.
5058 for (unsigned i = 0; i != NumElts; ++i)
5059 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5065 // If N is an integer constant that can be moved into a register in one
5066 // instruction, return an SDValue of such a constant (will become a MOV
5067 // instruction). Otherwise return null.
5068 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5069 const ARMSubtarget *ST, SDLoc dl) {
5071 if (!isa<ConstantSDNode>(N))
5073 Val = cast<ConstantSDNode>(N)->getZExtValue();
5075 if (ST->isThumb1Only()) {
5076 if (Val <= 255 || ~Val <= 255)
5077 return DAG.getConstant(Val, MVT::i32);
5079 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5080 return DAG.getConstant(Val, MVT::i32);
5085 // If this is a case we can't handle, return null and let the default
5086 // expansion code take care of it.
5087 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5088 const ARMSubtarget *ST) const {
5089 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5091 EVT VT = Op.getValueType();
5093 APInt SplatBits, SplatUndef;
5094 unsigned SplatBitSize;
5096 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5097 if (SplatBitSize <= 64) {
5098 // Check if an immediate VMOV works.
5100 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5101 SplatUndef.getZExtValue(), SplatBitSize,
5102 DAG, VmovVT, VT.is128BitVector(),
5104 if (Val.getNode()) {
5105 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5106 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5109 // Try an immediate VMVN.
5110 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5111 Val = isNEONModifiedImm(NegatedImm,
5112 SplatUndef.getZExtValue(), SplatBitSize,
5113 DAG, VmovVT, VT.is128BitVector(),
5115 if (Val.getNode()) {
5116 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5117 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5120 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5121 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5122 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5124 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5125 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5131 // Scan through the operands to see if only one value is used.
5133 // As an optimisation, even if more than one value is used it may be more
5134 // profitable to splat with one value then change some lanes.
5136 // Heuristically we decide to do this if the vector has a "dominant" value,
5137 // defined as splatted to more than half of the lanes.
5138 unsigned NumElts = VT.getVectorNumElements();
5139 bool isOnlyLowElement = true;
5140 bool usesOnlyOneValue = true;
5141 bool hasDominantValue = false;
5142 bool isConstant = true;
5144 // Map of the number of times a particular SDValue appears in the
5146 DenseMap<SDValue, unsigned> ValueCounts;
5148 for (unsigned i = 0; i < NumElts; ++i) {
5149 SDValue V = Op.getOperand(i);
5150 if (V.getOpcode() == ISD::UNDEF)
5153 isOnlyLowElement = false;
5154 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5157 ValueCounts.insert(std::make_pair(V, 0));
5158 unsigned &Count = ValueCounts[V];
5160 // Is this value dominant? (takes up more than half of the lanes)
5161 if (++Count > (NumElts / 2)) {
5162 hasDominantValue = true;
5166 if (ValueCounts.size() != 1)
5167 usesOnlyOneValue = false;
5168 if (!Value.getNode() && ValueCounts.size() > 0)
5169 Value = ValueCounts.begin()->first;
5171 if (ValueCounts.size() == 0)
5172 return DAG.getUNDEF(VT);
5174 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5175 // Keep going if we are hitting this case.
5176 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5177 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5179 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5181 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5182 // i32 and try again.
5183 if (hasDominantValue && EltSize <= 32) {
5187 // If we are VDUPing a value that comes directly from a vector, that will
5188 // cause an unnecessary move to and from a GPR, where instead we could
5189 // just use VDUPLANE. We can only do this if the lane being extracted
5190 // is at a constant index, as the VDUP from lane instructions only have
5191 // constant-index forms.
5192 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5193 isa<ConstantSDNode>(Value->getOperand(1))) {
5194 // We need to create a new undef vector to use for the VDUPLANE if the
5195 // size of the vector from which we get the value is different than the
5196 // size of the vector that we need to create. We will insert the element
5197 // such that the register coalescer will remove unnecessary copies.
5198 if (VT != Value->getOperand(0).getValueType()) {
5199 ConstantSDNode *constIndex;
5200 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5201 assert(constIndex && "The index is not a constant!");
5202 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5203 VT.getVectorNumElements();
5204 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5205 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5206 Value, DAG.getConstant(index, MVT::i32)),
5207 DAG.getConstant(index, MVT::i32));
5209 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5210 Value->getOperand(0), Value->getOperand(1));
5212 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5214 if (!usesOnlyOneValue) {
5215 // The dominant value was splatted as 'N', but we now have to insert
5216 // all differing elements.
5217 for (unsigned I = 0; I < NumElts; ++I) {
5218 if (Op.getOperand(I) == Value)
5220 SmallVector<SDValue, 3> Ops;
5222 Ops.push_back(Op.getOperand(I));
5223 Ops.push_back(DAG.getConstant(I, MVT::i32));
5224 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5229 if (VT.getVectorElementType().isFloatingPoint()) {
5230 SmallVector<SDValue, 8> Ops;
5231 for (unsigned i = 0; i < NumElts; ++i)
5232 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5234 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5235 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5236 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5238 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5240 if (usesOnlyOneValue) {
5241 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5242 if (isConstant && Val.getNode())
5243 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5247 // If all elements are constants and the case above didn't get hit, fall back
5248 // to the default expansion, which will generate a load from the constant
5253 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5255 SDValue shuffle = ReconstructShuffle(Op, DAG);
5256 if (shuffle != SDValue())
5260 // Vectors with 32- or 64-bit elements can be built by directly assigning
5261 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5262 // will be legalized.
5263 if (EltSize >= 32) {
5264 // Do the expansion with floating-point types, since that is what the VFP
5265 // registers are defined to use, and since i64 is not legal.
5266 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5267 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5268 SmallVector<SDValue, 8> Ops;
5269 for (unsigned i = 0; i < NumElts; ++i)
5270 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5271 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5272 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5275 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5276 // know the default expansion would otherwise fall back on something even
5277 // worse. For a vector with one or two non-undef values, that's
5278 // scalar_to_vector for the elements followed by a shuffle (provided the
5279 // shuffle is valid for the target) and materialization element by element
5280 // on the stack followed by a load for everything else.
5281 if (!isConstant && !usesOnlyOneValue) {
5282 SDValue Vec = DAG.getUNDEF(VT);
5283 for (unsigned i = 0 ; i < NumElts; ++i) {
5284 SDValue V = Op.getOperand(i);
5285 if (V.getOpcode() == ISD::UNDEF)
5287 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5288 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5296 // Gather data to see if the operation can be modelled as a
5297 // shuffle in combination with VEXTs.
5298 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5299 SelectionDAG &DAG) const {
5301 EVT VT = Op.getValueType();
5302 unsigned NumElts = VT.getVectorNumElements();
5304 SmallVector<SDValue, 2> SourceVecs;
5305 SmallVector<unsigned, 2> MinElts;
5306 SmallVector<unsigned, 2> MaxElts;
5308 for (unsigned i = 0; i < NumElts; ++i) {
5309 SDValue V = Op.getOperand(i);
5310 if (V.getOpcode() == ISD::UNDEF)
5312 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5313 // A shuffle can only come from building a vector from various
5314 // elements of other vectors.
5316 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5317 VT.getVectorElementType()) {
5318 // This code doesn't know how to handle shuffles where the vector
5319 // element types do not match (this happens because type legalization
5320 // promotes the return type of EXTRACT_VECTOR_ELT).
5321 // FIXME: It might be appropriate to extend this code to handle
5322 // mismatched types.
5326 // Record this extraction against the appropriate vector if possible...
5327 SDValue SourceVec = V.getOperand(0);
5328 // If the element number isn't a constant, we can't effectively
5329 // analyze what's going on.
5330 if (!isa<ConstantSDNode>(V.getOperand(1)))
5332 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5333 bool FoundSource = false;
5334 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5335 if (SourceVecs[j] == SourceVec) {
5336 if (MinElts[j] > EltNo)
5338 if (MaxElts[j] < EltNo)
5345 // Or record a new source if not...
5347 SourceVecs.push_back(SourceVec);
5348 MinElts.push_back(EltNo);
5349 MaxElts.push_back(EltNo);
5353 // Currently only do something sane when at most two source vectors
5355 if (SourceVecs.size() > 2)
5358 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5359 int VEXTOffsets[2] = {0, 0};
5361 // This loop extracts the usage patterns of the source vectors
5362 // and prepares appropriate SDValues for a shuffle if possible.
5363 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5364 if (SourceVecs[i].getValueType() == VT) {
5365 // No VEXT necessary
5366 ShuffleSrcs[i] = SourceVecs[i];
5369 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5370 // It probably isn't worth padding out a smaller vector just to
5371 // break it down again in a shuffle.
5375 // Since only 64-bit and 128-bit vectors are legal on ARM and
5376 // we've eliminated the other cases...
5377 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5378 "unexpected vector sizes in ReconstructShuffle");
5380 if (MaxElts[i] - MinElts[i] >= NumElts) {
5381 // Span too large for a VEXT to cope
5385 if (MinElts[i] >= NumElts) {
5386 // The extraction can just take the second half
5387 VEXTOffsets[i] = NumElts;
5388 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5390 DAG.getIntPtrConstant(NumElts));
5391 } else if (MaxElts[i] < NumElts) {
5392 // The extraction can just take the first half
5394 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5396 DAG.getIntPtrConstant(0));
5398 // An actual VEXT is needed
5399 VEXTOffsets[i] = MinElts[i];
5400 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5402 DAG.getIntPtrConstant(0));
5403 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5405 DAG.getIntPtrConstant(NumElts));
5406 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5407 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5411 SmallVector<int, 8> Mask;
5413 for (unsigned i = 0; i < NumElts; ++i) {
5414 SDValue Entry = Op.getOperand(i);
5415 if (Entry.getOpcode() == ISD::UNDEF) {
5420 SDValue ExtractVec = Entry.getOperand(0);
5421 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5422 .getOperand(1))->getSExtValue();
5423 if (ExtractVec == SourceVecs[0]) {
5424 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5426 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5430 // Final check before we try to produce nonsense...
5431 if (isShuffleMaskLegal(Mask, VT))
5432 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5438 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5439 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5440 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5441 /// are assumed to be legal.
5443 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5445 if (VT.getVectorNumElements() == 4 &&
5446 (VT.is128BitVector() || VT.is64BitVector())) {
5447 unsigned PFIndexes[4];
5448 for (unsigned i = 0; i != 4; ++i) {
5452 PFIndexes[i] = M[i];
5455 // Compute the index in the perfect shuffle table.
5456 unsigned PFTableIndex =
5457 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5458 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5459 unsigned Cost = (PFEntry >> 30);
5466 unsigned Imm, WhichResult;
5468 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5469 return (EltSize >= 32 ||
5470 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5471 isVREVMask(M, VT, 64) ||
5472 isVREVMask(M, VT, 32) ||
5473 isVREVMask(M, VT, 16) ||
5474 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5475 isVTBLMask(M, VT) ||
5476 isVTRNMask(M, VT, WhichResult) ||
5477 isVUZPMask(M, VT, WhichResult) ||
5478 isVZIPMask(M, VT, WhichResult) ||
5479 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5480 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5481 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5482 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5485 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5486 /// the specified operations to build the shuffle.
5487 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5488 SDValue RHS, SelectionDAG &DAG,
5490 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5491 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5492 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5495 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5504 OP_VUZPL, // VUZP, left result
5505 OP_VUZPR, // VUZP, right result
5506 OP_VZIPL, // VZIP, left result
5507 OP_VZIPR, // VZIP, right result
5508 OP_VTRNL, // VTRN, left result
5509 OP_VTRNR // VTRN, right result
5512 if (OpNum == OP_COPY) {
5513 if (LHSID == (1*9+2)*9+3) return LHS;
5514 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5518 SDValue OpLHS, OpRHS;
5519 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5520 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5521 EVT VT = OpLHS.getValueType();
5524 default: llvm_unreachable("Unknown shuffle opcode!");
5526 // VREV divides the vector in half and swaps within the half.
5527 if (VT.getVectorElementType() == MVT::i32 ||
5528 VT.getVectorElementType() == MVT::f32)
5529 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5530 // vrev <4 x i16> -> VREV32
5531 if (VT.getVectorElementType() == MVT::i16)
5532 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5533 // vrev <4 x i8> -> VREV16
5534 assert(VT.getVectorElementType() == MVT::i8);
5535 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5540 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5541 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5545 return DAG.getNode(ARMISD::VEXT, dl, VT,
5547 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5550 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5551 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5554 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5555 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5558 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5559 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5563 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5564 ArrayRef<int> ShuffleMask,
5565 SelectionDAG &DAG) {
5566 // Check to see if we can use the VTBL instruction.
5567 SDValue V1 = Op.getOperand(0);
5568 SDValue V2 = Op.getOperand(1);
5571 SmallVector<SDValue, 8> VTBLMask;
5572 for (ArrayRef<int>::iterator
5573 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5574 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5576 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5577 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5578 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5580 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5581 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5584 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5585 SelectionDAG &DAG) {
5587 SDValue OpLHS = Op.getOperand(0);
5588 EVT VT = OpLHS.getValueType();
5590 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5591 "Expect an v8i16/v16i8 type");
5592 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5593 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5594 // extract the first 8 bytes into the top double word and the last 8 bytes
5595 // into the bottom double word. The v8i16 case is similar.
5596 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5597 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5598 DAG.getConstant(ExtractNum, MVT::i32));
5601 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5602 SDValue V1 = Op.getOperand(0);
5603 SDValue V2 = Op.getOperand(1);
5605 EVT VT = Op.getValueType();
5606 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5608 // Convert shuffles that are directly supported on NEON to target-specific
5609 // DAG nodes, instead of keeping them as shuffles and matching them again
5610 // during code selection. This is more efficient and avoids the possibility
5611 // of inconsistencies between legalization and selection.
5612 // FIXME: floating-point vectors should be canonicalized to integer vectors
5613 // of the same time so that they get CSEd properly.
5614 ArrayRef<int> ShuffleMask = SVN->getMask();
5616 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5617 if (EltSize <= 32) {
5618 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5619 int Lane = SVN->getSplatIndex();
5620 // If this is undef splat, generate it via "just" vdup, if possible.
5621 if (Lane == -1) Lane = 0;
5623 // Test if V1 is a SCALAR_TO_VECTOR.
5624 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5625 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5627 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5628 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5630 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5631 !isa<ConstantSDNode>(V1.getOperand(0))) {
5632 bool IsScalarToVector = true;
5633 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5634 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5635 IsScalarToVector = false;
5638 if (IsScalarToVector)
5639 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5641 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5642 DAG.getConstant(Lane, MVT::i32));
5647 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5650 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5651 DAG.getConstant(Imm, MVT::i32));
5654 if (isVREVMask(ShuffleMask, VT, 64))
5655 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5656 if (isVREVMask(ShuffleMask, VT, 32))
5657 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5658 if (isVREVMask(ShuffleMask, VT, 16))
5659 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5661 if (V2->getOpcode() == ISD::UNDEF &&
5662 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5663 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5664 DAG.getConstant(Imm, MVT::i32));
5667 // Check for Neon shuffles that modify both input vectors in place.
5668 // If both results are used, i.e., if there are two shuffles with the same
5669 // source operands and with masks corresponding to both results of one of
5670 // these operations, DAG memoization will ensure that a single node is
5671 // used for both shuffles.
5672 unsigned WhichResult;
5673 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5674 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5675 V1, V2).getValue(WhichResult);
5676 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5677 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5678 V1, V2).getValue(WhichResult);
5679 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5680 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5681 V1, V2).getValue(WhichResult);
5683 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5684 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5685 V1, V1).getValue(WhichResult);
5686 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5687 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5688 V1, V1).getValue(WhichResult);
5689 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5690 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5691 V1, V1).getValue(WhichResult);
5694 // If the shuffle is not directly supported and it has 4 elements, use
5695 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5696 unsigned NumElts = VT.getVectorNumElements();
5698 unsigned PFIndexes[4];
5699 for (unsigned i = 0; i != 4; ++i) {
5700 if (ShuffleMask[i] < 0)
5703 PFIndexes[i] = ShuffleMask[i];
5706 // Compute the index in the perfect shuffle table.
5707 unsigned PFTableIndex =
5708 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5709 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5710 unsigned Cost = (PFEntry >> 30);
5713 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5716 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5717 if (EltSize >= 32) {
5718 // Do the expansion with floating-point types, since that is what the VFP
5719 // registers are defined to use, and since i64 is not legal.
5720 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5721 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5722 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5723 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5724 SmallVector<SDValue, 8> Ops;
5725 for (unsigned i = 0; i < NumElts; ++i) {
5726 if (ShuffleMask[i] < 0)
5727 Ops.push_back(DAG.getUNDEF(EltVT));
5729 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5730 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5731 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5734 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5735 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5738 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5739 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5741 if (VT == MVT::v8i8) {
5742 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5743 if (NewOp.getNode())
5750 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5751 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5752 SDValue Lane = Op.getOperand(2);
5753 if (!isa<ConstantSDNode>(Lane))
5759 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5760 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5761 SDValue Lane = Op.getOperand(1);
5762 if (!isa<ConstantSDNode>(Lane))
5765 SDValue Vec = Op.getOperand(0);
5766 if (Op.getValueType() == MVT::i32 &&
5767 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5769 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5775 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5776 // The only time a CONCAT_VECTORS operation can have legal types is when
5777 // two 64-bit vectors are concatenated to a 128-bit vector.
5778 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5779 "unexpected CONCAT_VECTORS");
5781 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5782 SDValue Op0 = Op.getOperand(0);
5783 SDValue Op1 = Op.getOperand(1);
5784 if (Op0.getOpcode() != ISD::UNDEF)
5785 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5786 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5787 DAG.getIntPtrConstant(0));
5788 if (Op1.getOpcode() != ISD::UNDEF)
5789 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5790 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5791 DAG.getIntPtrConstant(1));
5792 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5795 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5796 /// element has been zero/sign-extended, depending on the isSigned parameter,
5797 /// from an integer type half its size.
5798 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5800 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5801 EVT VT = N->getValueType(0);
5802 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5803 SDNode *BVN = N->getOperand(0).getNode();
5804 if (BVN->getValueType(0) != MVT::v4i32 ||
5805 BVN->getOpcode() != ISD::BUILD_VECTOR)
5807 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5808 unsigned HiElt = 1 - LoElt;
5809 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5810 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5811 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5812 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5813 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5816 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5817 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5820 if (Hi0->isNullValue() && Hi1->isNullValue())
5826 if (N->getOpcode() != ISD::BUILD_VECTOR)
5829 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5830 SDNode *Elt = N->getOperand(i).getNode();
5831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5832 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5833 unsigned HalfSize = EltSize / 2;
5835 if (!isIntN(HalfSize, C->getSExtValue()))
5838 if (!isUIntN(HalfSize, C->getZExtValue()))
5849 /// isSignExtended - Check if a node is a vector value that is sign-extended
5850 /// or a constant BUILD_VECTOR with sign-extended elements.
5851 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5852 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5854 if (isExtendedBUILD_VECTOR(N, DAG, true))
5859 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5860 /// or a constant BUILD_VECTOR with zero-extended elements.
5861 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5862 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5864 if (isExtendedBUILD_VECTOR(N, DAG, false))
5869 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5870 if (OrigVT.getSizeInBits() >= 64)
5873 assert(OrigVT.isSimple() && "Expecting a simple value type");
5875 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5876 switch (OrigSimpleTy) {
5877 default: llvm_unreachable("Unexpected Vector Type");
5886 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5887 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5888 /// We insert the required extension here to get the vector to fill a D register.
5889 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5892 unsigned ExtOpcode) {
5893 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5894 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5895 // 64-bits we need to insert a new extension so that it will be 64-bits.
5896 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5897 if (OrigTy.getSizeInBits() >= 64)
5900 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5901 EVT NewVT = getExtensionTo64Bits(OrigTy);
5903 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5906 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5907 /// does not do any sign/zero extension. If the original vector is less
5908 /// than 64 bits, an appropriate extension will be added after the load to
5909 /// reach a total size of 64 bits. We have to add the extension separately
5910 /// because ARM does not have a sign/zero extending load for vectors.
5911 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5912 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5914 // The load already has the right type.
5915 if (ExtendedTy == LD->getMemoryVT())
5916 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5917 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5918 LD->isNonTemporal(), LD->isInvariant(),
5919 LD->getAlignment());
5921 // We need to create a zextload/sextload. We cannot just create a load
5922 // followed by a zext/zext node because LowerMUL is also run during normal
5923 // operation legalization where we can't create illegal types.
5924 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5925 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5926 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5927 LD->isNonTemporal(), LD->getAlignment());
5930 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5931 /// extending load, or BUILD_VECTOR with extended elements, return the
5932 /// unextended value. The unextended vector should be 64 bits so that it can
5933 /// be used as an operand to a VMULL instruction. If the original vector size
5934 /// before extension is less than 64 bits we add a an extension to resize
5935 /// the vector to 64 bits.
5936 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5937 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5938 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5939 N->getOperand(0)->getValueType(0),
5943 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5944 return SkipLoadExtensionForVMULL(LD, DAG);
5946 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5947 // have been legalized as a BITCAST from v4i32.
5948 if (N->getOpcode() == ISD::BITCAST) {
5949 SDNode *BVN = N->getOperand(0).getNode();
5950 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5951 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5952 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5953 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5954 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5956 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5957 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5958 EVT VT = N->getValueType(0);
5959 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5960 unsigned NumElts = VT.getVectorNumElements();
5961 MVT TruncVT = MVT::getIntegerVT(EltSize);
5962 SmallVector<SDValue, 8> Ops;
5963 for (unsigned i = 0; i != NumElts; ++i) {
5964 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5965 const APInt &CInt = C->getAPIntValue();
5966 // Element types smaller than 32 bits are not legal, so use i32 elements.
5967 // The values are implicitly truncated so sext vs. zext doesn't matter.
5968 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5970 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5971 MVT::getVectorVT(TruncVT, NumElts), Ops);
5974 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5975 unsigned Opcode = N->getOpcode();
5976 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5977 SDNode *N0 = N->getOperand(0).getNode();
5978 SDNode *N1 = N->getOperand(1).getNode();
5979 return N0->hasOneUse() && N1->hasOneUse() &&
5980 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5985 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5986 unsigned Opcode = N->getOpcode();
5987 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5988 SDNode *N0 = N->getOperand(0).getNode();
5989 SDNode *N1 = N->getOperand(1).getNode();
5990 return N0->hasOneUse() && N1->hasOneUse() &&
5991 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5996 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5997 // Multiplications are only custom-lowered for 128-bit vectors so that
5998 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5999 EVT VT = Op.getValueType();
6000 assert(VT.is128BitVector() && VT.isInteger() &&
6001 "unexpected type for custom-lowering ISD::MUL");
6002 SDNode *N0 = Op.getOperand(0).getNode();
6003 SDNode *N1 = Op.getOperand(1).getNode();
6004 unsigned NewOpc = 0;
6006 bool isN0SExt = isSignExtended(N0, DAG);
6007 bool isN1SExt = isSignExtended(N1, DAG);
6008 if (isN0SExt && isN1SExt)
6009 NewOpc = ARMISD::VMULLs;
6011 bool isN0ZExt = isZeroExtended(N0, DAG);
6012 bool isN1ZExt = isZeroExtended(N1, DAG);
6013 if (isN0ZExt && isN1ZExt)
6014 NewOpc = ARMISD::VMULLu;
6015 else if (isN1SExt || isN1ZExt) {
6016 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6017 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6018 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6019 NewOpc = ARMISD::VMULLs;
6021 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6022 NewOpc = ARMISD::VMULLu;
6024 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6026 NewOpc = ARMISD::VMULLu;
6032 if (VT == MVT::v2i64)
6033 // Fall through to expand this. It is not legal.
6036 // Other vector multiplications are legal.
6041 // Legalize to a VMULL instruction.
6044 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6046 Op0 = SkipExtensionForVMULL(N0, DAG);
6047 assert(Op0.getValueType().is64BitVector() &&
6048 Op1.getValueType().is64BitVector() &&
6049 "unexpected types for extended operands to VMULL");
6050 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6053 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6054 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6061 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6062 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6063 EVT Op1VT = Op1.getValueType();
6064 return DAG.getNode(N0->getOpcode(), DL, VT,
6065 DAG.getNode(NewOpc, DL, VT,
6066 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6067 DAG.getNode(NewOpc, DL, VT,
6068 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6072 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6074 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6075 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6076 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6077 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6078 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6079 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6080 // Get reciprocal estimate.
6081 // float4 recip = vrecpeq_f32(yf);
6082 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6083 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6084 // Because char has a smaller range than uchar, we can actually get away
6085 // without any newton steps. This requires that we use a weird bias
6086 // of 0xb000, however (again, this has been exhaustively tested).
6087 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6088 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6089 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6090 Y = DAG.getConstant(0xb000, MVT::i32);
6091 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6092 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6093 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6094 // Convert back to short.
6095 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6096 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6101 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6103 // Convert to float.
6104 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6105 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6106 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6107 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6108 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6109 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6111 // Use reciprocal estimate and one refinement step.
6112 // float4 recip = vrecpeq_f32(yf);
6113 // recip *= vrecpsq_f32(yf, recip);
6114 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6115 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6116 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6117 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6119 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6120 // Because short has a smaller range than ushort, we can actually get away
6121 // with only a single newton step. This requires that we use a weird bias
6122 // of 89, however (again, this has been exhaustively tested).
6123 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6124 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6125 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6126 N1 = DAG.getConstant(0x89, MVT::i32);
6127 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6128 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6129 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6130 // Convert back to integer and return.
6131 // return vmovn_s32(vcvt_s32_f32(result));
6132 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6133 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6137 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6138 EVT VT = Op.getValueType();
6139 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6140 "unexpected type for custom-lowering ISD::SDIV");
6143 SDValue N0 = Op.getOperand(0);
6144 SDValue N1 = Op.getOperand(1);
6147 if (VT == MVT::v8i8) {
6148 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6149 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6151 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6152 DAG.getIntPtrConstant(4));
6153 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6154 DAG.getIntPtrConstant(4));
6155 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6156 DAG.getIntPtrConstant(0));
6157 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6158 DAG.getIntPtrConstant(0));
6160 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6161 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6163 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6164 N0 = LowerCONCAT_VECTORS(N0, DAG);
6166 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6169 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6172 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6173 EVT VT = Op.getValueType();
6174 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6175 "unexpected type for custom-lowering ISD::UDIV");
6178 SDValue N0 = Op.getOperand(0);
6179 SDValue N1 = Op.getOperand(1);
6182 if (VT == MVT::v8i8) {
6183 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6184 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6186 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6187 DAG.getIntPtrConstant(4));
6188 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6189 DAG.getIntPtrConstant(4));
6190 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6191 DAG.getIntPtrConstant(0));
6192 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6193 DAG.getIntPtrConstant(0));
6195 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6196 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6198 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6199 N0 = LowerCONCAT_VECTORS(N0, DAG);
6201 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6202 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6207 // v4i16 sdiv ... Convert to float.
6208 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6209 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6210 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6211 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6212 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6213 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6215 // Use reciprocal estimate and two refinement steps.
6216 // float4 recip = vrecpeq_f32(yf);
6217 // recip *= vrecpsq_f32(yf, recip);
6218 // recip *= vrecpsq_f32(yf, recip);
6219 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6220 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6221 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6222 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6224 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6225 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6226 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6228 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6229 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6230 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6231 // and that it will never cause us to return an answer too large).
6232 // float4 result = as_float4(as_int4(xf*recip) + 2);
6233 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6234 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6235 N1 = DAG.getConstant(2, MVT::i32);
6236 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6237 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6238 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6239 // Convert back to integer and return.
6240 // return vmovn_u32(vcvt_s32_f32(result));
6241 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6242 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6246 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6247 EVT VT = Op.getNode()->getValueType(0);
6248 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6251 bool ExtraOp = false;
6252 switch (Op.getOpcode()) {
6253 default: llvm_unreachable("Invalid code");
6254 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6255 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6256 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6257 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6261 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6263 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6264 Op.getOperand(1), Op.getOperand(2));
6267 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6268 assert(Subtarget->isTargetDarwin());
6270 // For iOS, we want to call an alternative entry point: __sincos_stret,
6271 // return values are passed via sret.
6273 SDValue Arg = Op.getOperand(0);
6274 EVT ArgVT = Arg.getValueType();
6275 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6277 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6278 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6280 // Pair of floats / doubles used to pass the result.
6281 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6283 // Create stack object for sret.
6284 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6285 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6286 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6287 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6293 Entry.Ty = RetTy->getPointerTo();
6294 Entry.isSExt = false;
6295 Entry.isZExt = false;
6296 Entry.isSRet = true;
6297 Args.push_back(Entry);
6301 Entry.isSExt = false;
6302 Entry.isZExt = false;
6303 Args.push_back(Entry);
6305 const char *LibcallName = (ArgVT == MVT::f64)
6306 ? "__sincos_stret" : "__sincosf_stret";
6307 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6309 TargetLowering::CallLoweringInfo CLI(DAG);
6310 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6311 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6313 .setDiscardResult();
6315 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6317 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6318 MachinePointerInfo(), false, false, false, 0);
6320 // Address of cos field.
6321 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6322 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6323 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6324 MachinePointerInfo(), false, false, false, 0);
6326 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6327 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6328 LoadSin.getValue(0), LoadCos.getValue(0));
6331 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6332 // Monotonic load/store is legal for all targets
6333 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6336 // Acquire/Release load/store is not legal for targets without a
6337 // dmb or equivalent available.
6341 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6342 SmallVectorImpl<SDValue> &Results,
6344 const ARMSubtarget *Subtarget) {
6346 SDValue Cycles32, OutChain;
6348 if (Subtarget->hasPerfMon()) {
6349 // Under Power Management extensions, the cycle-count is:
6350 // mrc p15, #0, <Rt>, c9, c13, #0
6351 SDValue Ops[] = { N->getOperand(0), // Chain
6352 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6353 DAG.getConstant(15, MVT::i32),
6354 DAG.getConstant(0, MVT::i32),
6355 DAG.getConstant(9, MVT::i32),
6356 DAG.getConstant(13, MVT::i32),
6357 DAG.getConstant(0, MVT::i32)
6360 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6361 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6362 OutChain = Cycles32.getValue(1);
6364 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6365 // there are older ARM CPUs that have implementation-specific ways of
6366 // obtaining this information (FIXME!).
6367 Cycles32 = DAG.getConstant(0, MVT::i32);
6368 OutChain = DAG.getEntryNode();
6372 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6373 Cycles32, DAG.getConstant(0, MVT::i32));
6374 Results.push_back(Cycles64);
6375 Results.push_back(OutChain);
6378 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6379 switch (Op.getOpcode()) {
6380 default: llvm_unreachable("Don't know how to custom lower this!");
6381 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6382 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6383 case ISD::GlobalAddress:
6384 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6385 default: llvm_unreachable("unknown object format");
6387 return LowerGlobalAddressWindows(Op, DAG);
6389 return LowerGlobalAddressELF(Op, DAG);
6391 return LowerGlobalAddressDarwin(Op, DAG);
6393 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6394 case ISD::SELECT: return LowerSELECT(Op, DAG);
6395 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6396 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6397 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6398 case ISD::VASTART: return LowerVASTART(Op, DAG);
6399 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6400 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6401 case ISD::SINT_TO_FP:
6402 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6403 case ISD::FP_TO_SINT:
6404 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6405 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6406 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6407 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6408 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6409 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6410 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6411 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6413 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6416 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6417 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6418 case ISD::SRL_PARTS:
6419 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6420 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6421 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6422 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6423 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6424 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6425 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6426 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6427 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6428 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6429 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6430 case ISD::MUL: return LowerMUL(Op, DAG);
6431 case ISD::SDIV: return LowerSDIV(Op, DAG);
6432 case ISD::UDIV: return LowerUDIV(Op, DAG);
6436 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6441 return LowerXALUO(Op, DAG);
6442 case ISD::ATOMIC_LOAD:
6443 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6444 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6446 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6447 case ISD::DYNAMIC_STACKALLOC:
6448 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6449 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6450 llvm_unreachable("Don't know how to custom lower this!");
6451 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6452 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6456 /// ReplaceNodeResults - Replace the results of node with an illegal result
6457 /// type with new values built out of custom code.
6458 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6459 SmallVectorImpl<SDValue>&Results,
6460 SelectionDAG &DAG) const {
6462 switch (N->getOpcode()) {
6464 llvm_unreachable("Don't know how to custom expand this!");
6466 Res = ExpandBITCAST(N, DAG);
6470 Res = Expand64BitShift(N, DAG, Subtarget);
6472 case ISD::READCYCLECOUNTER:
6473 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6477 Results.push_back(Res);
6480 //===----------------------------------------------------------------------===//
6481 // ARM Scheduler Hooks
6482 //===----------------------------------------------------------------------===//
6484 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6485 /// registers the function context.
6486 void ARMTargetLowering::
6487 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6488 MachineBasicBlock *DispatchBB, int FI) const {
6489 const TargetInstrInfo *TII =
6490 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6491 DebugLoc dl = MI->getDebugLoc();
6492 MachineFunction *MF = MBB->getParent();
6493 MachineRegisterInfo *MRI = &MF->getRegInfo();
6494 MachineConstantPool *MCP = MF->getConstantPool();
6495 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6496 const Function *F = MF->getFunction();
6498 bool isThumb = Subtarget->isThumb();
6499 bool isThumb2 = Subtarget->isThumb2();
6501 unsigned PCLabelId = AFI->createPICLabelUId();
6502 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6503 ARMConstantPoolValue *CPV =
6504 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6505 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6507 const TargetRegisterClass *TRC = isThumb ?
6508 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6509 (const TargetRegisterClass*)&ARM::GPRRegClass;
6511 // Grab constant pool and fixed stack memory operands.
6512 MachineMemOperand *CPMMO =
6513 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6514 MachineMemOperand::MOLoad, 4, 4);
6516 MachineMemOperand *FIMMOSt =
6517 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6518 MachineMemOperand::MOStore, 4, 4);
6520 // Load the address of the dispatch MBB into the jump buffer.
6522 // Incoming value: jbuf
6523 // ldr.n r5, LCPI1_1
6526 // str r5, [$jbuf, #+4] ; &jbuf[1]
6527 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6528 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6529 .addConstantPoolIndex(CPI)
6530 .addMemOperand(CPMMO));
6531 // Set the low bit because of thumb mode.
6532 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6534 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6535 .addReg(NewVReg1, RegState::Kill)
6537 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6538 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6539 .addReg(NewVReg2, RegState::Kill)
6541 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6542 .addReg(NewVReg3, RegState::Kill)
6544 .addImm(36) // &jbuf[1] :: pc
6545 .addMemOperand(FIMMOSt));
6546 } else if (isThumb) {
6547 // Incoming value: jbuf
6548 // ldr.n r1, LCPI1_4
6552 // add r2, $jbuf, #+4 ; &jbuf[1]
6554 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6555 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6556 .addConstantPoolIndex(CPI)
6557 .addMemOperand(CPMMO));
6558 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6559 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6560 .addReg(NewVReg1, RegState::Kill)
6562 // Set the low bit because of thumb mode.
6563 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6564 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6565 .addReg(ARM::CPSR, RegState::Define)
6567 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6568 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6569 .addReg(ARM::CPSR, RegState::Define)
6570 .addReg(NewVReg2, RegState::Kill)
6571 .addReg(NewVReg3, RegState::Kill));
6572 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6573 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6575 .addImm(36)); // &jbuf[1] :: pc
6576 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6577 .addReg(NewVReg4, RegState::Kill)
6578 .addReg(NewVReg5, RegState::Kill)
6580 .addMemOperand(FIMMOSt));
6582 // Incoming value: jbuf
6585 // str r1, [$jbuf, #+4] ; &jbuf[1]
6586 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6587 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6588 .addConstantPoolIndex(CPI)
6590 .addMemOperand(CPMMO));
6591 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6592 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6593 .addReg(NewVReg1, RegState::Kill)
6594 .addImm(PCLabelId));
6595 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6596 .addReg(NewVReg2, RegState::Kill)
6598 .addImm(36) // &jbuf[1] :: pc
6599 .addMemOperand(FIMMOSt));
6603 MachineBasicBlock *ARMTargetLowering::
6604 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6605 const TargetInstrInfo *TII =
6606 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6607 DebugLoc dl = MI->getDebugLoc();
6608 MachineFunction *MF = MBB->getParent();
6609 MachineRegisterInfo *MRI = &MF->getRegInfo();
6610 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6611 MachineFrameInfo *MFI = MF->getFrameInfo();
6612 int FI = MFI->getFunctionContextIndex();
6614 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6615 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6616 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6618 // Get a mapping of the call site numbers to all of the landing pads they're
6620 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6621 unsigned MaxCSNum = 0;
6622 MachineModuleInfo &MMI = MF->getMMI();
6623 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6625 if (!BB->isLandingPad()) continue;
6627 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6629 for (MachineBasicBlock::iterator
6630 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6631 if (!II->isEHLabel()) continue;
6633 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6634 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6636 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6637 for (SmallVectorImpl<unsigned>::iterator
6638 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6639 CSI != CSE; ++CSI) {
6640 CallSiteNumToLPad[*CSI].push_back(BB);
6641 MaxCSNum = std::max(MaxCSNum, *CSI);
6647 // Get an ordered list of the machine basic blocks for the jump table.
6648 std::vector<MachineBasicBlock*> LPadList;
6649 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6650 LPadList.reserve(CallSiteNumToLPad.size());
6651 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6652 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6653 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6654 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6655 LPadList.push_back(*II);
6656 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6660 assert(!LPadList.empty() &&
6661 "No landing pad destinations for the dispatch jump table!");
6663 // Create the jump table and associated information.
6664 MachineJumpTableInfo *JTI =
6665 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6666 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6667 unsigned UId = AFI->createJumpTableUId();
6668 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6670 // Create the MBBs for the dispatch code.
6672 // Shove the dispatch's address into the return slot in the function context.
6673 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6674 DispatchBB->setIsLandingPad();
6676 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6677 unsigned trap_opcode;
6678 if (Subtarget->isThumb())
6679 trap_opcode = ARM::tTRAP;
6681 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6683 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6684 DispatchBB->addSuccessor(TrapBB);
6686 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6687 DispatchBB->addSuccessor(DispContBB);
6690 MF->insert(MF->end(), DispatchBB);
6691 MF->insert(MF->end(), DispContBB);
6692 MF->insert(MF->end(), TrapBB);
6694 // Insert code into the entry block that creates and registers the function
6696 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6698 MachineMemOperand *FIMMOLd =
6699 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6700 MachineMemOperand::MOLoad |
6701 MachineMemOperand::MOVolatile, 4, 4);
6703 MachineInstrBuilder MIB;
6704 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6706 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6707 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6709 // Add a register mask with no preserved registers. This results in all
6710 // registers being marked as clobbered.
6711 MIB.addRegMask(RI.getNoPreservedMask());
6713 unsigned NumLPads = LPadList.size();
6714 if (Subtarget->isThumb2()) {
6715 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6716 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6719 .addMemOperand(FIMMOLd));
6721 if (NumLPads < 256) {
6722 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6724 .addImm(LPadList.size()));
6726 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6727 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6728 .addImm(NumLPads & 0xFFFF));
6730 unsigned VReg2 = VReg1;
6731 if ((NumLPads & 0xFFFF0000) != 0) {
6732 VReg2 = MRI->createVirtualRegister(TRC);
6733 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6735 .addImm(NumLPads >> 16));
6738 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6743 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6748 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6749 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6750 .addJumpTableIndex(MJTI)
6753 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6756 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6757 .addReg(NewVReg3, RegState::Kill)
6759 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6761 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6762 .addReg(NewVReg4, RegState::Kill)
6764 .addJumpTableIndex(MJTI)
6766 } else if (Subtarget->isThumb()) {
6767 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6768 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6771 .addMemOperand(FIMMOLd));
6773 if (NumLPads < 256) {
6774 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6778 MachineConstantPool *ConstantPool = MF->getConstantPool();
6779 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6780 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6782 // MachineConstantPool wants an explicit alignment.
6783 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6785 Align = getDataLayout()->getTypeAllocSize(C->getType());
6786 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6788 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6789 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6790 .addReg(VReg1, RegState::Define)
6791 .addConstantPoolIndex(Idx));
6792 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6797 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6802 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6803 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6804 .addReg(ARM::CPSR, RegState::Define)
6808 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6809 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6810 .addJumpTableIndex(MJTI)
6813 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6814 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6815 .addReg(ARM::CPSR, RegState::Define)
6816 .addReg(NewVReg2, RegState::Kill)
6819 MachineMemOperand *JTMMOLd =
6820 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6821 MachineMemOperand::MOLoad, 4, 4);
6823 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6824 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6825 .addReg(NewVReg4, RegState::Kill)
6827 .addMemOperand(JTMMOLd));
6829 unsigned NewVReg6 = NewVReg5;
6830 if (RelocM == Reloc::PIC_) {
6831 NewVReg6 = MRI->createVirtualRegister(TRC);
6832 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6833 .addReg(ARM::CPSR, RegState::Define)
6834 .addReg(NewVReg5, RegState::Kill)
6838 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6839 .addReg(NewVReg6, RegState::Kill)
6840 .addJumpTableIndex(MJTI)
6843 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6844 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6847 .addMemOperand(FIMMOLd));
6849 if (NumLPads < 256) {
6850 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6853 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6854 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6855 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6856 .addImm(NumLPads & 0xFFFF));
6858 unsigned VReg2 = VReg1;
6859 if ((NumLPads & 0xFFFF0000) != 0) {
6860 VReg2 = MRI->createVirtualRegister(TRC);
6861 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6863 .addImm(NumLPads >> 16));
6866 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6870 MachineConstantPool *ConstantPool = MF->getConstantPool();
6871 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6872 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6874 // MachineConstantPool wants an explicit alignment.
6875 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6877 Align = getDataLayout()->getTypeAllocSize(C->getType());
6878 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6880 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6881 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6882 .addReg(VReg1, RegState::Define)
6883 .addConstantPoolIndex(Idx)
6885 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6887 .addReg(VReg1, RegState::Kill));
6890 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6895 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6897 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6899 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6900 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6901 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6902 .addJumpTableIndex(MJTI)
6905 MachineMemOperand *JTMMOLd =
6906 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6907 MachineMemOperand::MOLoad, 4, 4);
6908 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6910 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6911 .addReg(NewVReg3, RegState::Kill)
6914 .addMemOperand(JTMMOLd));
6916 if (RelocM == Reloc::PIC_) {
6917 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6918 .addReg(NewVReg5, RegState::Kill)
6920 .addJumpTableIndex(MJTI)
6923 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6924 .addReg(NewVReg5, RegState::Kill)
6925 .addJumpTableIndex(MJTI)
6930 // Add the jump table entries as successors to the MBB.
6931 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6932 for (std::vector<MachineBasicBlock*>::iterator
6933 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6934 MachineBasicBlock *CurMBB = *I;
6935 if (SeenMBBs.insert(CurMBB))
6936 DispContBB->addSuccessor(CurMBB);
6939 // N.B. the order the invoke BBs are processed in doesn't matter here.
6940 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6941 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6942 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6943 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6944 MachineBasicBlock *BB = *I;
6946 // Remove the landing pad successor from the invoke block and replace it
6947 // with the new dispatch block.
6948 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6950 while (!Successors.empty()) {
6951 MachineBasicBlock *SMBB = Successors.pop_back_val();
6952 if (SMBB->isLandingPad()) {
6953 BB->removeSuccessor(SMBB);
6954 MBBLPads.push_back(SMBB);
6958 BB->addSuccessor(DispatchBB);
6960 // Find the invoke call and mark all of the callee-saved registers as
6961 // 'implicit defined' so that they're spilled. This prevents code from
6962 // moving instructions to before the EH block, where they will never be
6964 for (MachineBasicBlock::reverse_iterator
6965 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6966 if (!II->isCall()) continue;
6968 DenseMap<unsigned, bool> DefRegs;
6969 for (MachineInstr::mop_iterator
6970 OI = II->operands_begin(), OE = II->operands_end();
6972 if (!OI->isReg()) continue;
6973 DefRegs[OI->getReg()] = true;
6976 MachineInstrBuilder MIB(*MF, &*II);
6978 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6979 unsigned Reg = SavedRegs[i];
6980 if (Subtarget->isThumb2() &&
6981 !ARM::tGPRRegClass.contains(Reg) &&
6982 !ARM::hGPRRegClass.contains(Reg))
6984 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6986 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6989 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6996 // Mark all former landing pads as non-landing pads. The dispatch is the only
6998 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6999 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7000 (*I)->setIsLandingPad(false);
7002 // The instruction is gone now.
7003 MI->eraseFromParent();
7009 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7010 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7011 E = MBB->succ_end(); I != E; ++I)
7014 llvm_unreachable("Expecting a BB with two successors!");
7017 /// Return the load opcode for a given load size. If load size >= 8,
7018 /// neon opcode will be returned.
7019 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7021 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7022 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7024 return LdSize == 4 ? ARM::tLDRi
7025 : LdSize == 2 ? ARM::tLDRHi
7026 : LdSize == 1 ? ARM::tLDRBi : 0;
7028 return LdSize == 4 ? ARM::t2LDR_POST
7029 : LdSize == 2 ? ARM::t2LDRH_POST
7030 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7031 return LdSize == 4 ? ARM::LDR_POST_IMM
7032 : LdSize == 2 ? ARM::LDRH_POST
7033 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7036 /// Return the store opcode for a given store size. If store size >= 8,
7037 /// neon opcode will be returned.
7038 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7040 return StSize == 16 ? ARM::VST1q32wb_fixed
7041 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7043 return StSize == 4 ? ARM::tSTRi
7044 : StSize == 2 ? ARM::tSTRHi
7045 : StSize == 1 ? ARM::tSTRBi : 0;
7047 return StSize == 4 ? ARM::t2STR_POST
7048 : StSize == 2 ? ARM::t2STRH_POST
7049 : StSize == 1 ? ARM::t2STRB_POST : 0;
7050 return StSize == 4 ? ARM::STR_POST_IMM
7051 : StSize == 2 ? ARM::STRH_POST
7052 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7055 /// Emit a post-increment load operation with given size. The instructions
7056 /// will be added to BB at Pos.
7057 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7058 const TargetInstrInfo *TII, DebugLoc dl,
7059 unsigned LdSize, unsigned Data, unsigned AddrIn,
7060 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7061 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7062 assert(LdOpc != 0 && "Should have a load opcode");
7064 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7065 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7067 } else if (IsThumb1) {
7068 // load + update AddrIn
7069 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7070 .addReg(AddrIn).addImm(0));
7071 MachineInstrBuilder MIB =
7072 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7073 MIB = AddDefaultT1CC(MIB);
7074 MIB.addReg(AddrIn).addImm(LdSize);
7075 AddDefaultPred(MIB);
7076 } else if (IsThumb2) {
7077 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7078 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7081 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7082 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7083 .addReg(0).addImm(LdSize));
7087 /// Emit a post-increment store operation with given size. The instructions
7088 /// will be added to BB at Pos.
7089 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7090 const TargetInstrInfo *TII, DebugLoc dl,
7091 unsigned StSize, unsigned Data, unsigned AddrIn,
7092 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7093 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7094 assert(StOpc != 0 && "Should have a store opcode");
7096 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7097 .addReg(AddrIn).addImm(0).addReg(Data));
7098 } else if (IsThumb1) {
7099 // store + update AddrIn
7100 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7101 .addReg(AddrIn).addImm(0));
7102 MachineInstrBuilder MIB =
7103 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7104 MIB = AddDefaultT1CC(MIB);
7105 MIB.addReg(AddrIn).addImm(StSize);
7106 AddDefaultPred(MIB);
7107 } else if (IsThumb2) {
7108 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7109 .addReg(Data).addReg(AddrIn).addImm(StSize));
7111 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7112 .addReg(Data).addReg(AddrIn).addReg(0)
7118 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7119 MachineBasicBlock *BB) const {
7120 // This pseudo instruction has 3 operands: dst, src, size
7121 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7122 // Otherwise, we will generate unrolled scalar copies.
7123 const TargetInstrInfo *TII =
7124 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7125 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7126 MachineFunction::iterator It = BB;
7129 unsigned dest = MI->getOperand(0).getReg();
7130 unsigned src = MI->getOperand(1).getReg();
7131 unsigned SizeVal = MI->getOperand(2).getImm();
7132 unsigned Align = MI->getOperand(3).getImm();
7133 DebugLoc dl = MI->getDebugLoc();
7135 MachineFunction *MF = BB->getParent();
7136 MachineRegisterInfo &MRI = MF->getRegInfo();
7137 unsigned UnitSize = 0;
7138 const TargetRegisterClass *TRC = nullptr;
7139 const TargetRegisterClass *VecTRC = nullptr;
7141 bool IsThumb1 = Subtarget->isThumb1Only();
7142 bool IsThumb2 = Subtarget->isThumb2();
7146 } else if (Align & 2) {
7149 // Check whether we can use NEON instructions.
7150 if (!MF->getFunction()->getAttributes().
7151 hasAttribute(AttributeSet::FunctionIndex,
7152 Attribute::NoImplicitFloat) &&
7153 Subtarget->hasNEON()) {
7154 if ((Align % 16 == 0) && SizeVal >= 16)
7156 else if ((Align % 8 == 0) && SizeVal >= 8)
7159 // Can't use NEON instructions.
7164 // Select the correct opcode and register class for unit size load/store
7165 bool IsNeon = UnitSize >= 8;
7166 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7167 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7169 VecTRC = UnitSize == 16
7170 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7172 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7175 unsigned BytesLeft = SizeVal % UnitSize;
7176 unsigned LoopSize = SizeVal - BytesLeft;
7178 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7179 // Use LDR and STR to copy.
7180 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7181 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7182 unsigned srcIn = src;
7183 unsigned destIn = dest;
7184 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7185 unsigned srcOut = MRI.createVirtualRegister(TRC);
7186 unsigned destOut = MRI.createVirtualRegister(TRC);
7187 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7188 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7189 IsThumb1, IsThumb2);
7190 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7191 IsThumb1, IsThumb2);
7196 // Handle the leftover bytes with LDRB and STRB.
7197 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7198 // [destOut] = STRB_POST(scratch, destIn, 1)
7199 for (unsigned i = 0; i < BytesLeft; i++) {
7200 unsigned srcOut = MRI.createVirtualRegister(TRC);
7201 unsigned destOut = MRI.createVirtualRegister(TRC);
7202 unsigned scratch = MRI.createVirtualRegister(TRC);
7203 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7204 IsThumb1, IsThumb2);
7205 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7206 IsThumb1, IsThumb2);
7210 MI->eraseFromParent(); // The instruction is gone now.
7214 // Expand the pseudo op to a loop.
7217 // movw varEnd, # --> with thumb2
7219 // ldrcp varEnd, idx --> without thumb2
7220 // fallthrough --> loopMBB
7222 // PHI varPhi, varEnd, varLoop
7223 // PHI srcPhi, src, srcLoop
7224 // PHI destPhi, dst, destLoop
7225 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7226 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7227 // subs varLoop, varPhi, #UnitSize
7229 // fallthrough --> exitMBB
7231 // epilogue to handle left-over bytes
7232 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7233 // [destOut] = STRB_POST(scratch, destLoop, 1)
7234 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7235 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7236 MF->insert(It, loopMBB);
7237 MF->insert(It, exitMBB);
7239 // Transfer the remainder of BB and its successor edges to exitMBB.
7240 exitMBB->splice(exitMBB->begin(), BB,
7241 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7242 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7244 // Load an immediate to varEnd.
7245 unsigned varEnd = MRI.createVirtualRegister(TRC);
7247 unsigned Vtmp = varEnd;
7248 if ((LoopSize & 0xFFFF0000) != 0)
7249 Vtmp = MRI.createVirtualRegister(TRC);
7250 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7251 .addImm(LoopSize & 0xFFFF));
7253 if ((LoopSize & 0xFFFF0000) != 0)
7254 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7255 .addReg(Vtmp).addImm(LoopSize >> 16));
7257 MachineConstantPool *ConstantPool = MF->getConstantPool();
7258 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7259 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7261 // MachineConstantPool wants an explicit alignment.
7262 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7264 Align = getDataLayout()->getTypeAllocSize(C->getType());
7265 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7268 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7269 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7271 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7272 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7274 BB->addSuccessor(loopMBB);
7276 // Generate the loop body:
7277 // varPhi = PHI(varLoop, varEnd)
7278 // srcPhi = PHI(srcLoop, src)
7279 // destPhi = PHI(destLoop, dst)
7280 MachineBasicBlock *entryBB = BB;
7282 unsigned varLoop = MRI.createVirtualRegister(TRC);
7283 unsigned varPhi = MRI.createVirtualRegister(TRC);
7284 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7285 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7286 unsigned destLoop = MRI.createVirtualRegister(TRC);
7287 unsigned destPhi = MRI.createVirtualRegister(TRC);
7289 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7290 .addReg(varLoop).addMBB(loopMBB)
7291 .addReg(varEnd).addMBB(entryBB);
7292 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7293 .addReg(srcLoop).addMBB(loopMBB)
7294 .addReg(src).addMBB(entryBB);
7295 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7296 .addReg(destLoop).addMBB(loopMBB)
7297 .addReg(dest).addMBB(entryBB);
7299 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7300 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7301 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7302 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7303 IsThumb1, IsThumb2);
7304 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7305 IsThumb1, IsThumb2);
7307 // Decrement loop variable by UnitSize.
7309 MachineInstrBuilder MIB =
7310 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7311 MIB = AddDefaultT1CC(MIB);
7312 MIB.addReg(varPhi).addImm(UnitSize);
7313 AddDefaultPred(MIB);
7315 MachineInstrBuilder MIB =
7316 BuildMI(*BB, BB->end(), dl,
7317 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7318 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7319 MIB->getOperand(5).setReg(ARM::CPSR);
7320 MIB->getOperand(5).setIsDef(true);
7322 BuildMI(*BB, BB->end(), dl,
7323 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7324 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7326 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7327 BB->addSuccessor(loopMBB);
7328 BB->addSuccessor(exitMBB);
7330 // Add epilogue to handle BytesLeft.
7332 MachineInstr *StartOfExit = exitMBB->begin();
7334 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7335 // [destOut] = STRB_POST(scratch, destLoop, 1)
7336 unsigned srcIn = srcLoop;
7337 unsigned destIn = destLoop;
7338 for (unsigned i = 0; i < BytesLeft; i++) {
7339 unsigned srcOut = MRI.createVirtualRegister(TRC);
7340 unsigned destOut = MRI.createVirtualRegister(TRC);
7341 unsigned scratch = MRI.createVirtualRegister(TRC);
7342 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7343 IsThumb1, IsThumb2);
7344 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7345 IsThumb1, IsThumb2);
7350 MI->eraseFromParent(); // The instruction is gone now.
7355 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7356 MachineBasicBlock *MBB) const {
7357 const TargetMachine &TM = getTargetMachine();
7358 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7359 DebugLoc DL = MI->getDebugLoc();
7361 assert(Subtarget->isTargetWindows() &&
7362 "__chkstk is only supported on Windows");
7363 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7365 // __chkstk takes the number of words to allocate on the stack in R4, and
7366 // returns the stack adjustment in number of bytes in R4. This will not
7367 // clober any other registers (other than the obvious lr).
7369 // Although, technically, IP should be considered a register which may be
7370 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7371 // thumb-2 environment, so there is no interworking required. As a result, we
7372 // do not expect a veneer to be emitted by the linker, clobbering IP.
7374 // Each module receives its own copy of __chkstk, so no import thunk is
7375 // required, again, ensuring that IP is not clobbered.
7377 // Finally, although some linkers may theoretically provide a trampoline for
7378 // out of range calls (which is quite common due to a 32M range limitation of
7379 // branches for Thumb), we can generate the long-call version via
7380 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7383 switch (TM.getCodeModel()) {
7384 case CodeModel::Small:
7385 case CodeModel::Medium:
7386 case CodeModel::Default:
7387 case CodeModel::Kernel:
7388 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7389 .addImm((unsigned)ARMCC::AL).addReg(0)
7390 .addExternalSymbol("__chkstk")
7391 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7392 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7393 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7395 case CodeModel::Large:
7396 case CodeModel::JITDefault: {
7397 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7398 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7400 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7401 .addExternalSymbol("__chkstk");
7402 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7403 .addImm((unsigned)ARMCC::AL).addReg(0)
7404 .addReg(Reg, RegState::Kill)
7405 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7406 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7407 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7412 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7414 .addReg(ARM::SP).addReg(ARM::R4)));
7416 MI->eraseFromParent();
7421 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7422 MachineBasicBlock *BB) const {
7423 const TargetInstrInfo *TII =
7424 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7425 DebugLoc dl = MI->getDebugLoc();
7426 bool isThumb2 = Subtarget->isThumb2();
7427 switch (MI->getOpcode()) {
7430 llvm_unreachable("Unexpected instr type to insert");
7432 // The Thumb2 pre-indexed stores have the same MI operands, they just
7433 // define them differently in the .td files from the isel patterns, so
7434 // they need pseudos.
7435 case ARM::t2STR_preidx:
7436 MI->setDesc(TII->get(ARM::t2STR_PRE));
7438 case ARM::t2STRB_preidx:
7439 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7441 case ARM::t2STRH_preidx:
7442 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7445 case ARM::STRi_preidx:
7446 case ARM::STRBi_preidx: {
7447 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7448 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7449 // Decode the offset.
7450 unsigned Offset = MI->getOperand(4).getImm();
7451 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7452 Offset = ARM_AM::getAM2Offset(Offset);
7456 MachineMemOperand *MMO = *MI->memoperands_begin();
7457 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7458 .addOperand(MI->getOperand(0)) // Rn_wb
7459 .addOperand(MI->getOperand(1)) // Rt
7460 .addOperand(MI->getOperand(2)) // Rn
7461 .addImm(Offset) // offset (skip GPR==zero_reg)
7462 .addOperand(MI->getOperand(5)) // pred
7463 .addOperand(MI->getOperand(6))
7464 .addMemOperand(MMO);
7465 MI->eraseFromParent();
7468 case ARM::STRr_preidx:
7469 case ARM::STRBr_preidx:
7470 case ARM::STRH_preidx: {
7472 switch (MI->getOpcode()) {
7473 default: llvm_unreachable("unexpected opcode!");
7474 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7475 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7476 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7478 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7479 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7480 MIB.addOperand(MI->getOperand(i));
7481 MI->eraseFromParent();
7485 case ARM::tMOVCCr_pseudo: {
7486 // To "insert" a SELECT_CC instruction, we actually have to insert the
7487 // diamond control-flow pattern. The incoming instruction knows the
7488 // destination vreg to set, the condition code register to branch on, the
7489 // true/false values to select between, and a branch opcode to use.
7490 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7491 MachineFunction::iterator It = BB;
7497 // cmpTY ccX, r1, r2
7499 // fallthrough --> copy0MBB
7500 MachineBasicBlock *thisMBB = BB;
7501 MachineFunction *F = BB->getParent();
7502 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7503 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7504 F->insert(It, copy0MBB);
7505 F->insert(It, sinkMBB);
7507 // Transfer the remainder of BB and its successor edges to sinkMBB.
7508 sinkMBB->splice(sinkMBB->begin(), BB,
7509 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7510 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7512 BB->addSuccessor(copy0MBB);
7513 BB->addSuccessor(sinkMBB);
7515 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7516 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7519 // %FalseValue = ...
7520 // # fallthrough to sinkMBB
7523 // Update machine-CFG edges
7524 BB->addSuccessor(sinkMBB);
7527 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7530 BuildMI(*BB, BB->begin(), dl,
7531 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7532 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7533 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7535 MI->eraseFromParent(); // The pseudo instruction is gone now.
7540 case ARM::BCCZi64: {
7541 // If there is an unconditional branch to the other successor, remove it.
7542 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7544 // Compare both parts that make up the double comparison separately for
7546 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7548 unsigned LHS1 = MI->getOperand(1).getReg();
7549 unsigned LHS2 = MI->getOperand(2).getReg();
7551 AddDefaultPred(BuildMI(BB, dl,
7552 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7553 .addReg(LHS1).addImm(0));
7554 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7555 .addReg(LHS2).addImm(0)
7556 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7558 unsigned RHS1 = MI->getOperand(3).getReg();
7559 unsigned RHS2 = MI->getOperand(4).getReg();
7560 AddDefaultPred(BuildMI(BB, dl,
7561 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7562 .addReg(LHS1).addReg(RHS1));
7563 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7564 .addReg(LHS2).addReg(RHS2)
7565 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7568 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7569 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7570 if (MI->getOperand(0).getImm() == ARMCC::NE)
7571 std::swap(destMBB, exitMBB);
7573 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7574 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7576 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7578 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7580 MI->eraseFromParent(); // The pseudo instruction is gone now.
7584 case ARM::Int_eh_sjlj_setjmp:
7585 case ARM::Int_eh_sjlj_setjmp_nofp:
7586 case ARM::tInt_eh_sjlj_setjmp:
7587 case ARM::t2Int_eh_sjlj_setjmp:
7588 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7589 EmitSjLjDispatchBlock(MI, BB);
7594 // To insert an ABS instruction, we have to insert the
7595 // diamond control-flow pattern. The incoming instruction knows the
7596 // source vreg to test against 0, the destination vreg to set,
7597 // the condition code register to branch on, the
7598 // true/false values to select between, and a branch opcode to use.
7603 // BCC (branch to SinkBB if V0 >= 0)
7604 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7605 // SinkBB: V1 = PHI(V2, V3)
7606 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7607 MachineFunction::iterator BBI = BB;
7609 MachineFunction *Fn = BB->getParent();
7610 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7611 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7612 Fn->insert(BBI, RSBBB);
7613 Fn->insert(BBI, SinkBB);
7615 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7616 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7617 bool isThumb2 = Subtarget->isThumb2();
7618 MachineRegisterInfo &MRI = Fn->getRegInfo();
7619 // In Thumb mode S must not be specified if source register is the SP or
7620 // PC and if destination register is the SP, so restrict register class
7621 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7622 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7623 (const TargetRegisterClass*)&ARM::GPRRegClass);
7625 // Transfer the remainder of BB and its successor edges to sinkMBB.
7626 SinkBB->splice(SinkBB->begin(), BB,
7627 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7628 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7630 BB->addSuccessor(RSBBB);
7631 BB->addSuccessor(SinkBB);
7633 // fall through to SinkMBB
7634 RSBBB->addSuccessor(SinkBB);
7636 // insert a cmp at the end of BB
7637 AddDefaultPred(BuildMI(BB, dl,
7638 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7639 .addReg(ABSSrcReg).addImm(0));
7641 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7643 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7644 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7646 // insert rsbri in RSBBB
7647 // Note: BCC and rsbri will be converted into predicated rsbmi
7648 // by if-conversion pass
7649 BuildMI(*RSBBB, RSBBB->begin(), dl,
7650 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7651 .addReg(ABSSrcReg, RegState::Kill)
7652 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7654 // insert PHI in SinkBB,
7655 // reuse ABSDstReg to not change uses of ABS instruction
7656 BuildMI(*SinkBB, SinkBB->begin(), dl,
7657 TII->get(ARM::PHI), ABSDstReg)
7658 .addReg(NewRsbDstReg).addMBB(RSBBB)
7659 .addReg(ABSSrcReg).addMBB(BB);
7661 // remove ABS instruction
7662 MI->eraseFromParent();
7664 // return last added BB
7667 case ARM::COPY_STRUCT_BYVAL_I32:
7669 return EmitStructByval(MI, BB);
7670 case ARM::WIN__CHKSTK:
7671 return EmitLowered__chkstk(MI, BB);
7675 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7676 SDNode *Node) const {
7677 if (!MI->hasPostISelHook()) {
7678 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7679 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7683 const MCInstrDesc *MCID = &MI->getDesc();
7684 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7685 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7686 // operand is still set to noreg. If needed, set the optional operand's
7687 // register to CPSR, and remove the redundant implicit def.
7689 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7691 // Rename pseudo opcodes.
7692 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7694 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7695 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7696 MCID = &TII->get(NewOpc);
7698 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7699 "converted opcode should be the same except for cc_out");
7703 // Add the optional cc_out operand
7704 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7706 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7708 // Any ARM instruction that sets the 's' bit should specify an optional
7709 // "cc_out" operand in the last operand position.
7710 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7711 assert(!NewOpc && "Optional cc_out operand required");
7714 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7715 // since we already have an optional CPSR def.
7716 bool definesCPSR = false;
7717 bool deadCPSR = false;
7718 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7720 const MachineOperand &MO = MI->getOperand(i);
7721 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7725 MI->RemoveOperand(i);
7730 assert(!NewOpc && "Optional cc_out operand required");
7733 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7735 assert(!MI->getOperand(ccOutIdx).getReg() &&
7736 "expect uninitialized optional cc_out operand");
7740 // If this instruction was defined with an optional CPSR def and its dag node
7741 // had a live implicit CPSR def, then activate the optional CPSR def.
7742 MachineOperand &MO = MI->getOperand(ccOutIdx);
7743 MO.setReg(ARM::CPSR);
7747 //===----------------------------------------------------------------------===//
7748 // ARM Optimization Hooks
7749 //===----------------------------------------------------------------------===//
7751 // Helper function that checks if N is a null or all ones constant.
7752 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7753 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7756 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7759 // Return true if N is conditionally 0 or all ones.
7760 // Detects these expressions where cc is an i1 value:
7762 // (select cc 0, y) [AllOnes=0]
7763 // (select cc y, 0) [AllOnes=0]
7764 // (zext cc) [AllOnes=0]
7765 // (sext cc) [AllOnes=0/1]
7766 // (select cc -1, y) [AllOnes=1]
7767 // (select cc y, -1) [AllOnes=1]
7769 // Invert is set when N is the null/all ones constant when CC is false.
7770 // OtherOp is set to the alternative value of N.
7771 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7772 SDValue &CC, bool &Invert,
7774 SelectionDAG &DAG) {
7775 switch (N->getOpcode()) {
7776 default: return false;
7778 CC = N->getOperand(0);
7779 SDValue N1 = N->getOperand(1);
7780 SDValue N2 = N->getOperand(2);
7781 if (isZeroOrAllOnes(N1, AllOnes)) {
7786 if (isZeroOrAllOnes(N2, AllOnes)) {
7793 case ISD::ZERO_EXTEND:
7794 // (zext cc) can never be the all ones value.
7798 case ISD::SIGN_EXTEND: {
7799 EVT VT = N->getValueType(0);
7800 CC = N->getOperand(0);
7801 if (CC.getValueType() != MVT::i1)
7805 // When looking for an AllOnes constant, N is an sext, and the 'other'
7807 OtherOp = DAG.getConstant(0, VT);
7808 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7809 // When looking for a 0 constant, N can be zext or sext.
7810 OtherOp = DAG.getConstant(1, VT);
7812 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7818 // Combine a constant select operand into its use:
7820 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7821 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7822 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7823 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7824 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7826 // The transform is rejected if the select doesn't have a constant operand that
7827 // is null, or all ones when AllOnes is set.
7829 // Also recognize sext/zext from i1:
7831 // (add (zext cc), x) -> (select cc (add x, 1), x)
7832 // (add (sext cc), x) -> (select cc (add x, -1), x)
7834 // These transformations eventually create predicated instructions.
7836 // @param N The node to transform.
7837 // @param Slct The N operand that is a select.
7838 // @param OtherOp The other N operand (x above).
7839 // @param DCI Context.
7840 // @param AllOnes Require the select constant to be all ones instead of null.
7841 // @returns The new node, or SDValue() on failure.
7843 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7844 TargetLowering::DAGCombinerInfo &DCI,
7845 bool AllOnes = false) {
7846 SelectionDAG &DAG = DCI.DAG;
7847 EVT VT = N->getValueType(0);
7848 SDValue NonConstantVal;
7851 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7852 NonConstantVal, DAG))
7855 // Slct is now know to be the desired identity constant when CC is true.
7856 SDValue TrueVal = OtherOp;
7857 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7858 OtherOp, NonConstantVal);
7859 // Unless SwapSelectOps says CC should be false.
7861 std::swap(TrueVal, FalseVal);
7863 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7864 CCOp, TrueVal, FalseVal);
7867 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7869 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7870 TargetLowering::DAGCombinerInfo &DCI) {
7871 SDValue N0 = N->getOperand(0);
7872 SDValue N1 = N->getOperand(1);
7873 if (N0.getNode()->hasOneUse()) {
7874 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7875 if (Result.getNode())
7878 if (N1.getNode()->hasOneUse()) {
7879 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7880 if (Result.getNode())
7886 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7887 // (only after legalization).
7888 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7889 TargetLowering::DAGCombinerInfo &DCI,
7890 const ARMSubtarget *Subtarget) {
7892 // Only perform optimization if after legalize, and if NEON is available. We
7893 // also expected both operands to be BUILD_VECTORs.
7894 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7895 || N0.getOpcode() != ISD::BUILD_VECTOR
7896 || N1.getOpcode() != ISD::BUILD_VECTOR)
7899 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7900 EVT VT = N->getValueType(0);
7901 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7904 // Check that the vector operands are of the right form.
7905 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7906 // operands, where N is the size of the formed vector.
7907 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7908 // index such that we have a pair wise add pattern.
7910 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7911 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7913 SDValue Vec = N0->getOperand(0)->getOperand(0);
7914 SDNode *V = Vec.getNode();
7915 unsigned nextIndex = 0;
7917 // For each operands to the ADD which are BUILD_VECTORs,
7918 // check to see if each of their operands are an EXTRACT_VECTOR with
7919 // the same vector and appropriate index.
7920 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7921 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7922 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7924 SDValue ExtVec0 = N0->getOperand(i);
7925 SDValue ExtVec1 = N1->getOperand(i);
7927 // First operand is the vector, verify its the same.
7928 if (V != ExtVec0->getOperand(0).getNode() ||
7929 V != ExtVec1->getOperand(0).getNode())
7932 // Second is the constant, verify its correct.
7933 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7934 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7936 // For the constant, we want to see all the even or all the odd.
7937 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7938 || C1->getZExtValue() != nextIndex+1)
7947 // Create VPADDL node.
7948 SelectionDAG &DAG = DCI.DAG;
7949 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7951 // Build operand list.
7952 SmallVector<SDValue, 8> Ops;
7953 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7954 TLI.getPointerTy()));
7956 // Input is the vector.
7959 // Get widened type and narrowed type.
7961 unsigned numElem = VT.getVectorNumElements();
7963 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7964 switch (inputLaneType.getSimpleVT().SimpleTy) {
7965 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7966 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7967 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7969 llvm_unreachable("Invalid vector element type for padd optimization.");
7972 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7973 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7974 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7977 static SDValue findMUL_LOHI(SDValue V) {
7978 if (V->getOpcode() == ISD::UMUL_LOHI ||
7979 V->getOpcode() == ISD::SMUL_LOHI)
7984 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7985 TargetLowering::DAGCombinerInfo &DCI,
7986 const ARMSubtarget *Subtarget) {
7988 if (Subtarget->isThumb1Only()) return SDValue();
7990 // Only perform the checks after legalize when the pattern is available.
7991 if (DCI.isBeforeLegalize()) return SDValue();
7993 // Look for multiply add opportunities.
7994 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7995 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7996 // a glue link from the first add to the second add.
7997 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7998 // a S/UMLAL instruction.
8001 // \ / \ [no multiline comment]
8007 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8008 SDValue AddcOp0 = AddcNode->getOperand(0);
8009 SDValue AddcOp1 = AddcNode->getOperand(1);
8011 // Check if the two operands are from the same mul_lohi node.
8012 if (AddcOp0.getNode() == AddcOp1.getNode())
8015 assert(AddcNode->getNumValues() == 2 &&
8016 AddcNode->getValueType(0) == MVT::i32 &&
8017 "Expect ADDC with two result values. First: i32");
8019 // Check that we have a glued ADDC node.
8020 if (AddcNode->getValueType(1) != MVT::Glue)
8023 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8024 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8025 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8026 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8027 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8030 // Look for the glued ADDE.
8031 SDNode* AddeNode = AddcNode->getGluedUser();
8035 // Make sure it is really an ADDE.
8036 if (AddeNode->getOpcode() != ISD::ADDE)
8039 assert(AddeNode->getNumOperands() == 3 &&
8040 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8041 "ADDE node has the wrong inputs");
8043 // Check for the triangle shape.
8044 SDValue AddeOp0 = AddeNode->getOperand(0);
8045 SDValue AddeOp1 = AddeNode->getOperand(1);
8047 // Make sure that the ADDE operands are not coming from the same node.
8048 if (AddeOp0.getNode() == AddeOp1.getNode())
8051 // Find the MUL_LOHI node walking up ADDE's operands.
8052 bool IsLeftOperandMUL = false;
8053 SDValue MULOp = findMUL_LOHI(AddeOp0);
8054 if (MULOp == SDValue())
8055 MULOp = findMUL_LOHI(AddeOp1);
8057 IsLeftOperandMUL = true;
8058 if (MULOp == SDValue())
8061 // Figure out the right opcode.
8062 unsigned Opc = MULOp->getOpcode();
8063 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8065 // Figure out the high and low input values to the MLAL node.
8066 SDValue* HiMul = &MULOp;
8067 SDValue* HiAdd = nullptr;
8068 SDValue* LoMul = nullptr;
8069 SDValue* LowAdd = nullptr;
8071 if (IsLeftOperandMUL)
8077 if (AddcOp0->getOpcode() == Opc) {
8081 if (AddcOp1->getOpcode() == Opc) {
8089 if (LoMul->getNode() != HiMul->getNode())
8092 // Create the merged node.
8093 SelectionDAG &DAG = DCI.DAG;
8095 // Build operand list.
8096 SmallVector<SDValue, 8> Ops;
8097 Ops.push_back(LoMul->getOperand(0));
8098 Ops.push_back(LoMul->getOperand(1));
8099 Ops.push_back(*LowAdd);
8100 Ops.push_back(*HiAdd);
8102 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8103 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8105 // Replace the ADDs' nodes uses by the MLA node's values.
8106 SDValue HiMLALResult(MLALNode.getNode(), 1);
8107 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8109 SDValue LoMLALResult(MLALNode.getNode(), 0);
8110 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8112 // Return original node to notify the driver to stop replacing.
8113 SDValue resNode(AddcNode, 0);
8117 /// PerformADDCCombine - Target-specific dag combine transform from
8118 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8119 static SDValue PerformADDCCombine(SDNode *N,
8120 TargetLowering::DAGCombinerInfo &DCI,
8121 const ARMSubtarget *Subtarget) {
8123 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8127 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8128 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8129 /// called with the default operands, and if that fails, with commuted
8131 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8132 TargetLowering::DAGCombinerInfo &DCI,
8133 const ARMSubtarget *Subtarget){
8135 // Attempt to create vpaddl for this add.
8136 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8137 if (Result.getNode())
8140 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8141 if (N0.getNode()->hasOneUse()) {
8142 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8143 if (Result.getNode()) return Result;
8148 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8150 static SDValue PerformADDCombine(SDNode *N,
8151 TargetLowering::DAGCombinerInfo &DCI,
8152 const ARMSubtarget *Subtarget) {
8153 SDValue N0 = N->getOperand(0);
8154 SDValue N1 = N->getOperand(1);
8156 // First try with the default operand order.
8157 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8158 if (Result.getNode())
8161 // If that didn't work, try again with the operands commuted.
8162 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8165 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8167 static SDValue PerformSUBCombine(SDNode *N,
8168 TargetLowering::DAGCombinerInfo &DCI) {
8169 SDValue N0 = N->getOperand(0);
8170 SDValue N1 = N->getOperand(1);
8172 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8173 if (N1.getNode()->hasOneUse()) {
8174 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8175 if (Result.getNode()) return Result;
8181 /// PerformVMULCombine
8182 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8183 /// special multiplier accumulator forwarding.
8189 // However, for (A + B) * (A + B),
8196 static SDValue PerformVMULCombine(SDNode *N,
8197 TargetLowering::DAGCombinerInfo &DCI,
8198 const ARMSubtarget *Subtarget) {
8199 if (!Subtarget->hasVMLxForwarding())
8202 SelectionDAG &DAG = DCI.DAG;
8203 SDValue N0 = N->getOperand(0);
8204 SDValue N1 = N->getOperand(1);
8205 unsigned Opcode = N0.getOpcode();
8206 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8207 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8208 Opcode = N1.getOpcode();
8209 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8210 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8218 EVT VT = N->getValueType(0);
8220 SDValue N00 = N0->getOperand(0);
8221 SDValue N01 = N0->getOperand(1);
8222 return DAG.getNode(Opcode, DL, VT,
8223 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8224 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8227 static SDValue PerformMULCombine(SDNode *N,
8228 TargetLowering::DAGCombinerInfo &DCI,
8229 const ARMSubtarget *Subtarget) {
8230 SelectionDAG &DAG = DCI.DAG;
8232 if (Subtarget->isThumb1Only())
8235 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8238 EVT VT = N->getValueType(0);
8239 if (VT.is64BitVector() || VT.is128BitVector())
8240 return PerformVMULCombine(N, DCI, Subtarget);
8244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8248 int64_t MulAmt = C->getSExtValue();
8249 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8251 ShiftAmt = ShiftAmt & (32 - 1);
8252 SDValue V = N->getOperand(0);
8256 MulAmt >>= ShiftAmt;
8259 if (isPowerOf2_32(MulAmt - 1)) {
8260 // (mul x, 2^N + 1) => (add (shl x, N), x)
8261 Res = DAG.getNode(ISD::ADD, DL, VT,
8263 DAG.getNode(ISD::SHL, DL, VT,
8265 DAG.getConstant(Log2_32(MulAmt - 1),
8267 } else if (isPowerOf2_32(MulAmt + 1)) {
8268 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8269 Res = DAG.getNode(ISD::SUB, DL, VT,
8270 DAG.getNode(ISD::SHL, DL, VT,
8272 DAG.getConstant(Log2_32(MulAmt + 1),
8278 uint64_t MulAmtAbs = -MulAmt;
8279 if (isPowerOf2_32(MulAmtAbs + 1)) {
8280 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8281 Res = DAG.getNode(ISD::SUB, DL, VT,
8283 DAG.getNode(ISD::SHL, DL, VT,
8285 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8287 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8288 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8289 Res = DAG.getNode(ISD::ADD, DL, VT,
8291 DAG.getNode(ISD::SHL, DL, VT,
8293 DAG.getConstant(Log2_32(MulAmtAbs-1),
8295 Res = DAG.getNode(ISD::SUB, DL, VT,
8296 DAG.getConstant(0, MVT::i32),Res);
8303 Res = DAG.getNode(ISD::SHL, DL, VT,
8304 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8306 // Do not add new nodes to DAG combiner worklist.
8307 DCI.CombineTo(N, Res, false);
8311 static SDValue PerformANDCombine(SDNode *N,
8312 TargetLowering::DAGCombinerInfo &DCI,
8313 const ARMSubtarget *Subtarget) {
8315 // Attempt to use immediate-form VBIC
8316 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8318 EVT VT = N->getValueType(0);
8319 SelectionDAG &DAG = DCI.DAG;
8321 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8324 APInt SplatBits, SplatUndef;
8325 unsigned SplatBitSize;
8328 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8329 if (SplatBitSize <= 64) {
8331 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8332 SplatUndef.getZExtValue(), SplatBitSize,
8333 DAG, VbicVT, VT.is128BitVector(),
8335 if (Val.getNode()) {
8337 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8338 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8339 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8344 if (!Subtarget->isThumb1Only()) {
8345 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8346 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8347 if (Result.getNode())
8354 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8355 static SDValue PerformORCombine(SDNode *N,
8356 TargetLowering::DAGCombinerInfo &DCI,
8357 const ARMSubtarget *Subtarget) {
8358 // Attempt to use immediate-form VORR
8359 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8361 EVT VT = N->getValueType(0);
8362 SelectionDAG &DAG = DCI.DAG;
8364 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8367 APInt SplatBits, SplatUndef;
8368 unsigned SplatBitSize;
8370 if (BVN && Subtarget->hasNEON() &&
8371 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8372 if (SplatBitSize <= 64) {
8374 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8375 SplatUndef.getZExtValue(), SplatBitSize,
8376 DAG, VorrVT, VT.is128BitVector(),
8378 if (Val.getNode()) {
8380 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8381 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8382 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8387 if (!Subtarget->isThumb1Only()) {
8388 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8389 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8390 if (Result.getNode())
8394 // The code below optimizes (or (and X, Y), Z).
8395 // The AND operand needs to have a single user to make these optimizations
8397 SDValue N0 = N->getOperand(0);
8398 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8400 SDValue N1 = N->getOperand(1);
8402 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8403 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8404 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8406 unsigned SplatBitSize;
8409 APInt SplatBits0, SplatBits1;
8410 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8411 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8412 // Ensure that the second operand of both ands are constants
8413 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8414 HasAnyUndefs) && !HasAnyUndefs) {
8415 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8416 HasAnyUndefs) && !HasAnyUndefs) {
8417 // Ensure that the bit width of the constants are the same and that
8418 // the splat arguments are logical inverses as per the pattern we
8419 // are trying to simplify.
8420 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8421 SplatBits0 == ~SplatBits1) {
8422 // Canonicalize the vector type to make instruction selection
8424 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8425 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8429 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8435 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8438 // BFI is only available on V6T2+
8439 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8443 // 1) or (and A, mask), val => ARMbfi A, val, mask
8444 // iff (val & mask) == val
8446 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8447 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8448 // && mask == ~mask2
8449 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8450 // && ~mask == mask2
8451 // (i.e., copy a bitfield value into another bitfield of the same width)
8456 SDValue N00 = N0.getOperand(0);
8458 // The value and the mask need to be constants so we can verify this is
8459 // actually a bitfield set. If the mask is 0xffff, we can do better
8460 // via a movt instruction, so don't use BFI in that case.
8461 SDValue MaskOp = N0.getOperand(1);
8462 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8465 unsigned Mask = MaskC->getZExtValue();
8469 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8472 unsigned Val = N1C->getZExtValue();
8473 if ((Val & ~Mask) != Val)
8476 if (ARM::isBitFieldInvertedMask(Mask)) {
8477 Val >>= countTrailingZeros(~Mask);
8479 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8480 DAG.getConstant(Val, MVT::i32),
8481 DAG.getConstant(Mask, MVT::i32));
8483 // Do not add new nodes to DAG combiner worklist.
8484 DCI.CombineTo(N, Res, false);
8487 } else if (N1.getOpcode() == ISD::AND) {
8488 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8489 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8492 unsigned Mask2 = N11C->getZExtValue();
8494 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8496 if (ARM::isBitFieldInvertedMask(Mask) &&
8498 // The pack halfword instruction works better for masks that fit it,
8499 // so use that when it's available.
8500 if (Subtarget->hasT2ExtractPack() &&
8501 (Mask == 0xffff || Mask == 0xffff0000))
8504 unsigned amt = countTrailingZeros(Mask2);
8505 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8506 DAG.getConstant(amt, MVT::i32));
8507 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8508 DAG.getConstant(Mask, MVT::i32));
8509 // Do not add new nodes to DAG combiner worklist.
8510 DCI.CombineTo(N, Res, false);
8512 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8514 // The pack halfword instruction works better for masks that fit it,
8515 // so use that when it's available.
8516 if (Subtarget->hasT2ExtractPack() &&
8517 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8520 unsigned lsb = countTrailingZeros(Mask);
8521 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8522 DAG.getConstant(lsb, MVT::i32));
8523 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8524 DAG.getConstant(Mask2, MVT::i32));
8525 // Do not add new nodes to DAG combiner worklist.
8526 DCI.CombineTo(N, Res, false);
8531 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8532 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8533 ARM::isBitFieldInvertedMask(~Mask)) {
8534 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8535 // where lsb(mask) == #shamt and masked bits of B are known zero.
8536 SDValue ShAmt = N00.getOperand(1);
8537 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8538 unsigned LSB = countTrailingZeros(Mask);
8542 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8543 DAG.getConstant(~Mask, MVT::i32));
8545 // Do not add new nodes to DAG combiner worklist.
8546 DCI.CombineTo(N, Res, false);
8552 static SDValue PerformXORCombine(SDNode *N,
8553 TargetLowering::DAGCombinerInfo &DCI,
8554 const ARMSubtarget *Subtarget) {
8555 EVT VT = N->getValueType(0);
8556 SelectionDAG &DAG = DCI.DAG;
8558 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8561 if (!Subtarget->isThumb1Only()) {
8562 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8563 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8564 if (Result.getNode())
8571 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8572 /// the bits being cleared by the AND are not demanded by the BFI.
8573 static SDValue PerformBFICombine(SDNode *N,
8574 TargetLowering::DAGCombinerInfo &DCI) {
8575 SDValue N1 = N->getOperand(1);
8576 if (N1.getOpcode() == ISD::AND) {
8577 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8580 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8581 unsigned LSB = countTrailingZeros(~InvMask);
8582 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8583 unsigned Mask = (1 << Width)-1;
8584 unsigned Mask2 = N11C->getZExtValue();
8585 if ((Mask & (~Mask2)) == 0)
8586 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8587 N->getOperand(0), N1.getOperand(0),
8593 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8594 /// ARMISD::VMOVRRD.
8595 static SDValue PerformVMOVRRDCombine(SDNode *N,
8596 TargetLowering::DAGCombinerInfo &DCI,
8597 const ARMSubtarget *Subtarget) {
8598 // vmovrrd(vmovdrr x, y) -> x,y
8599 SDValue InDouble = N->getOperand(0);
8600 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8601 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8603 // vmovrrd(load f64) -> (load i32), (load i32)
8604 SDNode *InNode = InDouble.getNode();
8605 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8606 InNode->getValueType(0) == MVT::f64 &&
8607 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8608 !cast<LoadSDNode>(InNode)->isVolatile()) {
8609 // TODO: Should this be done for non-FrameIndex operands?
8610 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8612 SelectionDAG &DAG = DCI.DAG;
8614 SDValue BasePtr = LD->getBasePtr();
8615 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8616 LD->getPointerInfo(), LD->isVolatile(),
8617 LD->isNonTemporal(), LD->isInvariant(),
8618 LD->getAlignment());
8620 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8621 DAG.getConstant(4, MVT::i32));
8622 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8623 LD->getPointerInfo(), LD->isVolatile(),
8624 LD->isNonTemporal(), LD->isInvariant(),
8625 std::min(4U, LD->getAlignment() / 2));
8627 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8628 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8629 std::swap (NewLD1, NewLD2);
8630 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8637 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8638 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8639 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8640 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8641 SDValue Op0 = N->getOperand(0);
8642 SDValue Op1 = N->getOperand(1);
8643 if (Op0.getOpcode() == ISD::BITCAST)
8644 Op0 = Op0.getOperand(0);
8645 if (Op1.getOpcode() == ISD::BITCAST)
8646 Op1 = Op1.getOperand(0);
8647 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8648 Op0.getNode() == Op1.getNode() &&
8649 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8650 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8651 N->getValueType(0), Op0.getOperand(0));
8655 /// PerformSTORECombine - Target-specific dag combine xforms for
8657 static SDValue PerformSTORECombine(SDNode *N,
8658 TargetLowering::DAGCombinerInfo &DCI) {
8659 StoreSDNode *St = cast<StoreSDNode>(N);
8660 if (St->isVolatile())
8663 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8664 // pack all of the elements in one place. Next, store to memory in fewer
8666 SDValue StVal = St->getValue();
8667 EVT VT = StVal.getValueType();
8668 if (St->isTruncatingStore() && VT.isVector()) {
8669 SelectionDAG &DAG = DCI.DAG;
8670 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8671 EVT StVT = St->getMemoryVT();
8672 unsigned NumElems = VT.getVectorNumElements();
8673 assert(StVT != VT && "Cannot truncate to the same type");
8674 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8675 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8677 // From, To sizes and ElemCount must be pow of two
8678 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8680 // We are going to use the original vector elt for storing.
8681 // Accumulated smaller vector elements must be a multiple of the store size.
8682 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8684 unsigned SizeRatio = FromEltSz / ToEltSz;
8685 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8687 // Create a type on which we perform the shuffle.
8688 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8689 NumElems*SizeRatio);
8690 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8693 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8694 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8695 for (unsigned i = 0; i < NumElems; ++i)
8696 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8698 // Can't shuffle using an illegal type.
8699 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8701 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8702 DAG.getUNDEF(WideVec.getValueType()),
8704 // At this point all of the data is stored at the bottom of the
8705 // register. We now need to save it to mem.
8707 // Find the largest store unit
8708 MVT StoreType = MVT::i8;
8709 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8710 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8711 MVT Tp = (MVT::SimpleValueType)tp;
8712 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8715 // Didn't find a legal store type.
8716 if (!TLI.isTypeLegal(StoreType))
8719 // Bitcast the original vector into a vector of store-size units
8720 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8721 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8722 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8723 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8724 SmallVector<SDValue, 8> Chains;
8725 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8726 TLI.getPointerTy());
8727 SDValue BasePtr = St->getBasePtr();
8729 // Perform one or more big stores into memory.
8730 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8731 for (unsigned I = 0; I < E; I++) {
8732 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8733 StoreType, ShuffWide,
8734 DAG.getIntPtrConstant(I));
8735 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8736 St->getPointerInfo(), St->isVolatile(),
8737 St->isNonTemporal(), St->getAlignment());
8738 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8740 Chains.push_back(Ch);
8742 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8745 if (!ISD::isNormalStore(St))
8748 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8749 // ARM stores of arguments in the same cache line.
8750 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8751 StVal.getNode()->hasOneUse()) {
8752 SelectionDAG &DAG = DCI.DAG;
8753 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8755 SDValue BasePtr = St->getBasePtr();
8756 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8757 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8758 BasePtr, St->getPointerInfo(), St->isVolatile(),
8759 St->isNonTemporal(), St->getAlignment());
8761 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8762 DAG.getConstant(4, MVT::i32));
8763 return DAG.getStore(NewST1.getValue(0), DL,
8764 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8765 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8766 St->isNonTemporal(),
8767 std::min(4U, St->getAlignment() / 2));
8770 if (StVal.getValueType() != MVT::i64 ||
8771 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8774 // Bitcast an i64 store extracted from a vector to f64.
8775 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8776 SelectionDAG &DAG = DCI.DAG;
8778 SDValue IntVec = StVal.getOperand(0);
8779 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8780 IntVec.getValueType().getVectorNumElements());
8781 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8782 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8783 Vec, StVal.getOperand(1));
8785 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8786 // Make the DAGCombiner fold the bitcasts.
8787 DCI.AddToWorklist(Vec.getNode());
8788 DCI.AddToWorklist(ExtElt.getNode());
8789 DCI.AddToWorklist(V.getNode());
8790 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8791 St->getPointerInfo(), St->isVolatile(),
8792 St->isNonTemporal(), St->getAlignment(),
8796 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8797 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8798 /// i64 vector to have f64 elements, since the value can then be loaded
8799 /// directly into a VFP register.
8800 static bool hasNormalLoadOperand(SDNode *N) {
8801 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8802 for (unsigned i = 0; i < NumElts; ++i) {
8803 SDNode *Elt = N->getOperand(i).getNode();
8804 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8810 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8811 /// ISD::BUILD_VECTOR.
8812 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8813 TargetLowering::DAGCombinerInfo &DCI,
8814 const ARMSubtarget *Subtarget) {
8815 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8816 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8817 // into a pair of GPRs, which is fine when the value is used as a scalar,
8818 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8819 SelectionDAG &DAG = DCI.DAG;
8820 if (N->getNumOperands() == 2) {
8821 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8826 // Load i64 elements as f64 values so that type legalization does not split
8827 // them up into i32 values.
8828 EVT VT = N->getValueType(0);
8829 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8832 SmallVector<SDValue, 8> Ops;
8833 unsigned NumElts = VT.getVectorNumElements();
8834 for (unsigned i = 0; i < NumElts; ++i) {
8835 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8837 // Make the DAGCombiner fold the bitcast.
8838 DCI.AddToWorklist(V.getNode());
8840 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8841 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8842 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8845 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8847 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8848 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8849 // At that time, we may have inserted bitcasts from integer to float.
8850 // If these bitcasts have survived DAGCombine, change the lowering of this
8851 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8852 // force to use floating point types.
8854 // Make sure we can change the type of the vector.
8855 // This is possible iff:
8856 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8857 // 1.1. Vector is used only once.
8858 // 1.2. Use is a bit convert to an integer type.
8859 // 2. The size of its operands are 32-bits (64-bits are not legal).
8860 EVT VT = N->getValueType(0);
8861 EVT EltVT = VT.getVectorElementType();
8863 // Check 1.1. and 2.
8864 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8867 // By construction, the input type must be float.
8868 assert(EltVT == MVT::f32 && "Unexpected type!");
8871 SDNode *Use = *N->use_begin();
8872 if (Use->getOpcode() != ISD::BITCAST ||
8873 Use->getValueType(0).isFloatingPoint())
8876 // Check profitability.
8877 // Model is, if more than half of the relevant operands are bitcast from
8878 // i32, turn the build_vector into a sequence of insert_vector_elt.
8879 // Relevant operands are everything that is not statically
8880 // (i.e., at compile time) bitcasted.
8881 unsigned NumOfBitCastedElts = 0;
8882 unsigned NumElts = VT.getVectorNumElements();
8883 unsigned NumOfRelevantElts = NumElts;
8884 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8885 SDValue Elt = N->getOperand(Idx);
8886 if (Elt->getOpcode() == ISD::BITCAST) {
8887 // Assume only bit cast to i32 will go away.
8888 if (Elt->getOperand(0).getValueType() == MVT::i32)
8889 ++NumOfBitCastedElts;
8890 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8891 // Constants are statically casted, thus do not count them as
8892 // relevant operands.
8893 --NumOfRelevantElts;
8896 // Check if more than half of the elements require a non-free bitcast.
8897 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8900 SelectionDAG &DAG = DCI.DAG;
8901 // Create the new vector type.
8902 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8903 // Check if the type is legal.
8904 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8905 if (!TLI.isTypeLegal(VecVT))
8909 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8910 // => BITCAST INSERT_VECTOR_ELT
8911 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8913 SDValue Vec = DAG.getUNDEF(VecVT);
8915 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8916 SDValue V = N->getOperand(Idx);
8917 if (V.getOpcode() == ISD::UNDEF)
8919 if (V.getOpcode() == ISD::BITCAST &&
8920 V->getOperand(0).getValueType() == MVT::i32)
8921 // Fold obvious case.
8922 V = V.getOperand(0);
8924 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8925 // Make the DAGCombiner fold the bitcasts.
8926 DCI.AddToWorklist(V.getNode());
8928 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8929 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8931 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8932 // Make the DAGCombiner fold the bitcasts.
8933 DCI.AddToWorklist(Vec.getNode());
8937 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8938 /// ISD::INSERT_VECTOR_ELT.
8939 static SDValue PerformInsertEltCombine(SDNode *N,
8940 TargetLowering::DAGCombinerInfo &DCI) {
8941 // Bitcast an i64 load inserted into a vector to f64.
8942 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8943 EVT VT = N->getValueType(0);
8944 SDNode *Elt = N->getOperand(1).getNode();
8945 if (VT.getVectorElementType() != MVT::i64 ||
8946 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8949 SelectionDAG &DAG = DCI.DAG;
8951 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8952 VT.getVectorNumElements());
8953 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8954 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8955 // Make the DAGCombiner fold the bitcasts.
8956 DCI.AddToWorklist(Vec.getNode());
8957 DCI.AddToWorklist(V.getNode());
8958 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8959 Vec, V, N->getOperand(2));
8960 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8963 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8964 /// ISD::VECTOR_SHUFFLE.
8965 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8966 // The LLVM shufflevector instruction does not require the shuffle mask
8967 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8968 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8969 // operands do not match the mask length, they are extended by concatenating
8970 // them with undef vectors. That is probably the right thing for other
8971 // targets, but for NEON it is better to concatenate two double-register
8972 // size vector operands into a single quad-register size vector. Do that
8973 // transformation here:
8974 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8975 // shuffle(concat(v1, v2), undef)
8976 SDValue Op0 = N->getOperand(0);
8977 SDValue Op1 = N->getOperand(1);
8978 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8979 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8980 Op0.getNumOperands() != 2 ||
8981 Op1.getNumOperands() != 2)
8983 SDValue Concat0Op1 = Op0.getOperand(1);
8984 SDValue Concat1Op1 = Op1.getOperand(1);
8985 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8986 Concat1Op1.getOpcode() != ISD::UNDEF)
8988 // Skip the transformation if any of the types are illegal.
8989 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8990 EVT VT = N->getValueType(0);
8991 if (!TLI.isTypeLegal(VT) ||
8992 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8993 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8996 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8997 Op0.getOperand(0), Op1.getOperand(0));
8998 // Translate the shuffle mask.
8999 SmallVector<int, 16> NewMask;
9000 unsigned NumElts = VT.getVectorNumElements();
9001 unsigned HalfElts = NumElts/2;
9002 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9003 for (unsigned n = 0; n < NumElts; ++n) {
9004 int MaskElt = SVN->getMaskElt(n);
9006 if (MaskElt < (int)HalfElts)
9008 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9009 NewElt = HalfElts + MaskElt - NumElts;
9010 NewMask.push_back(NewElt);
9012 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9013 DAG.getUNDEF(VT), NewMask.data());
9016 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9017 /// NEON load/store intrinsics to merge base address updates.
9018 static SDValue CombineBaseUpdate(SDNode *N,
9019 TargetLowering::DAGCombinerInfo &DCI) {
9020 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9023 SelectionDAG &DAG = DCI.DAG;
9024 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9025 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9026 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9027 SDValue Addr = N->getOperand(AddrOpIdx);
9029 // Search for a use of the address operand that is an increment.
9030 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9031 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9033 if (User->getOpcode() != ISD::ADD ||
9034 UI.getUse().getResNo() != Addr.getResNo())
9037 // Check that the add is independent of the load/store. Otherwise, folding
9038 // it would create a cycle.
9039 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9042 // Find the new opcode for the updating load/store.
9044 bool isLaneOp = false;
9045 unsigned NewOpc = 0;
9046 unsigned NumVecs = 0;
9048 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9050 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9051 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9053 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9055 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9057 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9059 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9060 NumVecs = 2; isLaneOp = true; break;
9061 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9062 NumVecs = 3; isLaneOp = true; break;
9063 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9064 NumVecs = 4; isLaneOp = true; break;
9065 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9066 NumVecs = 1; isLoad = false; break;
9067 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9068 NumVecs = 2; isLoad = false; break;
9069 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9070 NumVecs = 3; isLoad = false; break;
9071 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9072 NumVecs = 4; isLoad = false; break;
9073 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9074 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9075 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9076 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9077 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9078 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9082 switch (N->getOpcode()) {
9083 default: llvm_unreachable("unexpected opcode for Neon base update");
9084 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9085 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9086 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9090 // Find the size of memory referenced by the load/store.
9093 VecTy = N->getValueType(0);
9095 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9096 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9098 NumBytes /= VecTy.getVectorNumElements();
9100 // If the increment is a constant, it must match the memory ref size.
9101 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9102 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9103 uint64_t IncVal = CInc->getZExtValue();
9104 if (IncVal != NumBytes)
9106 } else if (NumBytes >= 3 * 16) {
9107 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9108 // separate instructions that make it harder to use a non-constant update.
9112 // Create the new updating load/store node.
9114 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9116 for (n = 0; n < NumResultVecs; ++n)
9118 Tys[n++] = MVT::i32;
9119 Tys[n] = MVT::Other;
9120 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
9121 SmallVector<SDValue, 8> Ops;
9122 Ops.push_back(N->getOperand(0)); // incoming chain
9123 Ops.push_back(N->getOperand(AddrOpIdx));
9125 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9126 Ops.push_back(N->getOperand(i));
9128 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9129 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9130 Ops, MemInt->getMemoryVT(),
9131 MemInt->getMemOperand());
9134 std::vector<SDValue> NewResults;
9135 for (unsigned i = 0; i < NumResultVecs; ++i) {
9136 NewResults.push_back(SDValue(UpdN.getNode(), i));
9138 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9139 DCI.CombineTo(N, NewResults);
9140 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9147 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9148 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9149 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9151 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9152 SelectionDAG &DAG = DCI.DAG;
9153 EVT VT = N->getValueType(0);
9154 // vldN-dup instructions only support 64-bit vectors for N > 1.
9155 if (!VT.is64BitVector())
9158 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9159 SDNode *VLD = N->getOperand(0).getNode();
9160 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9162 unsigned NumVecs = 0;
9163 unsigned NewOpc = 0;
9164 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9165 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9167 NewOpc = ARMISD::VLD2DUP;
9168 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9170 NewOpc = ARMISD::VLD3DUP;
9171 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9173 NewOpc = ARMISD::VLD4DUP;
9178 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9179 // numbers match the load.
9180 unsigned VLDLaneNo =
9181 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9182 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9184 // Ignore uses of the chain result.
9185 if (UI.getUse().getResNo() == NumVecs)
9188 if (User->getOpcode() != ARMISD::VDUPLANE ||
9189 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9193 // Create the vldN-dup node.
9196 for (n = 0; n < NumVecs; ++n)
9198 Tys[n] = MVT::Other;
9199 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9200 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9201 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9202 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9203 Ops, VLDMemInt->getMemoryVT(),
9204 VLDMemInt->getMemOperand());
9207 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9209 unsigned ResNo = UI.getUse().getResNo();
9210 // Ignore uses of the chain result.
9211 if (ResNo == NumVecs)
9214 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9217 // Now the vldN-lane intrinsic is dead except for its chain result.
9218 // Update uses of the chain.
9219 std::vector<SDValue> VLDDupResults;
9220 for (unsigned n = 0; n < NumVecs; ++n)
9221 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9222 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9223 DCI.CombineTo(VLD, VLDDupResults);
9228 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9229 /// ARMISD::VDUPLANE.
9230 static SDValue PerformVDUPLANECombine(SDNode *N,
9231 TargetLowering::DAGCombinerInfo &DCI) {
9232 SDValue Op = N->getOperand(0);
9234 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9235 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9236 if (CombineVLDDUP(N, DCI))
9237 return SDValue(N, 0);
9239 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9240 // redundant. Ignore bit_converts for now; element sizes are checked below.
9241 while (Op.getOpcode() == ISD::BITCAST)
9242 Op = Op.getOperand(0);
9243 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9246 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9247 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9248 // The canonical VMOV for a zero vector uses a 32-bit element size.
9249 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9251 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9253 EVT VT = N->getValueType(0);
9254 if (EltSize > VT.getVectorElementType().getSizeInBits())
9257 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9260 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9261 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9262 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9266 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9268 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9273 APFloat APF = C->getValueAPF();
9274 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9275 != APFloat::opOK || !isExact)
9278 c0 = (I == 0) ? cN : c0;
9279 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9286 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9287 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9288 /// when the VMUL has a constant operand that is a power of 2.
9290 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9291 /// vmul.f32 d16, d17, d16
9292 /// vcvt.s32.f32 d16, d16
9294 /// vcvt.s32.f32 d16, d16, #3
9295 static SDValue PerformVCVTCombine(SDNode *N,
9296 TargetLowering::DAGCombinerInfo &DCI,
9297 const ARMSubtarget *Subtarget) {
9298 SelectionDAG &DAG = DCI.DAG;
9299 SDValue Op = N->getOperand(0);
9301 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9302 Op.getOpcode() != ISD::FMUL)
9306 SDValue N0 = Op->getOperand(0);
9307 SDValue ConstVec = Op->getOperand(1);
9308 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9310 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9311 !isConstVecPow2(ConstVec, isSigned, C))
9314 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9315 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9316 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9317 // These instructions only exist converting from f32 to i32. We can handle
9318 // smaller integers by generating an extra truncate, but larger ones would
9323 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9324 Intrinsic::arm_neon_vcvtfp2fxu;
9325 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9326 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9327 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9328 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9329 DAG.getConstant(Log2_64(C), MVT::i32));
9331 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9332 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9337 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9338 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9339 /// when the VDIV has a constant operand that is a power of 2.
9341 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9342 /// vcvt.f32.s32 d16, d16
9343 /// vdiv.f32 d16, d17, d16
9345 /// vcvt.f32.s32 d16, d16, #3
9346 static SDValue PerformVDIVCombine(SDNode *N,
9347 TargetLowering::DAGCombinerInfo &DCI,
9348 const ARMSubtarget *Subtarget) {
9349 SelectionDAG &DAG = DCI.DAG;
9350 SDValue Op = N->getOperand(0);
9351 unsigned OpOpcode = Op.getNode()->getOpcode();
9353 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9354 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9358 SDValue ConstVec = N->getOperand(1);
9359 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9361 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9362 !isConstVecPow2(ConstVec, isSigned, C))
9365 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9366 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9367 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9368 // These instructions only exist converting from i32 to f32. We can handle
9369 // smaller integers by generating an extra extend, but larger ones would
9374 SDValue ConvInput = Op.getOperand(0);
9375 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9376 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9377 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9378 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9381 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9382 Intrinsic::arm_neon_vcvtfxu2fp;
9383 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9385 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9386 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9389 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9390 /// operand of a vector shift operation, where all the elements of the
9391 /// build_vector must have the same constant integer value.
9392 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9393 // Ignore bit_converts.
9394 while (Op.getOpcode() == ISD::BITCAST)
9395 Op = Op.getOperand(0);
9396 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9397 APInt SplatBits, SplatUndef;
9398 unsigned SplatBitSize;
9400 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9401 HasAnyUndefs, ElementBits) ||
9402 SplatBitSize > ElementBits)
9404 Cnt = SplatBits.getSExtValue();
9408 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9409 /// operand of a vector shift left operation. That value must be in the range:
9410 /// 0 <= Value < ElementBits for a left shift; or
9411 /// 0 <= Value <= ElementBits for a long left shift.
9412 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9413 assert(VT.isVector() && "vector shift count is not a vector type");
9414 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9415 if (! getVShiftImm(Op, ElementBits, Cnt))
9417 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9420 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9421 /// operand of a vector shift right operation. For a shift opcode, the value
9422 /// is positive, but for an intrinsic the value count must be negative. The
9423 /// absolute value must be in the range:
9424 /// 1 <= |Value| <= ElementBits for a right shift; or
9425 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9426 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9428 assert(VT.isVector() && "vector shift count is not a vector type");
9429 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9430 if (! getVShiftImm(Op, ElementBits, Cnt))
9434 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9437 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9438 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9439 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9442 // Don't do anything for most intrinsics.
9445 // Vector shifts: check for immediate versions and lower them.
9446 // Note: This is done during DAG combining instead of DAG legalizing because
9447 // the build_vectors for 64-bit vector element shift counts are generally
9448 // not legal, and it is hard to see their values after they get legalized to
9449 // loads from a constant pool.
9450 case Intrinsic::arm_neon_vshifts:
9451 case Intrinsic::arm_neon_vshiftu:
9452 case Intrinsic::arm_neon_vrshifts:
9453 case Intrinsic::arm_neon_vrshiftu:
9454 case Intrinsic::arm_neon_vrshiftn:
9455 case Intrinsic::arm_neon_vqshifts:
9456 case Intrinsic::arm_neon_vqshiftu:
9457 case Intrinsic::arm_neon_vqshiftsu:
9458 case Intrinsic::arm_neon_vqshiftns:
9459 case Intrinsic::arm_neon_vqshiftnu:
9460 case Intrinsic::arm_neon_vqshiftnsu:
9461 case Intrinsic::arm_neon_vqrshiftns:
9462 case Intrinsic::arm_neon_vqrshiftnu:
9463 case Intrinsic::arm_neon_vqrshiftnsu: {
9464 EVT VT = N->getOperand(1).getValueType();
9466 unsigned VShiftOpc = 0;
9469 case Intrinsic::arm_neon_vshifts:
9470 case Intrinsic::arm_neon_vshiftu:
9471 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9472 VShiftOpc = ARMISD::VSHL;
9475 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9476 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9477 ARMISD::VSHRs : ARMISD::VSHRu);
9482 case Intrinsic::arm_neon_vrshifts:
9483 case Intrinsic::arm_neon_vrshiftu:
9484 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9488 case Intrinsic::arm_neon_vqshifts:
9489 case Intrinsic::arm_neon_vqshiftu:
9490 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9494 case Intrinsic::arm_neon_vqshiftsu:
9495 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9497 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9499 case Intrinsic::arm_neon_vrshiftn:
9500 case Intrinsic::arm_neon_vqshiftns:
9501 case Intrinsic::arm_neon_vqshiftnu:
9502 case Intrinsic::arm_neon_vqshiftnsu:
9503 case Intrinsic::arm_neon_vqrshiftns:
9504 case Intrinsic::arm_neon_vqrshiftnu:
9505 case Intrinsic::arm_neon_vqrshiftnsu:
9506 // Narrowing shifts require an immediate right shift.
9507 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9509 llvm_unreachable("invalid shift count for narrowing vector shift "
9513 llvm_unreachable("unhandled vector shift");
9517 case Intrinsic::arm_neon_vshifts:
9518 case Intrinsic::arm_neon_vshiftu:
9519 // Opcode already set above.
9521 case Intrinsic::arm_neon_vrshifts:
9522 VShiftOpc = ARMISD::VRSHRs; break;
9523 case Intrinsic::arm_neon_vrshiftu:
9524 VShiftOpc = ARMISD::VRSHRu; break;
9525 case Intrinsic::arm_neon_vrshiftn:
9526 VShiftOpc = ARMISD::VRSHRN; break;
9527 case Intrinsic::arm_neon_vqshifts:
9528 VShiftOpc = ARMISD::VQSHLs; break;
9529 case Intrinsic::arm_neon_vqshiftu:
9530 VShiftOpc = ARMISD::VQSHLu; break;
9531 case Intrinsic::arm_neon_vqshiftsu:
9532 VShiftOpc = ARMISD::VQSHLsu; break;
9533 case Intrinsic::arm_neon_vqshiftns:
9534 VShiftOpc = ARMISD::VQSHRNs; break;
9535 case Intrinsic::arm_neon_vqshiftnu:
9536 VShiftOpc = ARMISD::VQSHRNu; break;
9537 case Intrinsic::arm_neon_vqshiftnsu:
9538 VShiftOpc = ARMISD::VQSHRNsu; break;
9539 case Intrinsic::arm_neon_vqrshiftns:
9540 VShiftOpc = ARMISD::VQRSHRNs; break;
9541 case Intrinsic::arm_neon_vqrshiftnu:
9542 VShiftOpc = ARMISD::VQRSHRNu; break;
9543 case Intrinsic::arm_neon_vqrshiftnsu:
9544 VShiftOpc = ARMISD::VQRSHRNsu; break;
9547 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9548 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9551 case Intrinsic::arm_neon_vshiftins: {
9552 EVT VT = N->getOperand(1).getValueType();
9554 unsigned VShiftOpc = 0;
9556 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9557 VShiftOpc = ARMISD::VSLI;
9558 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9559 VShiftOpc = ARMISD::VSRI;
9561 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9564 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9565 N->getOperand(1), N->getOperand(2),
9566 DAG.getConstant(Cnt, MVT::i32));
9569 case Intrinsic::arm_neon_vqrshifts:
9570 case Intrinsic::arm_neon_vqrshiftu:
9571 // No immediate versions of these to check for.
9578 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9579 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9580 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9581 /// vector element shift counts are generally not legal, and it is hard to see
9582 /// their values after they get legalized to loads from a constant pool.
9583 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9584 const ARMSubtarget *ST) {
9585 EVT VT = N->getValueType(0);
9586 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9587 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9588 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9589 SDValue N1 = N->getOperand(1);
9590 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9591 SDValue N0 = N->getOperand(0);
9592 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9593 DAG.MaskedValueIsZero(N0.getOperand(0),
9594 APInt::getHighBitsSet(32, 16)))
9595 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9599 // Nothing to be done for scalar shifts.
9600 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9601 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9604 assert(ST->hasNEON() && "unexpected vector shift");
9607 switch (N->getOpcode()) {
9608 default: llvm_unreachable("unexpected shift opcode");
9611 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9612 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9613 DAG.getConstant(Cnt, MVT::i32));
9618 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9619 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9620 ARMISD::VSHRs : ARMISD::VSHRu);
9621 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9622 DAG.getConstant(Cnt, MVT::i32));
9628 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9629 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9630 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9631 const ARMSubtarget *ST) {
9632 SDValue N0 = N->getOperand(0);
9634 // Check for sign- and zero-extensions of vector extract operations of 8-
9635 // and 16-bit vector elements. NEON supports these directly. They are
9636 // handled during DAG combining because type legalization will promote them
9637 // to 32-bit types and it is messy to recognize the operations after that.
9638 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9639 SDValue Vec = N0.getOperand(0);
9640 SDValue Lane = N0.getOperand(1);
9641 EVT VT = N->getValueType(0);
9642 EVT EltVT = N0.getValueType();
9643 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9645 if (VT == MVT::i32 &&
9646 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9647 TLI.isTypeLegal(Vec.getValueType()) &&
9648 isa<ConstantSDNode>(Lane)) {
9651 switch (N->getOpcode()) {
9652 default: llvm_unreachable("unexpected opcode");
9653 case ISD::SIGN_EXTEND:
9654 Opc = ARMISD::VGETLANEs;
9656 case ISD::ZERO_EXTEND:
9657 case ISD::ANY_EXTEND:
9658 Opc = ARMISD::VGETLANEu;
9661 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9668 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9669 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9670 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9671 const ARMSubtarget *ST) {
9672 // If the target supports NEON, try to use vmax/vmin instructions for f32
9673 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9674 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9675 // a NaN; only do the transformation when it matches that behavior.
9677 // For now only do this when using NEON for FP operations; if using VFP, it
9678 // is not obvious that the benefit outweighs the cost of switching to the
9680 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9681 N->getValueType(0) != MVT::f32)
9684 SDValue CondLHS = N->getOperand(0);
9685 SDValue CondRHS = N->getOperand(1);
9686 SDValue LHS = N->getOperand(2);
9687 SDValue RHS = N->getOperand(3);
9688 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9690 unsigned Opcode = 0;
9692 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9693 IsReversed = false; // x CC y ? x : y
9694 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9695 IsReversed = true ; // x CC y ? y : x
9709 // If LHS is NaN, an ordered comparison will be false and the result will
9710 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9711 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9712 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9713 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9715 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9716 // will return -0, so vmin can only be used for unsafe math or if one of
9717 // the operands is known to be nonzero.
9718 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9719 !DAG.getTarget().Options.UnsafeFPMath &&
9720 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9722 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9731 // If LHS is NaN, an ordered comparison will be false and the result will
9732 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9733 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9734 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9735 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9737 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9738 // will return +0, so vmax can only be used for unsafe math or if one of
9739 // the operands is known to be nonzero.
9740 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9741 !DAG.getTarget().Options.UnsafeFPMath &&
9742 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9744 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9750 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9753 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9755 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9756 SDValue Cmp = N->getOperand(4);
9757 if (Cmp.getOpcode() != ARMISD::CMPZ)
9758 // Only looking at EQ and NE cases.
9761 EVT VT = N->getValueType(0);
9763 SDValue LHS = Cmp.getOperand(0);
9764 SDValue RHS = Cmp.getOperand(1);
9765 SDValue FalseVal = N->getOperand(0);
9766 SDValue TrueVal = N->getOperand(1);
9767 SDValue ARMcc = N->getOperand(2);
9768 ARMCC::CondCodes CC =
9769 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9787 /// FIXME: Turn this into a target neutral optimization?
9789 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9790 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9791 N->getOperand(3), Cmp);
9792 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9794 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9795 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9796 N->getOperand(3), NewCmp);
9799 if (Res.getNode()) {
9800 APInt KnownZero, KnownOne;
9801 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9802 // Capture demanded bits information that would be otherwise lost.
9803 if (KnownZero == 0xfffffffe)
9804 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9805 DAG.getValueType(MVT::i1));
9806 else if (KnownZero == 0xffffff00)
9807 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9808 DAG.getValueType(MVT::i8));
9809 else if (KnownZero == 0xffff0000)
9810 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9811 DAG.getValueType(MVT::i16));
9817 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9818 DAGCombinerInfo &DCI) const {
9819 switch (N->getOpcode()) {
9821 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9822 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9823 case ISD::SUB: return PerformSUBCombine(N, DCI);
9824 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9825 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9826 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9827 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9828 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9829 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9830 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9831 case ISD::STORE: return PerformSTORECombine(N, DCI);
9832 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9833 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9834 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9835 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9836 case ISD::FP_TO_SINT:
9837 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9838 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9839 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9842 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9843 case ISD::SIGN_EXTEND:
9844 case ISD::ZERO_EXTEND:
9845 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9846 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9847 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9848 case ARMISD::VLD2DUP:
9849 case ARMISD::VLD3DUP:
9850 case ARMISD::VLD4DUP:
9851 return CombineBaseUpdate(N, DCI);
9852 case ARMISD::BUILD_VECTOR:
9853 return PerformARMBUILD_VECTORCombine(N, DCI);
9854 case ISD::INTRINSIC_VOID:
9855 case ISD::INTRINSIC_W_CHAIN:
9856 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9857 case Intrinsic::arm_neon_vld1:
9858 case Intrinsic::arm_neon_vld2:
9859 case Intrinsic::arm_neon_vld3:
9860 case Intrinsic::arm_neon_vld4:
9861 case Intrinsic::arm_neon_vld2lane:
9862 case Intrinsic::arm_neon_vld3lane:
9863 case Intrinsic::arm_neon_vld4lane:
9864 case Intrinsic::arm_neon_vst1:
9865 case Intrinsic::arm_neon_vst2:
9866 case Intrinsic::arm_neon_vst3:
9867 case Intrinsic::arm_neon_vst4:
9868 case Intrinsic::arm_neon_vst2lane:
9869 case Intrinsic::arm_neon_vst3lane:
9870 case Intrinsic::arm_neon_vst4lane:
9871 return CombineBaseUpdate(N, DCI);
9879 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9881 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9884 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9888 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9889 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9891 switch (VT.getSimpleVT().SimpleTy) {
9897 // Unaligned access can use (for example) LRDB, LRDH, LDR
9898 if (AllowsUnaligned) {
9900 *Fast = Subtarget->hasV7Ops();
9907 // For any little-endian targets with neon, we can support unaligned ld/st
9908 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9909 // A big-endian target may also explicitly support unaligned accesses
9910 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9920 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9921 unsigned AlignCheck) {
9922 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9923 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9926 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9927 unsigned DstAlign, unsigned SrcAlign,
9928 bool IsMemset, bool ZeroMemset,
9930 MachineFunction &MF) const {
9931 const Function *F = MF.getFunction();
9933 // See if we can use NEON instructions for this...
9934 if ((!IsMemset || ZeroMemset) &&
9935 Subtarget->hasNEON() &&
9936 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9937 Attribute::NoImplicitFloat)) {
9940 (memOpAlign(SrcAlign, DstAlign, 16) ||
9941 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9943 } else if (Size >= 8 &&
9944 (memOpAlign(SrcAlign, DstAlign, 8) ||
9945 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9951 // Lowering to i32/i16 if the size permits.
9957 // Let the target-independent logic figure it out.
9961 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9962 if (Val.getOpcode() != ISD::LOAD)
9965 EVT VT1 = Val.getValueType();
9966 if (!VT1.isSimple() || !VT1.isInteger() ||
9967 !VT2.isSimple() || !VT2.isInteger())
9970 switch (VT1.getSimpleVT().SimpleTy) {
9975 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9982 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9983 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9986 if (!isTypeLegal(EVT::getEVT(Ty1)))
9989 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9991 // Assuming the caller doesn't have a zeroext or signext return parameter,
9992 // truncation all the way down to i1 is valid.
9997 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10001 unsigned Scale = 1;
10002 switch (VT.getSimpleVT().SimpleTy) {
10003 default: return false;
10018 if ((V & (Scale - 1)) != 0)
10021 return V == (V & ((1LL << 5) - 1));
10024 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10025 const ARMSubtarget *Subtarget) {
10026 bool isNeg = false;
10032 switch (VT.getSimpleVT().SimpleTy) {
10033 default: return false;
10038 // + imm12 or - imm8
10040 return V == (V & ((1LL << 8) - 1));
10041 return V == (V & ((1LL << 12) - 1));
10044 // Same as ARM mode. FIXME: NEON?
10045 if (!Subtarget->hasVFP2())
10050 return V == (V & ((1LL << 8) - 1));
10054 /// isLegalAddressImmediate - Return true if the integer value can be used
10055 /// as the offset of the target addressing mode for load / store of the
10057 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10058 const ARMSubtarget *Subtarget) {
10062 if (!VT.isSimple())
10065 if (Subtarget->isThumb1Only())
10066 return isLegalT1AddressImmediate(V, VT);
10067 else if (Subtarget->isThumb2())
10068 return isLegalT2AddressImmediate(V, VT, Subtarget);
10073 switch (VT.getSimpleVT().SimpleTy) {
10074 default: return false;
10079 return V == (V & ((1LL << 12) - 1));
10082 return V == (V & ((1LL << 8) - 1));
10085 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10090 return V == (V & ((1LL << 8) - 1));
10094 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10096 int Scale = AM.Scale;
10100 switch (VT.getSimpleVT().SimpleTy) {
10101 default: return false;
10109 Scale = Scale & ~1;
10110 return Scale == 2 || Scale == 4 || Scale == 8;
10113 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10117 // Note, we allow "void" uses (basically, uses that aren't loads or
10118 // stores), because arm allows folding a scale into many arithmetic
10119 // operations. This should be made more precise and revisited later.
10121 // Allow r << imm, but the imm has to be a multiple of two.
10122 if (Scale & 1) return false;
10123 return isPowerOf2_32(Scale);
10127 /// isLegalAddressingMode - Return true if the addressing mode represented
10128 /// by AM is legal for this target, for a load/store of the specified type.
10129 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10131 EVT VT = getValueType(Ty, true);
10132 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10135 // Can never fold addr of global into load/store.
10139 switch (AM.Scale) {
10140 case 0: // no scale reg, must be "r+i" or "r", or "i".
10143 if (Subtarget->isThumb1Only())
10147 // ARM doesn't support any R+R*scale+imm addr modes.
10151 if (!VT.isSimple())
10154 if (Subtarget->isThumb2())
10155 return isLegalT2ScaledAddressingMode(AM, VT);
10157 int Scale = AM.Scale;
10158 switch (VT.getSimpleVT().SimpleTy) {
10159 default: return false;
10163 if (Scale < 0) Scale = -Scale;
10167 return isPowerOf2_32(Scale & ~1);
10171 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10176 // Note, we allow "void" uses (basically, uses that aren't loads or
10177 // stores), because arm allows folding a scale into many arithmetic
10178 // operations. This should be made more precise and revisited later.
10180 // Allow r << imm, but the imm has to be a multiple of two.
10181 if (Scale & 1) return false;
10182 return isPowerOf2_32(Scale);
10188 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10189 /// icmp immediate, that is the target has icmp instructions which can compare
10190 /// a register against the immediate without having to materialize the
10191 /// immediate into a register.
10192 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10193 // Thumb2 and ARM modes can use cmn for negative immediates.
10194 if (!Subtarget->isThumb())
10195 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10196 if (Subtarget->isThumb2())
10197 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10198 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10199 return Imm >= 0 && Imm <= 255;
10202 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10203 /// *or sub* immediate, that is the target has add or sub instructions which can
10204 /// add a register with the immediate without having to materialize the
10205 /// immediate into a register.
10206 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10207 // Same encoding for add/sub, just flip the sign.
10208 int64_t AbsImm = llvm::abs64(Imm);
10209 if (!Subtarget->isThumb())
10210 return ARM_AM::getSOImmVal(AbsImm) != -1;
10211 if (Subtarget->isThumb2())
10212 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10213 // Thumb1 only has 8-bit unsigned immediate.
10214 return AbsImm >= 0 && AbsImm <= 255;
10217 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10218 bool isSEXTLoad, SDValue &Base,
10219 SDValue &Offset, bool &isInc,
10220 SelectionDAG &DAG) {
10221 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10224 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10225 // AddressingMode 3
10226 Base = Ptr->getOperand(0);
10227 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10228 int RHSC = (int)RHS->getZExtValue();
10229 if (RHSC < 0 && RHSC > -256) {
10230 assert(Ptr->getOpcode() == ISD::ADD);
10232 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10236 isInc = (Ptr->getOpcode() == ISD::ADD);
10237 Offset = Ptr->getOperand(1);
10239 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10240 // AddressingMode 2
10241 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10242 int RHSC = (int)RHS->getZExtValue();
10243 if (RHSC < 0 && RHSC > -0x1000) {
10244 assert(Ptr->getOpcode() == ISD::ADD);
10246 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10247 Base = Ptr->getOperand(0);
10252 if (Ptr->getOpcode() == ISD::ADD) {
10254 ARM_AM::ShiftOpc ShOpcVal=
10255 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10256 if (ShOpcVal != ARM_AM::no_shift) {
10257 Base = Ptr->getOperand(1);
10258 Offset = Ptr->getOperand(0);
10260 Base = Ptr->getOperand(0);
10261 Offset = Ptr->getOperand(1);
10266 isInc = (Ptr->getOpcode() == ISD::ADD);
10267 Base = Ptr->getOperand(0);
10268 Offset = Ptr->getOperand(1);
10272 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10276 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10277 bool isSEXTLoad, SDValue &Base,
10278 SDValue &Offset, bool &isInc,
10279 SelectionDAG &DAG) {
10280 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10283 Base = Ptr->getOperand(0);
10284 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10285 int RHSC = (int)RHS->getZExtValue();
10286 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10287 assert(Ptr->getOpcode() == ISD::ADD);
10289 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10291 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10292 isInc = Ptr->getOpcode() == ISD::ADD;
10293 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10301 /// getPreIndexedAddressParts - returns true by value, base pointer and
10302 /// offset pointer and addressing mode by reference if the node's address
10303 /// can be legally represented as pre-indexed load / store address.
10305 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10307 ISD::MemIndexedMode &AM,
10308 SelectionDAG &DAG) const {
10309 if (Subtarget->isThumb1Only())
10314 bool isSEXTLoad = false;
10315 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10316 Ptr = LD->getBasePtr();
10317 VT = LD->getMemoryVT();
10318 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10319 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10320 Ptr = ST->getBasePtr();
10321 VT = ST->getMemoryVT();
10326 bool isLegal = false;
10327 if (Subtarget->isThumb2())
10328 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10329 Offset, isInc, DAG);
10331 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10332 Offset, isInc, DAG);
10336 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10340 /// getPostIndexedAddressParts - returns true by value, base pointer and
10341 /// offset pointer and addressing mode by reference if this node can be
10342 /// combined with a load / store to form a post-indexed load / store.
10343 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10346 ISD::MemIndexedMode &AM,
10347 SelectionDAG &DAG) const {
10348 if (Subtarget->isThumb1Only())
10353 bool isSEXTLoad = false;
10354 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10355 VT = LD->getMemoryVT();
10356 Ptr = LD->getBasePtr();
10357 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10358 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10359 VT = ST->getMemoryVT();
10360 Ptr = ST->getBasePtr();
10365 bool isLegal = false;
10366 if (Subtarget->isThumb2())
10367 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10370 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10376 // Swap base ptr and offset to catch more post-index load / store when
10377 // it's legal. In Thumb2 mode, offset must be an immediate.
10378 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10379 !Subtarget->isThumb2())
10380 std::swap(Base, Offset);
10382 // Post-indexed load / store update the base pointer.
10387 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10391 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10394 const SelectionDAG &DAG,
10395 unsigned Depth) const {
10396 unsigned BitWidth = KnownOne.getBitWidth();
10397 KnownZero = KnownOne = APInt(BitWidth, 0);
10398 switch (Op.getOpcode()) {
10404 // These nodes' second result is a boolean
10405 if (Op.getResNo() == 0)
10407 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10409 case ARMISD::CMOV: {
10410 // Bits are known zero/one if known on the LHS and RHS.
10411 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10412 if (KnownZero == 0 && KnownOne == 0) return;
10414 APInt KnownZeroRHS, KnownOneRHS;
10415 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10416 KnownZero &= KnownZeroRHS;
10417 KnownOne &= KnownOneRHS;
10420 case ISD::INTRINSIC_W_CHAIN: {
10421 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10422 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10425 case Intrinsic::arm_ldaex:
10426 case Intrinsic::arm_ldrex: {
10427 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10428 unsigned MemBits = VT.getScalarType().getSizeInBits();
10429 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10437 //===----------------------------------------------------------------------===//
10438 // ARM Inline Assembly Support
10439 //===----------------------------------------------------------------------===//
10441 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10442 // Looking for "rev" which is V6+.
10443 if (!Subtarget->hasV6Ops())
10446 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10447 std::string AsmStr = IA->getAsmString();
10448 SmallVector<StringRef, 4> AsmPieces;
10449 SplitString(AsmStr, AsmPieces, ";\n");
10451 switch (AsmPieces.size()) {
10452 default: return false;
10454 AsmStr = AsmPieces[0];
10456 SplitString(AsmStr, AsmPieces, " \t,");
10459 if (AsmPieces.size() == 3 &&
10460 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10461 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10462 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10463 if (Ty && Ty->getBitWidth() == 32)
10464 return IntrinsicLowering::LowerToByteSwap(CI);
10472 /// getConstraintType - Given a constraint letter, return the type of
10473 /// constraint it is for this target.
10474 ARMTargetLowering::ConstraintType
10475 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10476 if (Constraint.size() == 1) {
10477 switch (Constraint[0]) {
10479 case 'l': return C_RegisterClass;
10480 case 'w': return C_RegisterClass;
10481 case 'h': return C_RegisterClass;
10482 case 'x': return C_RegisterClass;
10483 case 't': return C_RegisterClass;
10484 case 'j': return C_Other; // Constant for movw.
10485 // An address with a single base register. Due to the way we
10486 // currently handle addresses it is the same as an 'r' memory constraint.
10487 case 'Q': return C_Memory;
10489 } else if (Constraint.size() == 2) {
10490 switch (Constraint[0]) {
10492 // All 'U+' constraints are addresses.
10493 case 'U': return C_Memory;
10496 return TargetLowering::getConstraintType(Constraint);
10499 /// Examine constraint type and operand type and determine a weight value.
10500 /// This object must already have been set up with the operand type
10501 /// and the current alternative constraint selected.
10502 TargetLowering::ConstraintWeight
10503 ARMTargetLowering::getSingleConstraintMatchWeight(
10504 AsmOperandInfo &info, const char *constraint) const {
10505 ConstraintWeight weight = CW_Invalid;
10506 Value *CallOperandVal = info.CallOperandVal;
10507 // If we don't have a value, we can't do a match,
10508 // but allow it at the lowest weight.
10509 if (!CallOperandVal)
10511 Type *type = CallOperandVal->getType();
10512 // Look at the constraint type.
10513 switch (*constraint) {
10515 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10518 if (type->isIntegerTy()) {
10519 if (Subtarget->isThumb())
10520 weight = CW_SpecificReg;
10522 weight = CW_Register;
10526 if (type->isFloatingPointTy())
10527 weight = CW_Register;
10533 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10535 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10537 if (Constraint.size() == 1) {
10538 // GCC ARM Constraint Letters
10539 switch (Constraint[0]) {
10540 case 'l': // Low regs or general regs.
10541 if (Subtarget->isThumb())
10542 return RCPair(0U, &ARM::tGPRRegClass);
10543 return RCPair(0U, &ARM::GPRRegClass);
10544 case 'h': // High regs or no regs.
10545 if (Subtarget->isThumb())
10546 return RCPair(0U, &ARM::hGPRRegClass);
10549 return RCPair(0U, &ARM::GPRRegClass);
10551 if (VT == MVT::Other)
10553 if (VT == MVT::f32)
10554 return RCPair(0U, &ARM::SPRRegClass);
10555 if (VT.getSizeInBits() == 64)
10556 return RCPair(0U, &ARM::DPRRegClass);
10557 if (VT.getSizeInBits() == 128)
10558 return RCPair(0U, &ARM::QPRRegClass);
10561 if (VT == MVT::Other)
10563 if (VT == MVT::f32)
10564 return RCPair(0U, &ARM::SPR_8RegClass);
10565 if (VT.getSizeInBits() == 64)
10566 return RCPair(0U, &ARM::DPR_8RegClass);
10567 if (VT.getSizeInBits() == 128)
10568 return RCPair(0U, &ARM::QPR_8RegClass);
10571 if (VT == MVT::f32)
10572 return RCPair(0U, &ARM::SPRRegClass);
10576 if (StringRef("{cc}").equals_lower(Constraint))
10577 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10579 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10582 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10583 /// vector. If it is invalid, don't add anything to Ops.
10584 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10585 std::string &Constraint,
10586 std::vector<SDValue>&Ops,
10587 SelectionDAG &DAG) const {
10590 // Currently only support length 1 constraints.
10591 if (Constraint.length() != 1) return;
10593 char ConstraintLetter = Constraint[0];
10594 switch (ConstraintLetter) {
10597 case 'I': case 'J': case 'K': case 'L':
10598 case 'M': case 'N': case 'O':
10599 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10603 int64_t CVal64 = C->getSExtValue();
10604 int CVal = (int) CVal64;
10605 // None of these constraints allow values larger than 32 bits. Check
10606 // that the value fits in an int.
10607 if (CVal != CVal64)
10610 switch (ConstraintLetter) {
10612 // Constant suitable for movw, must be between 0 and
10614 if (Subtarget->hasV6T2Ops())
10615 if (CVal >= 0 && CVal <= 65535)
10619 if (Subtarget->isThumb1Only()) {
10620 // This must be a constant between 0 and 255, for ADD
10622 if (CVal >= 0 && CVal <= 255)
10624 } else if (Subtarget->isThumb2()) {
10625 // A constant that can be used as an immediate value in a
10626 // data-processing instruction.
10627 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10630 // A constant that can be used as an immediate value in a
10631 // data-processing instruction.
10632 if (ARM_AM::getSOImmVal(CVal) != -1)
10638 if (Subtarget->isThumb()) { // FIXME thumb2
10639 // This must be a constant between -255 and -1, for negated ADD
10640 // immediates. This can be used in GCC with an "n" modifier that
10641 // prints the negated value, for use with SUB instructions. It is
10642 // not useful otherwise but is implemented for compatibility.
10643 if (CVal >= -255 && CVal <= -1)
10646 // This must be a constant between -4095 and 4095. It is not clear
10647 // what this constraint is intended for. Implemented for
10648 // compatibility with GCC.
10649 if (CVal >= -4095 && CVal <= 4095)
10655 if (Subtarget->isThumb1Only()) {
10656 // A 32-bit value where only one byte has a nonzero value. Exclude
10657 // zero to match GCC. This constraint is used by GCC internally for
10658 // constants that can be loaded with a move/shift combination.
10659 // It is not useful otherwise but is implemented for compatibility.
10660 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10662 } else if (Subtarget->isThumb2()) {
10663 // A constant whose bitwise inverse can be used as an immediate
10664 // value in a data-processing instruction. This can be used in GCC
10665 // with a "B" modifier that prints the inverted value, for use with
10666 // BIC and MVN instructions. It is not useful otherwise but is
10667 // implemented for compatibility.
10668 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10671 // A constant whose bitwise inverse can be used as an immediate
10672 // value in a data-processing instruction. This can be used in GCC
10673 // with a "B" modifier that prints the inverted value, for use with
10674 // BIC and MVN instructions. It is not useful otherwise but is
10675 // implemented for compatibility.
10676 if (ARM_AM::getSOImmVal(~CVal) != -1)
10682 if (Subtarget->isThumb1Only()) {
10683 // This must be a constant between -7 and 7,
10684 // for 3-operand ADD/SUB immediate instructions.
10685 if (CVal >= -7 && CVal < 7)
10687 } else if (Subtarget->isThumb2()) {
10688 // A constant whose negation can be used as an immediate value in a
10689 // data-processing instruction. This can be used in GCC with an "n"
10690 // modifier that prints the negated value, for use with SUB
10691 // instructions. It is not useful otherwise but is implemented for
10693 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10696 // A constant whose negation can be used as an immediate value in a
10697 // data-processing instruction. This can be used in GCC with an "n"
10698 // modifier that prints the negated value, for use with SUB
10699 // instructions. It is not useful otherwise but is implemented for
10701 if (ARM_AM::getSOImmVal(-CVal) != -1)
10707 if (Subtarget->isThumb()) { // FIXME thumb2
10708 // This must be a multiple of 4 between 0 and 1020, for
10709 // ADD sp + immediate.
10710 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10713 // A power of two or a constant between 0 and 32. This is used in
10714 // GCC for the shift amount on shifted register operands, but it is
10715 // useful in general for any shift amounts.
10716 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10722 if (Subtarget->isThumb()) { // FIXME thumb2
10723 // This must be a constant between 0 and 31, for shift amounts.
10724 if (CVal >= 0 && CVal <= 31)
10730 if (Subtarget->isThumb()) { // FIXME thumb2
10731 // This must be a multiple of 4 between -508 and 508, for
10732 // ADD/SUB sp = sp + immediate.
10733 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10738 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10742 if (Result.getNode()) {
10743 Ops.push_back(Result);
10746 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10749 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10750 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10751 unsigned Opcode = Op->getOpcode();
10752 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10753 "Invalid opcode for Div/Rem lowering");
10754 bool isSigned = (Opcode == ISD::SDIVREM);
10755 EVT VT = Op->getValueType(0);
10756 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10759 switch (VT.getSimpleVT().SimpleTy) {
10760 default: llvm_unreachable("Unexpected request for libcall!");
10761 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10762 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10763 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10764 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10767 SDValue InChain = DAG.getEntryNode();
10769 TargetLowering::ArgListTy Args;
10770 TargetLowering::ArgListEntry Entry;
10771 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10772 EVT ArgVT = Op->getOperand(i).getValueType();
10773 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10774 Entry.Node = Op->getOperand(i);
10776 Entry.isSExt = isSigned;
10777 Entry.isZExt = !isSigned;
10778 Args.push_back(Entry);
10781 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10784 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10787 TargetLowering::CallLoweringInfo CLI(DAG);
10788 CLI.setDebugLoc(dl).setChain(InChain)
10789 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10790 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10792 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10793 return CallInfo.first;
10797 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10798 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10802 SDValue Chain = Op.getOperand(0);
10803 SDValue Size = Op.getOperand(1);
10805 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10806 DAG.getConstant(2, MVT::i32));
10809 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10810 Flag = Chain.getValue(1);
10812 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10813 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10815 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10816 Chain = NewSP.getValue(1);
10818 SDValue Ops[2] = { NewSP, Chain };
10819 return DAG.getMergeValues(Ops, DL);
10822 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10823 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10824 "Unexpected type for custom-lowering FP_EXTEND");
10827 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10829 SDValue SrcVal = Op.getOperand(0);
10830 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10831 /*isSigned*/ false, SDLoc(Op)).first;
10834 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10835 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10836 Subtarget->isFPOnlySP() &&
10837 "Unexpected type for custom-lowering FP_ROUND");
10840 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10842 SDValue SrcVal = Op.getOperand(0);
10843 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10844 /*isSigned*/ false, SDLoc(Op)).first;
10848 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10849 // The ARM target isn't yet aware of offsets.
10853 bool ARM::isBitFieldInvertedMask(unsigned v) {
10854 if (v == 0xffffffff)
10857 // there can be 1's on either or both "outsides", all the "inside"
10858 // bits must be 0's
10859 unsigned TO = CountTrailingOnes_32(v);
10860 unsigned LO = CountLeadingOnes_32(v);
10861 v = (v >> TO) << TO;
10862 v = (v << LO) >> LO;
10866 /// isFPImmLegal - Returns true if the target can instruction select the
10867 /// specified FP immediate natively. If false, the legalizer will
10868 /// materialize the FP immediate as a load from a constant pool.
10869 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10870 if (!Subtarget->hasVFP3())
10872 if (VT == MVT::f32)
10873 return ARM_AM::getFP32Imm(Imm) != -1;
10874 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10875 return ARM_AM::getFP64Imm(Imm) != -1;
10879 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10880 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10881 /// specified in the intrinsic calls.
10882 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10884 unsigned Intrinsic) const {
10885 switch (Intrinsic) {
10886 case Intrinsic::arm_neon_vld1:
10887 case Intrinsic::arm_neon_vld2:
10888 case Intrinsic::arm_neon_vld3:
10889 case Intrinsic::arm_neon_vld4:
10890 case Intrinsic::arm_neon_vld2lane:
10891 case Intrinsic::arm_neon_vld3lane:
10892 case Intrinsic::arm_neon_vld4lane: {
10893 Info.opc = ISD::INTRINSIC_W_CHAIN;
10894 // Conservatively set memVT to the entire set of vectors loaded.
10895 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10896 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10897 Info.ptrVal = I.getArgOperand(0);
10899 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10900 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10901 Info.vol = false; // volatile loads with NEON intrinsics not supported
10902 Info.readMem = true;
10903 Info.writeMem = false;
10906 case Intrinsic::arm_neon_vst1:
10907 case Intrinsic::arm_neon_vst2:
10908 case Intrinsic::arm_neon_vst3:
10909 case Intrinsic::arm_neon_vst4:
10910 case Intrinsic::arm_neon_vst2lane:
10911 case Intrinsic::arm_neon_vst3lane:
10912 case Intrinsic::arm_neon_vst4lane: {
10913 Info.opc = ISD::INTRINSIC_VOID;
10914 // Conservatively set memVT to the entire set of vectors stored.
10915 unsigned NumElts = 0;
10916 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10917 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10918 if (!ArgTy->isVectorTy())
10920 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10922 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10923 Info.ptrVal = I.getArgOperand(0);
10925 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10926 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10927 Info.vol = false; // volatile stores with NEON intrinsics not supported
10928 Info.readMem = false;
10929 Info.writeMem = true;
10932 case Intrinsic::arm_ldaex:
10933 case Intrinsic::arm_ldrex: {
10934 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10935 Info.opc = ISD::INTRINSIC_W_CHAIN;
10936 Info.memVT = MVT::getVT(PtrTy->getElementType());
10937 Info.ptrVal = I.getArgOperand(0);
10939 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10941 Info.readMem = true;
10942 Info.writeMem = false;
10945 case Intrinsic::arm_stlex:
10946 case Intrinsic::arm_strex: {
10947 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10948 Info.opc = ISD::INTRINSIC_W_CHAIN;
10949 Info.memVT = MVT::getVT(PtrTy->getElementType());
10950 Info.ptrVal = I.getArgOperand(1);
10952 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10954 Info.readMem = false;
10955 Info.writeMem = true;
10958 case Intrinsic::arm_stlexd:
10959 case Intrinsic::arm_strexd: {
10960 Info.opc = ISD::INTRINSIC_W_CHAIN;
10961 Info.memVT = MVT::i64;
10962 Info.ptrVal = I.getArgOperand(2);
10966 Info.readMem = false;
10967 Info.writeMem = true;
10970 case Intrinsic::arm_ldaexd:
10971 case Intrinsic::arm_ldrexd: {
10972 Info.opc = ISD::INTRINSIC_W_CHAIN;
10973 Info.memVT = MVT::i64;
10974 Info.ptrVal = I.getArgOperand(0);
10978 Info.readMem = true;
10979 Info.writeMem = false;
10989 /// \brief Returns true if it is beneficial to convert a load of a constant
10990 /// to just the constant itself.
10991 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10993 assert(Ty->isIntegerTy());
10995 unsigned Bits = Ty->getPrimitiveSizeInBits();
10996 if (Bits == 0 || Bits > 32)
11001 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
11002 // Loads and stores less than 64-bits are already atomic; ones above that
11003 // are doomed anyway, so defer to the default libcall and blame the OS when
11004 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11005 // anything for those.
11006 bool IsMClass = Subtarget->isMClass();
11007 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
11008 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11009 return Size == 64 && !IsMClass;
11010 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
11011 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
11014 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11015 // and up to 64 bits on the non-M profiles
11016 unsigned AtomicLimit = IsMClass ? 32 : 64;
11017 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
11020 // This has so far only been implemented for MachO.
11021 bool ARMTargetLowering::useLoadStackGuardNode() const {
11022 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11025 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11026 AtomicOrdering Ord) const {
11027 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11028 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11029 bool IsAcquire = isAtLeastAcquire(Ord);
11031 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11032 // intrinsic must return {i32, i32} and we have to recombine them into a
11033 // single i64 here.
11034 if (ValTy->getPrimitiveSizeInBits() == 64) {
11035 Intrinsic::ID Int =
11036 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11037 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11039 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11040 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11042 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11043 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11044 if (!Subtarget->isLittle())
11045 std::swap (Lo, Hi);
11046 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11047 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11048 return Builder.CreateOr(
11049 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11052 Type *Tys[] = { Addr->getType() };
11053 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11054 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11056 return Builder.CreateTruncOrBitCast(
11057 Builder.CreateCall(Ldrex, Addr),
11058 cast<PointerType>(Addr->getType())->getElementType());
11061 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11063 AtomicOrdering Ord) const {
11064 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11065 bool IsRelease = isAtLeastRelease(Ord);
11067 // Since the intrinsics must have legal type, the i64 intrinsics take two
11068 // parameters: "i32, i32". We must marshal Val into the appropriate form
11069 // before the call.
11070 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11071 Intrinsic::ID Int =
11072 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11073 Function *Strex = Intrinsic::getDeclaration(M, Int);
11074 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11076 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11077 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11078 if (!Subtarget->isLittle())
11079 std::swap (Lo, Hi);
11080 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11081 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11084 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11085 Type *Tys[] = { Addr->getType() };
11086 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11088 return Builder.CreateCall2(
11089 Strex, Builder.CreateZExtOrBitCast(
11090 Val, Strex->getFunctionType()->getParamType(0)),
11102 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11103 uint64_t &Members) {
11104 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11105 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11106 uint64_t SubMembers = 0;
11107 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11109 Members += SubMembers;
11111 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11112 uint64_t SubMembers = 0;
11113 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11115 Members += SubMembers * AT->getNumElements();
11116 } else if (Ty->isFloatTy()) {
11117 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11121 } else if (Ty->isDoubleTy()) {
11122 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11126 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11133 return VT->getBitWidth() == 64;
11135 return VT->getBitWidth() == 128;
11137 switch (VT->getBitWidth()) {
11150 return (Members > 0 && Members <= 4);
11153 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11154 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11155 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11156 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11157 CallingConv::ARM_AAPCS_VFP)
11160 HABaseType Base = HA_UNKNOWN;
11161 uint64_t Members = 0;
11162 bool result = isHomogeneousAggregate(Ty, Base, Members);
11163 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());