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 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283 // Single-precision floating-point arithmetic helper functions
284 // RTABI chapter 4.1.2, Table 4
285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 // Single-precision floating-point comparison helper functions
291 // RTABI chapter 4.1.2, Table 5
292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301 // Floating-point to integer conversions.
302 // RTABI chapter 4.1.2, Table 6
303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Conversions between floating types.
313 // RTABI chapter 4.1.2, Table 7
314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 // Integer to floating-point conversions.
319 // RTABI chapter 4.1.2, Table 8
320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Long long helper functions
330 // RTABI chapter 4.2, Table 9
331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 // Integer division functions
337 // RTABI chapter 4.3.1
338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 // RTABI chapter 4.3.4
349 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 for (const auto &LC : LibraryCalls) {
355 setLibcallName(LC.Op, LC.Name);
356 setLibcallCallingConv(LC.Op, LC.CC);
357 if (LC.Cond != ISD::SETCC_INVALID)
358 setCmpLibcallCC(LC.Op, LC.Cond);
362 if (Subtarget->isTargetWindows()) {
363 static const struct {
364 const RTLIB::Libcall Op;
365 const char * const Name;
366 const CallingConv::ID CC;
368 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378 for (const auto &LC : LibraryCalls) {
379 setLibcallName(LC.Op, LC.Name);
380 setLibcallCallingConv(LC.Op, LC.CC);
384 // Use divmod compiler-rt calls for iOS 5.0 and later.
385 if (Subtarget->getTargetTriple().isiOS() &&
386 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
391 // The half <-> float conversion functions are always soft-float, but are
392 // needed for some targets which use a hard-float calling convention by
394 if (Subtarget->isAAPCS_ABI()) {
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
404 if (Subtarget->isThumb1Only())
405 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
409 !Subtarget->isThumb1Only()) {
410 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
414 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
415 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
416 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
417 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
418 setTruncStoreAction((MVT::SimpleValueType)VT,
419 (MVT::SimpleValueType)InnerVT, Expand);
420 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
421 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
424 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
425 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
426 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
427 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
429 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
432 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
433 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435 if (Subtarget->hasNEON()) {
436 addDRTypeForNEON(MVT::v2f32);
437 addDRTypeForNEON(MVT::v8i8);
438 addDRTypeForNEON(MVT::v4i16);
439 addDRTypeForNEON(MVT::v2i32);
440 addDRTypeForNEON(MVT::v1i64);
442 addQRTypeForNEON(MVT::v4f32);
443 addQRTypeForNEON(MVT::v2f64);
444 addQRTypeForNEON(MVT::v16i8);
445 addQRTypeForNEON(MVT::v8i16);
446 addQRTypeForNEON(MVT::v4i32);
447 addQRTypeForNEON(MVT::v2i64);
449 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
450 // neither Neon nor VFP support any arithmetic operations on it.
451 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
452 // supported for v4f32.
453 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
454 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
455 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
456 // FIXME: Code duplication: FDIV and FREM are expanded always, see
457 // ARMTargetLowering::addTypeForNEON method for details.
458 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
459 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
460 // FIXME: Create unittest.
461 // In another words, find a way when "copysign" appears in DAG with vector
463 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
464 // FIXME: Code duplication: SETCC has custom operation action, see
465 // ARMTargetLowering::addTypeForNEON method for details.
466 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
467 // FIXME: Create unittest for FNEG and for FABS.
468 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
469 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
470 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
471 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
472 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
473 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
474 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
475 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
476 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
477 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
478 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
479 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
480 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
481 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
482 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
483 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
484 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
485 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
486 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
489 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
490 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
491 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
492 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
493 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
494 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
495 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
496 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
497 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
498 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
499 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
500 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
501 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
502 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504 // Mark v2f32 intrinsics.
505 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
506 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
507 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
508 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
509 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
510 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
511 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
512 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
513 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
514 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
515 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
516 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
517 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
518 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
519 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521 // Neon does not support some operations on v1i64 and v2i64 types.
522 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
523 // Custom handling for some quad-vector types to detect VMULL.
524 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
525 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
526 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
527 // Custom handling for some vector types to avoid expensive expansions
528 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
529 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
530 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
531 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
532 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
533 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
534 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
535 // a destination type that is wider than the source, and nor does
536 // it have a FP_TO_[SU]INT instruction with a narrower destination than
538 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
539 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
544 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
546 // NEON does not have single instruction CTPOP for vectors with element
547 // types wider than 8-bits. However, custom lowering can leverage the
548 // v8i8/v16i8 vcnt instruction.
549 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
550 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
551 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
552 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
554 // NEON only has FMA instructions as of VFP4.
555 if (!Subtarget->hasVFP4()) {
556 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
557 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
560 setTargetDAGCombine(ISD::INTRINSIC_VOID);
561 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
562 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
563 setTargetDAGCombine(ISD::SHL);
564 setTargetDAGCombine(ISD::SRL);
565 setTargetDAGCombine(ISD::SRA);
566 setTargetDAGCombine(ISD::SIGN_EXTEND);
567 setTargetDAGCombine(ISD::ZERO_EXTEND);
568 setTargetDAGCombine(ISD::ANY_EXTEND);
569 setTargetDAGCombine(ISD::SELECT_CC);
570 setTargetDAGCombine(ISD::BUILD_VECTOR);
571 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
572 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
573 setTargetDAGCombine(ISD::STORE);
574 setTargetDAGCombine(ISD::FP_TO_SINT);
575 setTargetDAGCombine(ISD::FP_TO_UINT);
576 setTargetDAGCombine(ISD::FDIV);
578 // It is legal to extload from v4i8 to v4i16 or v4i32.
579 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
580 MVT::v4i16, MVT::v2i16,
582 for (unsigned i = 0; i < 6; ++i) {
583 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
584 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
585 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
589 // ARM and Thumb2 support UMLAL/SMLAL.
590 if (!Subtarget->isThumb1Only())
591 setTargetDAGCombine(ISD::ADDC);
593 if (Subtarget->isFPOnlySP()) {
594 // When targetting a floating-point unit with only single-precision
595 // operations, f64 is legal for the few double-precision instructions which
596 // are present However, no double-precision operations other than moves,
597 // loads and stores are provided by the hardware.
598 setOperationAction(ISD::FADD, MVT::f64, Expand);
599 setOperationAction(ISD::FSUB, MVT::f64, Expand);
600 setOperationAction(ISD::FMUL, MVT::f64, Expand);
601 setOperationAction(ISD::FMA, MVT::f64, Expand);
602 setOperationAction(ISD::FDIV, MVT::f64, Expand);
603 setOperationAction(ISD::FREM, MVT::f64, Expand);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
605 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
606 setOperationAction(ISD::FNEG, MVT::f64, Expand);
607 setOperationAction(ISD::FABS, MVT::f64, Expand);
608 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
609 setOperationAction(ISD::FSIN, MVT::f64, Expand);
610 setOperationAction(ISD::FCOS, MVT::f64, Expand);
611 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
612 setOperationAction(ISD::FPOW, MVT::f64, Expand);
613 setOperationAction(ISD::FLOG, MVT::f64, Expand);
614 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
615 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
616 setOperationAction(ISD::FEXP, MVT::f64, Expand);
617 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
618 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
619 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
620 setOperationAction(ISD::FRINT, MVT::f64, Expand);
621 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
622 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
623 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
624 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
627 computeRegisterProperties();
629 // ARM does not have floating-point extending loads.
630 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
631 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
633 // ... or truncating stores
634 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
635 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
636 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638 // ARM does not have i1 sign extending load.
639 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
641 // ARM supports all 4 flavors of integer indexed load / store.
642 if (!Subtarget->isThumb1Only()) {
643 for (unsigned im = (unsigned)ISD::PRE_INC;
644 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
645 setIndexedLoadAction(im, MVT::i1, Legal);
646 setIndexedLoadAction(im, MVT::i8, Legal);
647 setIndexedLoadAction(im, MVT::i16, Legal);
648 setIndexedLoadAction(im, MVT::i32, Legal);
649 setIndexedStoreAction(im, MVT::i1, Legal);
650 setIndexedStoreAction(im, MVT::i8, Legal);
651 setIndexedStoreAction(im, MVT::i16, Legal);
652 setIndexedStoreAction(im, MVT::i32, Legal);
656 setOperationAction(ISD::SADDO, MVT::i32, Custom);
657 setOperationAction(ISD::UADDO, MVT::i32, Custom);
658 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
659 setOperationAction(ISD::USUBO, MVT::i32, Custom);
661 // i64 operation support.
662 setOperationAction(ISD::MUL, MVT::i64, Expand);
663 setOperationAction(ISD::MULHU, MVT::i32, Expand);
664 if (Subtarget->isThumb1Only()) {
665 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
666 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
668 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
669 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
670 setOperationAction(ISD::MULHS, MVT::i32, Expand);
672 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
673 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
674 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
675 setOperationAction(ISD::SRL, MVT::i64, Custom);
676 setOperationAction(ISD::SRA, MVT::i64, Custom);
678 if (!Subtarget->isThumb1Only()) {
679 // FIXME: We should do this for Thumb1 as well.
680 setOperationAction(ISD::ADDC, MVT::i32, Custom);
681 setOperationAction(ISD::ADDE, MVT::i32, Custom);
682 setOperationAction(ISD::SUBC, MVT::i32, Custom);
683 setOperationAction(ISD::SUBE, MVT::i32, Custom);
686 // ARM does not have ROTL.
687 setOperationAction(ISD::ROTL, MVT::i32, Expand);
688 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
689 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
690 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
691 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
693 // These just redirect to CTTZ and CTLZ on ARM.
694 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
695 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
697 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
699 // Only ARMv6 has BSWAP.
700 if (!Subtarget->hasV6Ops())
701 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
703 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
704 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
705 // These are expanded into libcalls if the cpu doesn't have HW divider.
706 setOperationAction(ISD::SDIV, MVT::i32, Expand);
707 setOperationAction(ISD::UDIV, MVT::i32, Expand);
710 // FIXME: Also set divmod for SREM on EABI
711 setOperationAction(ISD::SREM, MVT::i32, Expand);
712 setOperationAction(ISD::UREM, MVT::i32, Expand);
713 // Register based DivRem for AEABI (RTABI 4.2)
714 if (Subtarget->isTargetAEABI()) {
715 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
716 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
717 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
718 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
719 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
720 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
721 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
722 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
724 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
725 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
730 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
731 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
733 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
734 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
736 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
737 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
740 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
741 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
742 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
743 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
744 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
746 setOperationAction(ISD::TRAP, MVT::Other, Legal);
748 // Use the default implementation.
749 setOperationAction(ISD::VASTART, MVT::Other, Custom);
750 setOperationAction(ISD::VAARG, MVT::Other, Expand);
751 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
752 setOperationAction(ISD::VAEND, MVT::Other, Expand);
753 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
754 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
756 if (!Subtarget->isTargetMachO()) {
757 // Non-MachO platforms may return values in these registers via the
758 // personality function.
759 setExceptionPointerRegister(ARM::R0);
760 setExceptionSelectorRegister(ARM::R1);
763 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
764 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
766 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
768 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
769 // the default expansion. If we are targeting a single threaded system,
770 // then set them all for expand so we can lower them later into their
772 if (TM.Options.ThreadModel == ThreadModel::Single)
773 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
774 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
775 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
776 // to ldrex/strex loops already.
777 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
779 // On v8, we have particularly efficient implementations of atomic fences
780 // if they can be combined with nearby atomic loads and stores.
781 if (!Subtarget->hasV8Ops()) {
782 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
783 setInsertFencesForAtomic(true);
786 // If there's anything we can use as a barrier, go through custom lowering
788 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
789 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791 // Set them all for expansion, which will force libcalls.
792 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
804 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
805 // Unordered/Monotonic case.
806 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
807 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
810 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
812 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
813 if (!Subtarget->hasV6Ops()) {
814 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
817 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
820 !Subtarget->isThumb1Only()) {
821 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
822 // iff target supports vfp2.
823 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
824 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
827 // We want to custom lower some of our intrinsics.
828 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
829 if (Subtarget->isTargetDarwin()) {
830 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
831 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
832 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
835 setOperationAction(ISD::SETCC, MVT::i32, Expand);
836 setOperationAction(ISD::SETCC, MVT::f32, Expand);
837 setOperationAction(ISD::SETCC, MVT::f64, Expand);
838 setOperationAction(ISD::SELECT, MVT::i32, Custom);
839 setOperationAction(ISD::SELECT, MVT::f32, Custom);
840 setOperationAction(ISD::SELECT, MVT::f64, Custom);
841 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
842 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
843 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
846 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
847 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
848 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
849 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
851 // We don't support sin/cos/fmod/copysign/pow
852 setOperationAction(ISD::FSIN, MVT::f64, Expand);
853 setOperationAction(ISD::FSIN, MVT::f32, Expand);
854 setOperationAction(ISD::FCOS, MVT::f32, Expand);
855 setOperationAction(ISD::FCOS, MVT::f64, Expand);
856 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
857 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
858 setOperationAction(ISD::FREM, MVT::f64, Expand);
859 setOperationAction(ISD::FREM, MVT::f32, Expand);
860 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
861 !Subtarget->isThumb1Only()) {
862 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
863 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865 setOperationAction(ISD::FPOW, MVT::f64, Expand);
866 setOperationAction(ISD::FPOW, MVT::f32, Expand);
868 if (!Subtarget->hasVFP4()) {
869 setOperationAction(ISD::FMA, MVT::f64, Expand);
870 setOperationAction(ISD::FMA, MVT::f32, Expand);
873 // Various VFP goodness
874 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
875 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
876 if (Subtarget->hasVFP2()) {
877 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
878 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
879 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
880 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
883 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
884 if (!Subtarget->hasV8Ops()) {
885 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
886 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
889 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
890 if (!Subtarget->hasFP16()) {
891 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
892 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
896 // Combine sin / cos into one node or libcall if possible.
897 if (Subtarget->hasSinCos()) {
898 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
899 setLibcallName(RTLIB::SINCOS_F64, "sincos");
900 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
901 // For iOS, we don't want to the normal expansion of a libcall to
902 // sincos. We want to issue a libcall to __sincos_stret.
903 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
904 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
908 // ARMv8 implements a lot of rounding-like FP operations.
909 if (Subtarget->hasV8Ops()) {
910 static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
911 for (const auto Ty : RoundingTypes) {
912 setOperationAction(ISD::FFLOOR, Ty, Legal);
913 setOperationAction(ISD::FCEIL, Ty, Legal);
914 setOperationAction(ISD::FROUND, Ty, Legal);
915 setOperationAction(ISD::FTRUNC, Ty, Legal);
916 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
917 setOperationAction(ISD::FRINT, Ty, Legal);
920 // We have target-specific dag combine patterns for the following nodes:
921 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
922 setTargetDAGCombine(ISD::ADD);
923 setTargetDAGCombine(ISD::SUB);
924 setTargetDAGCombine(ISD::MUL);
925 setTargetDAGCombine(ISD::AND);
926 setTargetDAGCombine(ISD::OR);
927 setTargetDAGCombine(ISD::XOR);
929 if (Subtarget->hasV6Ops())
930 setTargetDAGCombine(ISD::SRL);
932 setStackPointerRegisterToSaveRestore(ARM::SP);
934 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
935 !Subtarget->hasVFP2())
936 setSchedulingPreference(Sched::RegPressure);
938 setSchedulingPreference(Sched::Hybrid);
940 //// temporary - rewrite interface to use type
941 MaxStoresPerMemset = 8;
942 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
943 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
944 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
945 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
946 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948 // On ARM arguments smaller than 4 bytes are extended, so all arguments
949 // are at least 4 bytes aligned.
950 setMinStackArgumentAlignment(4);
952 // Prefer likely predicted branches to selects on out-of-order cores.
953 PredictableSelectIsExpensive = Subtarget->isLikeA9();
955 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
958 // FIXME: It might make sense to define the representative register class as the
959 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
960 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
961 // SPR's representative would be DPR_VFP2. This should work well if register
962 // pressure tracking were modified such that a register use would increment the
963 // pressure of the register class's representative and all of it's super
964 // classes' representatives transitively. We have not implemented this because
965 // of the difficulty prior to coalescing of modeling operand register classes
966 // due to the common occurrence of cross class copies and subregister insertions
968 std::pair<const TargetRegisterClass*, uint8_t>
969 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
970 const TargetRegisterClass *RRC = nullptr;
972 switch (VT.SimpleTy) {
974 return TargetLowering::findRepresentativeClass(VT);
975 // Use DPR as representative register class for all floating point
976 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
977 // the cost is 1 for both f32 and f64.
978 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
979 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
980 RRC = &ARM::DPRRegClass;
981 // When NEON is used for SP, only half of the register file is available
982 // because operations that define both SP and DP results will be constrained
983 // to the VFP2 class (D0-D15). We currently model this constraint prior to
984 // coalescing by double-counting the SP regs. See the FIXME above.
985 if (Subtarget->useNEONForSinglePrecisionFP())
988 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
989 case MVT::v4f32: case MVT::v2f64:
990 RRC = &ARM::DPRRegClass;
994 RRC = &ARM::DPRRegClass;
998 RRC = &ARM::DPRRegClass;
1002 return std::make_pair(RRC, Cost);
1005 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007 default: return nullptr;
1008 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1009 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1010 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1011 case ARMISD::CALL: return "ARMISD::CALL";
1012 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1013 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1014 case ARMISD::tCALL: return "ARMISD::tCALL";
1015 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1016 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1017 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1018 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1019 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1020 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1021 case ARMISD::CMP: return "ARMISD::CMP";
1022 case ARMISD::CMN: return "ARMISD::CMN";
1023 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1024 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1025 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1026 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1027 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1029 case ARMISD::CMOV: return "ARMISD::CMOV";
1031 case ARMISD::RBIT: return "ARMISD::RBIT";
1033 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1034 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1035 case ARMISD::SITOF: return "ARMISD::SITOF";
1036 case ARMISD::UITOF: return "ARMISD::UITOF";
1038 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1039 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1040 case ARMISD::RRX: return "ARMISD::RRX";
1042 case ARMISD::ADDC: return "ARMISD::ADDC";
1043 case ARMISD::ADDE: return "ARMISD::ADDE";
1044 case ARMISD::SUBC: return "ARMISD::SUBC";
1045 case ARMISD::SUBE: return "ARMISD::SUBE";
1047 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1048 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1050 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1051 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1055 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1059 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1063 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1065 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1066 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1067 case ARMISD::VCGE: return "ARMISD::VCGE";
1068 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1069 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1070 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1071 case ARMISD::VCGT: return "ARMISD::VCGT";
1072 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1073 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1074 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1075 case ARMISD::VTST: return "ARMISD::VTST";
1077 case ARMISD::VSHL: return "ARMISD::VSHL";
1078 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1079 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1080 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1081 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1082 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1083 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1084 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1085 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1086 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1087 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1088 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1089 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1090 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1091 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1092 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1093 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1094 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1095 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1096 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1097 case ARMISD::VDUP: return "ARMISD::VDUP";
1098 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1099 case ARMISD::VEXT: return "ARMISD::VEXT";
1100 case ARMISD::VREV64: return "ARMISD::VREV64";
1101 case ARMISD::VREV32: return "ARMISD::VREV32";
1102 case ARMISD::VREV16: return "ARMISD::VREV16";
1103 case ARMISD::VZIP: return "ARMISD::VZIP";
1104 case ARMISD::VUZP: return "ARMISD::VUZP";
1105 case ARMISD::VTRN: return "ARMISD::VTRN";
1106 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1107 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1108 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1109 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1110 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1111 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1112 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1113 case ARMISD::FMAX: return "ARMISD::FMAX";
1114 case ARMISD::FMIN: return "ARMISD::FMIN";
1115 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1116 case ARMISD::VMINNM: return "ARMISD::VMIN";
1117 case ARMISD::BFI: return "ARMISD::BFI";
1118 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1119 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1120 case ARMISD::VBSL: return "ARMISD::VBSL";
1121 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1122 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1123 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1124 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1125 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1126 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1127 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1128 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1129 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1130 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1131 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1132 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1133 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1134 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1135 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1136 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1137 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1138 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1139 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1140 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1144 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1145 if (!VT.isVector()) return getPointerTy();
1146 return VT.changeVectorElementTypeToInteger();
1149 /// getRegClassFor - Return the register class that should be used for the
1150 /// specified value type.
1151 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1152 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1153 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1154 // load / store 4 to 8 consecutive D registers.
1155 if (Subtarget->hasNEON()) {
1156 if (VT == MVT::v4i64)
1157 return &ARM::QQPRRegClass;
1158 if (VT == MVT::v8i64)
1159 return &ARM::QQQQPRRegClass;
1161 return TargetLowering::getRegClassFor(VT);
1164 // Create a fast isel object.
1166 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1167 const TargetLibraryInfo *libInfo) const {
1168 return ARM::createFastISel(funcInfo, libInfo);
1171 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1172 /// be used for loads / stores from the global.
1173 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1174 return (Subtarget->isThumb1Only() ? 127 : 4095);
1177 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1178 unsigned NumVals = N->getNumValues();
1180 return Sched::RegPressure;
1182 for (unsigned i = 0; i != NumVals; ++i) {
1183 EVT VT = N->getValueType(i);
1184 if (VT == MVT::Glue || VT == MVT::Other)
1186 if (VT.isFloatingPoint() || VT.isVector())
1190 if (!N->isMachineOpcode())
1191 return Sched::RegPressure;
1193 // Load are scheduled for latency even if there instruction itinerary
1194 // is not available.
1195 const TargetInstrInfo *TII =
1196 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1197 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199 if (MCID.getNumDefs() == 0)
1200 return Sched::RegPressure;
1201 if (!Itins->isEmpty() &&
1202 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1205 return Sched::RegPressure;
1208 //===----------------------------------------------------------------------===//
1210 //===----------------------------------------------------------------------===//
1212 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1213 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215 default: llvm_unreachable("Unknown condition code!");
1216 case ISD::SETNE: return ARMCC::NE;
1217 case ISD::SETEQ: return ARMCC::EQ;
1218 case ISD::SETGT: return ARMCC::GT;
1219 case ISD::SETGE: return ARMCC::GE;
1220 case ISD::SETLT: return ARMCC::LT;
1221 case ISD::SETLE: return ARMCC::LE;
1222 case ISD::SETUGT: return ARMCC::HI;
1223 case ISD::SETUGE: return ARMCC::HS;
1224 case ISD::SETULT: return ARMCC::LO;
1225 case ISD::SETULE: return ARMCC::LS;
1229 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1230 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1231 ARMCC::CondCodes &CondCode2) {
1232 CondCode2 = ARMCC::AL;
1234 default: llvm_unreachable("Unknown FP condition!");
1236 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1241 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1242 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1243 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1244 case ISD::SETO: CondCode = ARMCC::VC; break;
1245 case ISD::SETUO: CondCode = ARMCC::VS; break;
1246 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1247 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1248 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250 case ISD::SETULT: CondCode = ARMCC::LT; break;
1252 case ISD::SETULE: CondCode = ARMCC::LE; break;
1254 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1258 //===----------------------------------------------------------------------===//
1259 // Calling Convention Implementation
1260 //===----------------------------------------------------------------------===//
1262 #include "ARMGenCallingConv.inc"
1264 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1265 /// account presence of floating point hardware and calling convention
1266 /// limitations, such as support for variadic functions.
1268 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1269 bool isVarArg) const {
1272 llvm_unreachable("Unsupported calling convention");
1273 case CallingConv::ARM_AAPCS:
1274 case CallingConv::ARM_APCS:
1275 case CallingConv::GHC:
1277 case CallingConv::ARM_AAPCS_VFP:
1278 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1279 case CallingConv::C:
1280 if (!Subtarget->isAAPCS_ABI())
1281 return CallingConv::ARM_APCS;
1282 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1283 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285 return CallingConv::ARM_AAPCS_VFP;
1287 return CallingConv::ARM_AAPCS;
1288 case CallingConv::Fast:
1289 if (!Subtarget->isAAPCS_ABI()) {
1290 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1291 return CallingConv::Fast;
1292 return CallingConv::ARM_APCS;
1293 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1294 return CallingConv::ARM_AAPCS_VFP;
1296 return CallingConv::ARM_AAPCS;
1300 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1301 /// CallingConvention.
1302 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1304 bool isVarArg) const {
1305 switch (getEffectiveCallingConv(CC, isVarArg)) {
1307 llvm_unreachable("Unsupported calling convention");
1308 case CallingConv::ARM_APCS:
1309 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1310 case CallingConv::ARM_AAPCS:
1311 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1312 case CallingConv::ARM_AAPCS_VFP:
1313 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1314 case CallingConv::Fast:
1315 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1316 case CallingConv::GHC:
1317 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1321 /// LowerCallResult - Lower the result values of a call into the
1322 /// appropriate copies out of appropriate physical registers.
1324 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1325 CallingConv::ID CallConv, bool isVarArg,
1326 const SmallVectorImpl<ISD::InputArg> &Ins,
1327 SDLoc dl, SelectionDAG &DAG,
1328 SmallVectorImpl<SDValue> &InVals,
1329 bool isThisReturn, SDValue ThisVal) const {
1331 // Assign locations to each value returned by this call.
1332 SmallVector<CCValAssign, 16> RVLocs;
1333 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1334 *DAG.getContext(), Call);
1335 CCInfo.AnalyzeCallResult(Ins,
1336 CCAssignFnForNode(CallConv, /* Return*/ true,
1339 // Copy all of the result registers out of their specified physreg.
1340 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1341 CCValAssign VA = RVLocs[i];
1343 // Pass 'this' value directly from the argument to return value, to avoid
1344 // reg unit interference
1345 if (i == 0 && isThisReturn) {
1346 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1347 "unexpected return calling convention register assignment");
1348 InVals.push_back(ThisVal);
1353 if (VA.needsCustom()) {
1354 // Handle f64 or half of a v2f64.
1355 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357 Chain = Lo.getValue(1);
1358 InFlag = Lo.getValue(2);
1359 VA = RVLocs[++i]; // skip ahead to next loc
1360 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362 Chain = Hi.getValue(1);
1363 InFlag = Hi.getValue(2);
1364 if (!Subtarget->isLittle())
1366 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1368 if (VA.getLocVT() == MVT::v2f64) {
1369 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1370 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1371 DAG.getConstant(0, MVT::i32));
1373 VA = RVLocs[++i]; // skip ahead to next loc
1374 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1375 Chain = Lo.getValue(1);
1376 InFlag = Lo.getValue(2);
1377 VA = RVLocs[++i]; // skip ahead to next loc
1378 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1379 Chain = Hi.getValue(1);
1380 InFlag = Hi.getValue(2);
1381 if (!Subtarget->isLittle())
1383 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1384 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1385 DAG.getConstant(1, MVT::i32));
1388 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1390 Chain = Val.getValue(1);
1391 InFlag = Val.getValue(2);
1394 switch (VA.getLocInfo()) {
1395 default: llvm_unreachable("Unknown loc info!");
1396 case CCValAssign::Full: break;
1397 case CCValAssign::BCvt:
1398 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1402 InVals.push_back(Val);
1408 /// LowerMemOpCallTo - Store the argument to the stack.
1410 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1411 SDValue StackPtr, SDValue Arg,
1412 SDLoc dl, SelectionDAG &DAG,
1413 const CCValAssign &VA,
1414 ISD::ArgFlagsTy Flags) const {
1415 unsigned LocMemOffset = VA.getLocMemOffset();
1416 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1417 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1418 return DAG.getStore(Chain, dl, Arg, PtrOff,
1419 MachinePointerInfo::getStack(LocMemOffset),
1423 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1424 SDValue Chain, SDValue &Arg,
1425 RegsToPassVector &RegsToPass,
1426 CCValAssign &VA, CCValAssign &NextVA,
1428 SmallVectorImpl<SDValue> &MemOpChains,
1429 ISD::ArgFlagsTy Flags) const {
1431 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1432 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1433 unsigned id = Subtarget->isLittle() ? 0 : 1;
1434 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1436 if (NextVA.isRegLoc())
1437 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1439 assert(NextVA.isMemLoc());
1440 if (!StackPtr.getNode())
1441 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1443 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1449 /// LowerCall - Lowering a call into a callseq_start <-
1450 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1453 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1454 SmallVectorImpl<SDValue> &InVals) const {
1455 SelectionDAG &DAG = CLI.DAG;
1457 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1458 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1459 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1460 SDValue Chain = CLI.Chain;
1461 SDValue Callee = CLI.Callee;
1462 bool &isTailCall = CLI.IsTailCall;
1463 CallingConv::ID CallConv = CLI.CallConv;
1464 bool doesNotRet = CLI.DoesNotReturn;
1465 bool isVarArg = CLI.IsVarArg;
1467 MachineFunction &MF = DAG.getMachineFunction();
1468 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1469 bool isThisReturn = false;
1470 bool isSibCall = false;
1472 // Disable tail calls if they're not supported.
1473 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1477 // Check if it's really possible to do a tail call.
1478 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1479 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1480 Outs, OutVals, Ins, DAG);
1481 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1482 report_fatal_error("failed to perform tail call elimination on a call "
1483 "site marked musttail");
1484 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1485 // detected sibcalls.
1492 // Analyze operands of the call, assigning locations to each operand.
1493 SmallVector<CCValAssign, 16> ArgLocs;
1494 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1495 *DAG.getContext(), Call);
1496 CCInfo.AnalyzeCallOperands(Outs,
1497 CCAssignFnForNode(CallConv, /* Return*/ false,
1500 // Get a count of how many bytes are to be pushed on the stack.
1501 unsigned NumBytes = CCInfo.getNextStackOffset();
1503 // For tail calls, memory operands are available in our caller's stack.
1507 // Adjust the stack pointer for the new arguments...
1508 // These operations are automatically eliminated by the prolog/epilog pass
1510 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1513 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1515 RegsToPassVector RegsToPass;
1516 SmallVector<SDValue, 8> MemOpChains;
1518 // Walk the register/memloc assignments, inserting copies/loads. In the case
1519 // of tail call optimization, arguments are handled later.
1520 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1522 ++i, ++realArgIdx) {
1523 CCValAssign &VA = ArgLocs[i];
1524 SDValue Arg = OutVals[realArgIdx];
1525 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1526 bool isByVal = Flags.isByVal();
1528 // Promote the value if needed.
1529 switch (VA.getLocInfo()) {
1530 default: llvm_unreachable("Unknown loc info!");
1531 case CCValAssign::Full: break;
1532 case CCValAssign::SExt:
1533 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1535 case CCValAssign::ZExt:
1536 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1538 case CCValAssign::AExt:
1539 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1541 case CCValAssign::BCvt:
1542 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1546 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1547 if (VA.needsCustom()) {
1548 if (VA.getLocVT() == MVT::v2f64) {
1549 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1550 DAG.getConstant(0, MVT::i32));
1551 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1552 DAG.getConstant(1, MVT::i32));
1554 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1555 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557 VA = ArgLocs[++i]; // skip ahead to next loc
1558 if (VA.isRegLoc()) {
1559 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1560 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562 assert(VA.isMemLoc());
1564 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1565 dl, DAG, VA, Flags));
1568 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1569 StackPtr, MemOpChains, Flags);
1571 } else if (VA.isRegLoc()) {
1572 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1573 assert(VA.getLocVT() == MVT::i32 &&
1574 "unexpected calling convention register assignment");
1575 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1576 "unexpected use of 'returned'");
1577 isThisReturn = true;
1579 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1580 } else if (isByVal) {
1581 assert(VA.isMemLoc());
1582 unsigned offset = 0;
1584 // True if this byval aggregate will be split between registers
1586 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1587 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1589 if (CurByValIdx < ByValArgsCount) {
1591 unsigned RegBegin, RegEnd;
1592 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1594 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1596 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1597 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1598 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1599 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1600 MachinePointerInfo(),
1601 false, false, false,
1602 DAG.InferPtrAlignment(AddArg));
1603 MemOpChains.push_back(Load.getValue(1));
1604 RegsToPass.push_back(std::make_pair(j, Load));
1607 // If parameter size outsides register area, "offset" value
1608 // helps us to calculate stack slot for remained part properly.
1609 offset = RegEnd - RegBegin;
1611 CCInfo.nextInRegsParam();
1614 if (Flags.getByValSize() > 4*offset) {
1615 unsigned LocMemOffset = VA.getLocMemOffset();
1616 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1617 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1619 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1620 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1621 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1623 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1625 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1626 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1627 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1630 } else if (!isSibCall) {
1631 assert(VA.isMemLoc());
1633 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1634 dl, DAG, VA, Flags));
1638 if (!MemOpChains.empty())
1639 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1641 // Build a sequence of copy-to-reg nodes chained together with token chain
1642 // and flag operands which copy the outgoing args into the appropriate regs.
1644 // Tail call byval lowering might overwrite argument registers so in case of
1645 // tail call optimization the copies to registers are lowered later.
1647 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1648 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1649 RegsToPass[i].second, InFlag);
1650 InFlag = Chain.getValue(1);
1653 // For tail calls lower the arguments to the 'real' stack slot.
1655 // Force all the incoming stack arguments to be loaded from the stack
1656 // before any new outgoing arguments are stored to the stack, because the
1657 // outgoing stack slots may alias the incoming argument stack slots, and
1658 // the alias isn't otherwise explicit. This is slightly more conservative
1659 // than necessary, because it means that each store effectively depends
1660 // on every argument instead of just those arguments it would clobber.
1662 // Do not flag preceding copytoreg stuff together with the following stuff.
1664 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666 RegsToPass[i].second, InFlag);
1667 InFlag = Chain.getValue(1);
1672 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1673 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1674 // node so that legalize doesn't hack it.
1675 bool isDirect = false;
1676 bool isARMFunc = false;
1677 bool isLocalARMFunc = false;
1678 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1680 if (EnableARMLongCalls) {
1681 assert((Subtarget->isTargetWindows() ||
1682 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1683 "long-calls with non-static relocation model!");
1684 // Handle a global address or an external symbol. If it's not one of
1685 // those, the target's already in a register, so we don't need to do
1687 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1688 const GlobalValue *GV = G->getGlobal();
1689 // Create a constant pool entry for the callee address
1690 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1691 ARMConstantPoolValue *CPV =
1692 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1694 // Get the address of the callee into a register
1695 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1696 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1697 Callee = DAG.getLoad(getPointerTy(), dl,
1698 DAG.getEntryNode(), CPAddr,
1699 MachinePointerInfo::getConstantPool(),
1700 false, false, false, 0);
1701 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1702 const char *Sym = S->getSymbol();
1704 // Create a constant pool entry for the callee address
1705 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1706 ARMConstantPoolValue *CPV =
1707 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1708 ARMPCLabelIndex, 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);
1717 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1718 const GlobalValue *GV = G->getGlobal();
1720 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1721 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1722 getTargetMachine().getRelocationModel() != Reloc::Static;
1723 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1724 // ARM call to a local ARM function is predicable.
1725 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1726 // tBX takes a register source operand.
1727 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1728 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1729 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1730 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1731 0, ARMII::MO_NONLAZY));
1732 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1733 MachinePointerInfo::getGOT(), false, false, true, 0);
1734 } else if (Subtarget->isTargetCOFF()) {
1735 assert(Subtarget->isTargetWindows() &&
1736 "Windows is the only supported COFF target");
1737 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1738 ? ARMII::MO_DLLIMPORT
1739 : ARMII::MO_NO_FLAG;
1740 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1742 if (GV->hasDLLImportStorageClass())
1743 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1744 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1745 Callee), MachinePointerInfo::getGOT(),
1746 false, false, false, 0);
1748 // On ELF targets for PIC code, direct calls should go through the PLT
1749 unsigned OpFlags = 0;
1750 if (Subtarget->isTargetELF() &&
1751 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1752 OpFlags = ARMII::MO_PLT;
1753 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1755 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1757 bool isStub = Subtarget->isTargetMachO() &&
1758 getTargetMachine().getRelocationModel() != Reloc::Static;
1759 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1760 // tBX takes a register source operand.
1761 const char *Sym = S->getSymbol();
1762 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1763 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1764 ARMConstantPoolValue *CPV =
1765 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1766 ARMPCLabelIndex, 4);
1767 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1768 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769 Callee = DAG.getLoad(getPointerTy(), dl,
1770 DAG.getEntryNode(), CPAddr,
1771 MachinePointerInfo::getConstantPool(),
1772 false, false, false, 0);
1773 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1774 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1775 getPointerTy(), Callee, PICLabel);
1777 unsigned OpFlags = 0;
1778 // On ELF targets for PIC code, direct calls should go through the PLT
1779 if (Subtarget->isTargetELF() &&
1780 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1781 OpFlags = ARMII::MO_PLT;
1782 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1786 // FIXME: handle tail calls differently.
1788 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1789 AttributeSet::FunctionIndex, Attribute::MinSize);
1790 if (Subtarget->isThumb()) {
1791 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1792 CallOpc = ARMISD::CALL_NOLINK;
1794 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1796 if (!isDirect && !Subtarget->hasV5TOps())
1797 CallOpc = ARMISD::CALL_NOLINK;
1798 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1799 // Emit regular call when code size is the priority
1801 // "mov lr, pc; b _foo" to avoid confusing the RSP
1802 CallOpc = ARMISD::CALL_NOLINK;
1804 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1807 std::vector<SDValue> Ops;
1808 Ops.push_back(Chain);
1809 Ops.push_back(Callee);
1811 // Add argument registers to the end of the list so that they are known live
1813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815 RegsToPass[i].second.getValueType()));
1817 // Add a register mask operand representing the call-preserved registers.
1819 const uint32_t *Mask;
1820 const TargetRegisterInfo *TRI =
1821 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1822 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1824 // For 'this' returns, use the R0-preserving mask if applicable
1825 Mask = ARI->getThisReturnPreservedMask(CallConv);
1827 // Set isThisReturn to false if the calling convention is not one that
1828 // allows 'returned' to be modeled in this way, so LowerCallResult does
1829 // not try to pass 'this' straight through
1830 isThisReturn = false;
1831 Mask = ARI->getCallPreservedMask(CallConv);
1834 Mask = ARI->getCallPreservedMask(CallConv);
1836 assert(Mask && "Missing call preserved mask for calling convention");
1837 Ops.push_back(DAG.getRegisterMask(Mask));
1840 if (InFlag.getNode())
1841 Ops.push_back(InFlag);
1843 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847 // Returns a chain and a flag for retval copy to use.
1848 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1849 InFlag = Chain.getValue(1);
1851 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1852 DAG.getIntPtrConstant(0, true), InFlag, dl);
1854 InFlag = Chain.getValue(1);
1856 // Handle result values, copying them out of physregs into vregs that we
1858 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1859 InVals, isThisReturn,
1860 isThisReturn ? OutVals[0] : SDValue());
1863 /// HandleByVal - Every parameter *after* a byval parameter is passed
1864 /// on the stack. Remember the next parameter register to allocate,
1865 /// and then confiscate the rest of the parameter registers to insure
1868 ARMTargetLowering::HandleByVal(
1869 CCState *State, unsigned &size, unsigned Align) const {
1870 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1871 assert((State->getCallOrPrologue() == Prologue ||
1872 State->getCallOrPrologue() == Call) &&
1873 "unhandled ParmContext");
1875 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1876 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1877 unsigned AlignInRegs = Align / 4;
1878 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1879 for (unsigned i = 0; i < Waste; ++i)
1880 reg = State->AllocateReg(GPRArgRegs, 4);
1883 unsigned excess = 4 * (ARM::R4 - reg);
1885 // Special case when NSAA != SP and parameter size greater than size of
1886 // all remained GPR regs. In that case we can't split parameter, we must
1887 // send it to stack. We also must set NCRN to R4, so waste all
1888 // remained registers.
1889 const unsigned NSAAOffset = State->getNextStackOffset();
1890 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1891 while (State->AllocateReg(GPRArgRegs, 4))
1896 // First register for byval parameter is the first register that wasn't
1897 // allocated before this method call, so it would be "reg".
1898 // If parameter is small enough to be saved in range [reg, r4), then
1899 // the end (first after last) register would be reg + param-size-in-regs,
1900 // else parameter would be splitted between registers and stack,
1901 // end register would be r4 in this case.
1902 unsigned ByValRegBegin = reg;
1903 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1904 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1905 // Note, first register is allocated in the beginning of function already,
1906 // allocate remained amount of registers we need.
1907 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1908 State->AllocateReg(GPRArgRegs, 4);
1909 // A byval parameter that is split between registers and memory needs its
1910 // size truncated here.
1911 // In the case where the entire structure fits in registers, we set the
1912 // size in memory to zero.
1921 /// MatchingStackOffset - Return true if the given stack call argument is
1922 /// already available in the same position (relatively) of the caller's
1923 /// incoming argument stack.
1925 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1926 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1927 const TargetInstrInfo *TII) {
1928 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1930 if (Arg.getOpcode() == ISD::CopyFromReg) {
1931 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1932 if (!TargetRegisterInfo::isVirtualRegister(VR))
1934 MachineInstr *Def = MRI->getVRegDef(VR);
1937 if (!Flags.isByVal()) {
1938 if (!TII->isLoadFromStackSlot(Def, FI))
1943 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1944 if (Flags.isByVal())
1945 // ByVal argument is passed in as a pointer but it's now being
1946 // dereferenced. e.g.
1947 // define @foo(%struct.X* %A) {
1948 // tail call @bar(%struct.X* byval %A)
1951 SDValue Ptr = Ld->getBasePtr();
1952 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1955 FI = FINode->getIndex();
1959 assert(FI != INT_MAX);
1960 if (!MFI->isFixedObjectIndex(FI))
1962 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1965 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1966 /// for tail call optimization. Targets which want to do tail call
1967 /// optimization should implement this function.
1969 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1970 CallingConv::ID CalleeCC,
1972 bool isCalleeStructRet,
1973 bool isCallerStructRet,
1974 const SmallVectorImpl<ISD::OutputArg> &Outs,
1975 const SmallVectorImpl<SDValue> &OutVals,
1976 const SmallVectorImpl<ISD::InputArg> &Ins,
1977 SelectionDAG& DAG) const {
1978 const Function *CallerF = DAG.getMachineFunction().getFunction();
1979 CallingConv::ID CallerCC = CallerF->getCallingConv();
1980 bool CCMatch = CallerCC == CalleeCC;
1982 // Look for obvious safe cases to perform tail call optimization that do not
1983 // require ABI changes. This is what gcc calls sibcall.
1985 // Do not sibcall optimize vararg calls unless the call site is not passing
1987 if (isVarArg && !Outs.empty())
1990 // Exception-handling functions need a special set of instructions to indicate
1991 // a return to the hardware. Tail-calling another function would probably
1993 if (CallerF->hasFnAttribute("interrupt"))
1996 // Also avoid sibcall optimization if either caller or callee uses struct
1997 // return semantics.
1998 if (isCalleeStructRet || isCallerStructRet)
2001 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2002 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2003 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2004 // support in the assembler and linker to be used. This would need to be
2005 // fixed to fully support tail calls in Thumb1.
2007 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2008 // LR. This means if we need to reload LR, it takes an extra instructions,
2009 // which outweighs the value of the tail call; but here we don't know yet
2010 // whether LR is going to be used. Probably the right approach is to
2011 // generate the tail call here and turn it back into CALL/RET in
2012 // emitEpilogue if LR is used.
2014 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2015 // but we need to make sure there are enough registers; the only valid
2016 // registers are the 4 used for parameters. We don't currently do this
2018 if (Subtarget->isThumb1Only())
2021 // Externally-defined functions with weak linkage should not be
2022 // tail-called on ARM when the OS does not support dynamic
2023 // pre-emption of symbols, as the AAELF spec requires normal calls
2024 // to undefined weak functions to be replaced with a NOP or jump to the
2025 // next instruction. The behaviour of branch instructions in this
2026 // situation (as used for tail calls) is implementation-defined, so we
2027 // cannot rely on the linker replacing the tail call with a return.
2028 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2029 const GlobalValue *GV = G->getGlobal();
2030 if (GV->hasExternalWeakLinkage())
2034 // If the calling conventions do not match, then we'd better make sure the
2035 // results are returned in the same way as what the caller expects.
2037 SmallVector<CCValAssign, 16> RVLocs1;
2038 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2039 *DAG.getContext(), Call);
2040 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2042 SmallVector<CCValAssign, 16> RVLocs2;
2043 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2044 *DAG.getContext(), Call);
2045 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2047 if (RVLocs1.size() != RVLocs2.size())
2049 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2050 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2052 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2054 if (RVLocs1[i].isRegLoc()) {
2055 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2058 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2064 // If Caller's vararg or byval argument has been split between registers and
2065 // stack, do not perform tail call, since part of the argument is in caller's
2067 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2068 getInfo<ARMFunctionInfo>();
2069 if (AFI_Caller->getArgRegsSaveSize())
2072 // If the callee takes no arguments then go on to check the results of the
2074 if (!Outs.empty()) {
2075 // Check if stack adjustment is needed. For now, do not do this if any
2076 // argument is passed on the stack.
2077 SmallVector<CCValAssign, 16> ArgLocs;
2078 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2079 *DAG.getContext(), Call);
2080 CCInfo.AnalyzeCallOperands(Outs,
2081 CCAssignFnForNode(CalleeCC, false, isVarArg));
2082 if (CCInfo.getNextStackOffset()) {
2083 MachineFunction &MF = DAG.getMachineFunction();
2085 // Check if the arguments are already laid out in the right way as
2086 // the caller's fixed stack objects.
2087 MachineFrameInfo *MFI = MF.getFrameInfo();
2088 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2089 const TargetInstrInfo *TII =
2090 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2091 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2093 ++i, ++realArgIdx) {
2094 CCValAssign &VA = ArgLocs[i];
2095 EVT RegVT = VA.getLocVT();
2096 SDValue Arg = OutVals[realArgIdx];
2097 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2098 if (VA.getLocInfo() == CCValAssign::Indirect)
2100 if (VA.needsCustom()) {
2101 // f64 and vector types are split into multiple registers or
2102 // register/stack-slot combinations. The types will not match
2103 // the registers; give up on memory f64 refs until we figure
2104 // out what to do about this.
2107 if (!ArgLocs[++i].isRegLoc())
2109 if (RegVT == MVT::v2f64) {
2110 if (!ArgLocs[++i].isRegLoc())
2112 if (!ArgLocs[++i].isRegLoc())
2115 } else if (!VA.isRegLoc()) {
2116 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2128 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2129 MachineFunction &MF, bool isVarArg,
2130 const SmallVectorImpl<ISD::OutputArg> &Outs,
2131 LLVMContext &Context) const {
2132 SmallVector<CCValAssign, 16> RVLocs;
2133 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2134 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2138 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2139 SDLoc DL, SelectionDAG &DAG) {
2140 const MachineFunction &MF = DAG.getMachineFunction();
2141 const Function *F = MF.getFunction();
2143 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2145 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2146 // version of the "preferred return address". These offsets affect the return
2147 // instruction if this is a return from PL1 without hypervisor extensions.
2148 // IRQ/FIQ: +4 "subs pc, lr, #4"
2149 // SWI: 0 "subs pc, lr, #0"
2150 // ABORT: +4 "subs pc, lr, #4"
2151 // UNDEF: +4/+2 "subs pc, lr, #0"
2152 // UNDEF varies depending on where the exception came from ARM or Thumb
2153 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2156 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2159 else if (IntKind == "SWI" || IntKind == "UNDEF")
2162 report_fatal_error("Unsupported interrupt attribute. If present, value "
2163 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2165 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2167 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2171 ARMTargetLowering::LowerReturn(SDValue Chain,
2172 CallingConv::ID CallConv, bool isVarArg,
2173 const SmallVectorImpl<ISD::OutputArg> &Outs,
2174 const SmallVectorImpl<SDValue> &OutVals,
2175 SDLoc dl, SelectionDAG &DAG) const {
2177 // CCValAssign - represent the assignment of the return value to a location.
2178 SmallVector<CCValAssign, 16> RVLocs;
2180 // CCState - Info about the registers and stack slots.
2181 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2182 *DAG.getContext(), Call);
2184 // Analyze outgoing return values.
2185 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2189 SmallVector<SDValue, 4> RetOps;
2190 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2191 bool isLittleEndian = Subtarget->isLittle();
2193 MachineFunction &MF = DAG.getMachineFunction();
2194 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2195 AFI->setReturnRegsCount(RVLocs.size());
2197 // Copy the result values into the output registers.
2198 for (unsigned i = 0, realRVLocIdx = 0;
2200 ++i, ++realRVLocIdx) {
2201 CCValAssign &VA = RVLocs[i];
2202 assert(VA.isRegLoc() && "Can only return in registers!");
2204 SDValue Arg = OutVals[realRVLocIdx];
2206 switch (VA.getLocInfo()) {
2207 default: llvm_unreachable("Unknown loc info!");
2208 case CCValAssign::Full: break;
2209 case CCValAssign::BCvt:
2210 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2214 if (VA.needsCustom()) {
2215 if (VA.getLocVT() == MVT::v2f64) {
2216 // Extract the first half and return it in two registers.
2217 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2218 DAG.getConstant(0, MVT::i32));
2219 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2220 DAG.getVTList(MVT::i32, MVT::i32), Half);
2222 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2223 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2225 Flag = Chain.getValue(1);
2226 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2227 VA = RVLocs[++i]; // skip ahead to next loc
2228 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2231 Flag = Chain.getValue(1);
2232 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233 VA = RVLocs[++i]; // skip ahead to next loc
2235 // Extract the 2nd half and fall through to handle it as an f64 value.
2236 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2237 DAG.getConstant(1, MVT::i32));
2239 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2241 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2242 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2243 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2244 fmrrd.getValue(isLittleEndian ? 0 : 1),
2246 Flag = Chain.getValue(1);
2247 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2248 VA = RVLocs[++i]; // skip ahead to next loc
2249 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2250 fmrrd.getValue(isLittleEndian ? 1 : 0),
2253 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2255 // Guarantee that all emitted copies are
2256 // stuck together, avoiding something bad.
2257 Flag = Chain.getValue(1);
2258 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2261 // Update chain and glue.
2264 RetOps.push_back(Flag);
2266 // CPUs which aren't M-class use a special sequence to return from
2267 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2268 // though we use "subs pc, lr, #N").
2270 // M-class CPUs actually use a normal return sequence with a special
2271 // (hardware-provided) value in LR, so the normal code path works.
2272 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2273 !Subtarget->isMClass()) {
2274 if (Subtarget->isThumb1Only())
2275 report_fatal_error("interrupt attribute is not supported in Thumb1");
2276 return LowerInterruptReturn(RetOps, dl, DAG);
2279 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2282 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2283 if (N->getNumValues() != 1)
2285 if (!N->hasNUsesOfValue(1, 0))
2288 SDValue TCChain = Chain;
2289 SDNode *Copy = *N->use_begin();
2290 if (Copy->getOpcode() == ISD::CopyToReg) {
2291 // If the copy has a glue operand, we conservatively assume it isn't safe to
2292 // perform a tail call.
2293 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2295 TCChain = Copy->getOperand(0);
2296 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2297 SDNode *VMov = Copy;
2298 // f64 returned in a pair of GPRs.
2299 SmallPtrSet<SDNode*, 2> Copies;
2300 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2302 if (UI->getOpcode() != ISD::CopyToReg)
2306 if (Copies.size() > 2)
2309 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2311 SDValue UseChain = UI->getOperand(0);
2312 if (Copies.count(UseChain.getNode()))
2319 } else if (Copy->getOpcode() == ISD::BITCAST) {
2320 // f32 returned in a single GPR.
2321 if (!Copy->hasOneUse())
2323 Copy = *Copy->use_begin();
2324 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2326 TCChain = Copy->getOperand(0);
2331 bool HasRet = false;
2332 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2334 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2335 UI->getOpcode() != ARMISD::INTRET_FLAG)
2347 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2348 if (!Subtarget->supportsTailCall())
2351 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2354 return !Subtarget->isThumb1Only();
2357 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2358 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2359 // one of the above mentioned nodes. It has to be wrapped because otherwise
2360 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2361 // be used to form addressing mode. These wrapped nodes will be selected
2363 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2364 EVT PtrVT = Op.getValueType();
2365 // FIXME there is no actual debug info here
2367 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2369 if (CP->isMachineConstantPoolEntry())
2370 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2371 CP->getAlignment());
2373 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2374 CP->getAlignment());
2375 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2378 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2379 return MachineJumpTableInfo::EK_Inline;
2382 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2383 SelectionDAG &DAG) const {
2384 MachineFunction &MF = DAG.getMachineFunction();
2385 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2386 unsigned ARMPCLabelIndex = 0;
2388 EVT PtrVT = getPointerTy();
2389 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2390 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2392 if (RelocM == Reloc::Static) {
2393 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2395 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2396 ARMPCLabelIndex = AFI->createPICLabelUId();
2397 ARMConstantPoolValue *CPV =
2398 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2399 ARMCP::CPBlockAddress, PCAdj);
2400 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2402 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2403 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2404 MachinePointerInfo::getConstantPool(),
2405 false, false, false, 0);
2406 if (RelocM == Reloc::Static)
2408 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2409 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2412 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2414 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2415 SelectionDAG &DAG) const {
2417 EVT PtrVT = getPointerTy();
2418 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2419 MachineFunction &MF = DAG.getMachineFunction();
2420 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2421 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2422 ARMConstantPoolValue *CPV =
2423 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2424 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2425 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2426 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2427 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2428 MachinePointerInfo::getConstantPool(),
2429 false, false, false, 0);
2430 SDValue Chain = Argument.getValue(1);
2432 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2433 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2435 // call __tls_get_addr.
2438 Entry.Node = Argument;
2439 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2440 Args.push_back(Entry);
2442 // FIXME: is there useful debug info available here?
2443 TargetLowering::CallLoweringInfo CLI(DAG);
2444 CLI.setDebugLoc(dl).setChain(Chain)
2445 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2446 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2449 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2450 return CallResult.first;
2453 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2454 // "local exec" model.
2456 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2458 TLSModel::Model model) const {
2459 const GlobalValue *GV = GA->getGlobal();
2462 SDValue Chain = DAG.getEntryNode();
2463 EVT PtrVT = getPointerTy();
2464 // Get the Thread Pointer
2465 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2467 if (model == TLSModel::InitialExec) {
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2470 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2471 // Initial exec model.
2472 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2473 ARMConstantPoolValue *CPV =
2474 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2475 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2477 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2478 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2479 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2480 MachinePointerInfo::getConstantPool(),
2481 false, false, false, 0);
2482 Chain = Offset.getValue(1);
2484 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2485 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2487 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2488 MachinePointerInfo::getConstantPool(),
2489 false, false, false, 0);
2492 assert(model == TLSModel::LocalExec);
2493 ARMConstantPoolValue *CPV =
2494 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2495 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2496 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2497 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2498 MachinePointerInfo::getConstantPool(),
2499 false, false, false, 0);
2502 // The address of the thread local variable is the add of the thread
2503 // pointer with the offset of the variable.
2504 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2508 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2509 // TODO: implement the "local dynamic" model
2510 assert(Subtarget->isTargetELF() &&
2511 "TLS not implemented for non-ELF targets");
2512 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2514 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2517 case TLSModel::GeneralDynamic:
2518 case TLSModel::LocalDynamic:
2519 return LowerToTLSGeneralDynamicModel(GA, DAG);
2520 case TLSModel::InitialExec:
2521 case TLSModel::LocalExec:
2522 return LowerToTLSExecModels(GA, DAG, model);
2524 llvm_unreachable("bogus TLS model");
2527 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2528 SelectionDAG &DAG) const {
2529 EVT PtrVT = getPointerTy();
2531 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2532 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2533 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2534 ARMConstantPoolValue *CPV =
2535 ARMConstantPoolConstant::Create(GV,
2536 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2537 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2538 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2539 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2541 MachinePointerInfo::getConstantPool(),
2542 false, false, false, 0);
2543 SDValue Chain = Result.getValue(1);
2544 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2545 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2547 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2548 MachinePointerInfo::getGOT(),
2549 false, false, false, 0);
2553 // If we have T2 ops, we can materialize the address directly via movt/movw
2554 // pair. This is always cheaper.
2555 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2557 // FIXME: Once remat is capable of dealing with instructions with register
2558 // operands, expand this into two nodes.
2559 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2560 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2562 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2563 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2564 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2565 MachinePointerInfo::getConstantPool(),
2566 false, false, false, 0);
2570 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2571 SelectionDAG &DAG) const {
2572 EVT PtrVT = getPointerTy();
2574 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2575 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2577 if (Subtarget->useMovt(DAG.getMachineFunction()))
2580 // FIXME: Once remat is capable of dealing with instructions with register
2581 // operands, expand this into multiple nodes
2583 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2585 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2586 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2588 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2589 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2590 MachinePointerInfo::getGOT(), false, false, false, 0);
2594 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2595 SelectionDAG &DAG) const {
2596 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2597 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2598 "Windows on ARM expects to use movw/movt");
2600 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2601 const ARMII::TOF TargetFlags =
2602 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2603 EVT PtrVT = getPointerTy();
2609 // FIXME: Once remat is capable of dealing with instructions with register
2610 // operands, expand this into two nodes.
2611 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2612 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2614 if (GV->hasDLLImportStorageClass())
2615 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2616 MachinePointerInfo::getGOT(), false, false, false, 0);
2620 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2621 SelectionDAG &DAG) const {
2622 assert(Subtarget->isTargetELF() &&
2623 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2626 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2627 EVT PtrVT = getPointerTy();
2629 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2630 ARMConstantPoolValue *CPV =
2631 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2632 ARMPCLabelIndex, PCAdj);
2633 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2634 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2635 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2636 MachinePointerInfo::getConstantPool(),
2637 false, false, false, 0);
2638 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2639 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2643 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2645 SDValue Val = DAG.getConstant(0, MVT::i32);
2646 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2647 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2648 Op.getOperand(1), Val);
2652 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2654 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2655 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2659 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2660 const ARMSubtarget *Subtarget) const {
2661 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2664 default: return SDValue(); // Don't custom lower most intrinsics.
2665 case Intrinsic::arm_rbit: {
2666 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2667 "RBIT intrinsic must have i32 type!");
2668 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2670 case Intrinsic::arm_thread_pointer: {
2671 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2672 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2674 case Intrinsic::eh_sjlj_lsda: {
2675 MachineFunction &MF = DAG.getMachineFunction();
2676 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2677 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2678 EVT PtrVT = getPointerTy();
2679 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2681 unsigned PCAdj = (RelocM != Reloc::PIC_)
2682 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2683 ARMConstantPoolValue *CPV =
2684 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2685 ARMCP::CPLSDA, PCAdj);
2686 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2687 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2689 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2690 MachinePointerInfo::getConstantPool(),
2691 false, false, false, 0);
2693 if (RelocM == Reloc::PIC_) {
2694 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2695 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2699 case Intrinsic::arm_neon_vmulls:
2700 case Intrinsic::arm_neon_vmullu: {
2701 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2702 ? ARMISD::VMULLs : ARMISD::VMULLu;
2703 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2704 Op.getOperand(1), Op.getOperand(2));
2709 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2710 const ARMSubtarget *Subtarget) {
2711 // FIXME: handle "fence singlethread" more efficiently.
2713 if (!Subtarget->hasDataBarrier()) {
2714 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2715 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2717 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2718 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2719 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2720 DAG.getConstant(0, MVT::i32));
2723 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2724 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2725 unsigned Domain = ARM_MB::ISH;
2726 if (Subtarget->isMClass()) {
2727 // Only a full system barrier exists in the M-class architectures.
2728 Domain = ARM_MB::SY;
2729 } else if (Subtarget->isSwift() && Ord == Release) {
2730 // Swift happens to implement ISHST barriers in a way that's compatible with
2731 // Release semantics but weaker than ISH so we'd be fools not to use
2732 // it. Beware: other processors probably don't!
2733 Domain = ARM_MB::ISHST;
2736 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2737 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2738 DAG.getConstant(Domain, MVT::i32));
2741 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2742 const ARMSubtarget *Subtarget) {
2743 // ARM pre v5TE and Thumb1 does not have preload instructions.
2744 if (!(Subtarget->isThumb2() ||
2745 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2746 // Just preserve the chain.
2747 return Op.getOperand(0);
2750 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2752 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2753 // ARMv7 with MP extension has PLDW.
2754 return Op.getOperand(0);
2756 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2757 if (Subtarget->isThumb()) {
2759 isRead = ~isRead & 1;
2760 isData = ~isData & 1;
2763 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2764 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2765 DAG.getConstant(isData, MVT::i32));
2768 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2769 MachineFunction &MF = DAG.getMachineFunction();
2770 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2772 // vastart just stores the address of the VarArgsFrameIndex slot into the
2773 // memory location argument.
2775 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2776 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2777 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2778 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2779 MachinePointerInfo(SV), false, false, 0);
2783 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2784 SDValue &Root, SelectionDAG &DAG,
2786 MachineFunction &MF = DAG.getMachineFunction();
2787 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2789 const TargetRegisterClass *RC;
2790 if (AFI->isThumb1OnlyFunction())
2791 RC = &ARM::tGPRRegClass;
2793 RC = &ARM::GPRRegClass;
2795 // Transform the arguments stored in physical registers into virtual ones.
2796 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2797 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2800 if (NextVA.isMemLoc()) {
2801 MachineFrameInfo *MFI = MF.getFrameInfo();
2802 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2804 // Create load node to retrieve arguments from the stack.
2805 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2806 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2807 MachinePointerInfo::getFixedStack(FI),
2808 false, false, false, 0);
2810 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2811 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813 if (!Subtarget->isLittle())
2814 std::swap (ArgValue, ArgValue2);
2815 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2819 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2820 unsigned InRegsParamRecordIdx,
2822 unsigned &ArgRegsSize,
2823 unsigned &ArgRegsSaveSize)
2826 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2827 unsigned RBegin, REnd;
2828 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2829 NumGPRs = REnd - RBegin;
2831 unsigned int firstUnalloced;
2832 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2833 sizeof(GPRArgRegs) /
2834 sizeof(GPRArgRegs[0]));
2835 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2838 unsigned Align = MF.getTarget()
2840 ->getFrameLowering()
2841 ->getStackAlignment();
2842 ArgRegsSize = NumGPRs * 4;
2844 // If parameter is split between stack and GPRs...
2845 if (NumGPRs && Align > 4 &&
2846 (ArgRegsSize < ArgSize ||
2847 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2848 // Add padding for part of param recovered from GPRs. For example,
2849 // if Align == 8, its last byte must be at address K*8 - 1.
2850 // We need to do it, since remained (stack) part of parameter has
2851 // stack alignment, and we need to "attach" "GPRs head" without gaps
2854 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2855 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2857 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2860 ArgRegsSaveSize = ArgRegsSize + Padding;
2862 // We don't need to extend regs save size for byval parameters if they
2863 // are passed via GPRs only.
2864 ArgRegsSaveSize = ArgRegsSize;
2867 // The remaining GPRs hold either the beginning of variable-argument
2868 // data, or the beginning of an aggregate passed by value (usually
2869 // byval). Either way, we allocate stack slots adjacent to the data
2870 // provided by our caller, and store the unallocated registers there.
2871 // If this is a variadic function, the va_list pointer will begin with
2872 // these values; otherwise, this reassembles a (byval) structure that
2873 // was split between registers and memory.
2874 // Return: The frame index registers were stored into.
2876 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2877 SDLoc dl, SDValue &Chain,
2878 const Value *OrigArg,
2879 unsigned InRegsParamRecordIdx,
2880 unsigned OffsetFromOrigArg,
2884 unsigned ByValStoreOffset,
2885 unsigned TotalArgRegsSaveSize) const {
2887 // Currently, two use-cases possible:
2888 // Case #1. Non-var-args function, and we meet first byval parameter.
2889 // Setup first unallocated register as first byval register;
2890 // eat all remained registers
2891 // (these two actions are performed by HandleByVal method).
2892 // Then, here, we initialize stack frame with
2893 // "store-reg" instructions.
2894 // Case #2. Var-args function, that doesn't contain byval parameters.
2895 // The same: eat all remained unallocated registers,
2896 // initialize stack frame.
2898 MachineFunction &MF = DAG.getMachineFunction();
2899 MachineFrameInfo *MFI = MF.getFrameInfo();
2900 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2902 unsigned RBegin, REnd;
2903 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2904 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2905 firstRegToSaveIndex = RBegin - ARM::R0;
2906 lastRegToSaveIndex = REnd - ARM::R0;
2908 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2909 (GPRArgRegs, array_lengthof(GPRArgRegs));
2910 lastRegToSaveIndex = 4;
2913 unsigned ArgRegsSize, ArgRegsSaveSize;
2914 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2915 ArgRegsSize, ArgRegsSaveSize);
2917 // Store any by-val regs to their spots on the stack so that they may be
2918 // loaded by deferencing the result of formal parameter pointer or va_next.
2919 // Note: once stack area for byval/varargs registers
2920 // was initialized, it can't be initialized again.
2921 if (ArgRegsSaveSize) {
2922 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2925 assert(AFI->getStoredByValParamsPadding() == 0 &&
2926 "The only parameter may be padded.");
2927 AFI->setStoredByValParamsPadding(Padding);
2930 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2933 (int64_t)TotalArgRegsSaveSize,
2935 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2937 MFI->CreateFixedObject(Padding,
2938 ArgOffset + ByValStoreOffset -
2939 (int64_t)ArgRegsSaveSize,
2943 SmallVector<SDValue, 4> MemOps;
2944 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2945 ++firstRegToSaveIndex, ++i) {
2946 const TargetRegisterClass *RC;
2947 if (AFI->isThumb1OnlyFunction())
2948 RC = &ARM::tGPRRegClass;
2950 RC = &ARM::GPRRegClass;
2952 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2953 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2955 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2956 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2958 MemOps.push_back(Store);
2959 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2960 DAG.getConstant(4, getPointerTy()));
2963 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2965 if (!MemOps.empty())
2966 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2970 // We cannot allocate a zero-byte object for the first variadic argument,
2971 // so just make up a size.
2974 // This will point to the next argument passed via stack.
2975 return MFI->CreateFixedObject(
2976 ArgSize, ArgOffset, !ForceMutable);
2980 // Setup stack frame, the va_list pointer will start from.
2982 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2983 SDLoc dl, SDValue &Chain,
2985 unsigned TotalArgRegsSaveSize,
2986 bool ForceMutable) const {
2987 MachineFunction &MF = DAG.getMachineFunction();
2988 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2990 // Try to store any remaining integer argument regs
2991 // to their spots on the stack so that they may be loaded by deferencing
2992 // the result of va_next.
2993 // If there is no regs to be stored, just point address after last
2994 // argument passed via stack.
2996 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2997 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2998 0, TotalArgRegsSaveSize);
3000 AFI->setVarArgsFrameIndex(FrameIndex);
3004 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3005 CallingConv::ID CallConv, bool isVarArg,
3006 const SmallVectorImpl<ISD::InputArg>
3008 SDLoc dl, SelectionDAG &DAG,
3009 SmallVectorImpl<SDValue> &InVals)
3011 MachineFunction &MF = DAG.getMachineFunction();
3012 MachineFrameInfo *MFI = MF.getFrameInfo();
3014 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3016 // Assign locations to all of the incoming arguments.
3017 SmallVector<CCValAssign, 16> ArgLocs;
3018 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3019 *DAG.getContext(), Prologue);
3020 CCInfo.AnalyzeFormalArguments(Ins,
3021 CCAssignFnForNode(CallConv, /* Return*/ false,
3024 SmallVector<SDValue, 16> ArgValues;
3025 int lastInsIndex = -1;
3027 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3028 unsigned CurArgIdx = 0;
3030 // Initially ArgRegsSaveSize is zero.
3031 // Then we increase this value each time we meet byval parameter.
3032 // We also increase this value in case of varargs function.
3033 AFI->setArgRegsSaveSize(0);
3035 unsigned ByValStoreOffset = 0;
3036 unsigned TotalArgRegsSaveSize = 0;
3037 unsigned ArgRegsSaveSizeMaxAlign = 4;
3039 // Calculate the amount of stack space that we need to allocate to store
3040 // byval and variadic arguments that are passed in registers.
3041 // We need to know this before we allocate the first byval or variadic
3042 // argument, as they will be allocated a stack slot below the CFA (Canonical
3043 // Frame Address, the stack pointer at entry to the function).
3044 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3045 CCValAssign &VA = ArgLocs[i];
3046 if (VA.isMemLoc()) {
3047 int index = VA.getValNo();
3048 if (index != lastInsIndex) {
3049 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3050 if (Flags.isByVal()) {
3051 unsigned ExtraArgRegsSize;
3052 unsigned ExtraArgRegsSaveSize;
3053 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3054 Flags.getByValSize(),
3055 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3057 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3058 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3059 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3060 CCInfo.nextInRegsParam();
3062 lastInsIndex = index;
3066 CCInfo.rewindByValRegsInfo();
3068 if (isVarArg && MFI->hasVAStart()) {
3069 unsigned ExtraArgRegsSize;
3070 unsigned ExtraArgRegsSaveSize;
3071 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3072 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3073 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3075 // If the arg regs save area contains N-byte aligned values, the
3076 // bottom of it must be at least N-byte aligned.
3077 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3078 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3080 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3081 CCValAssign &VA = ArgLocs[i];
3082 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3083 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3084 // Arguments stored in registers.
3085 if (VA.isRegLoc()) {
3086 EVT RegVT = VA.getLocVT();
3088 if (VA.needsCustom()) {
3089 // f64 and vector types are split up into multiple registers or
3090 // combinations of registers and stack slots.
3091 if (VA.getLocVT() == MVT::v2f64) {
3092 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3094 VA = ArgLocs[++i]; // skip ahead to next loc
3096 if (VA.isMemLoc()) {
3097 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3098 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3099 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3100 MachinePointerInfo::getFixedStack(FI),
3101 false, false, false, 0);
3103 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3106 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3107 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3108 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3109 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3110 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3112 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3115 const TargetRegisterClass *RC;
3117 if (RegVT == MVT::f32)
3118 RC = &ARM::SPRRegClass;
3119 else if (RegVT == MVT::f64)
3120 RC = &ARM::DPRRegClass;
3121 else if (RegVT == MVT::v2f64)
3122 RC = &ARM::QPRRegClass;
3123 else if (RegVT == MVT::i32)
3124 RC = AFI->isThumb1OnlyFunction() ?
3125 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3126 (const TargetRegisterClass*)&ARM::GPRRegClass;
3128 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3130 // Transform the arguments in physical registers into virtual ones.
3131 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3132 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3135 // If this is an 8 or 16-bit value, it is really passed promoted
3136 // to 32 bits. Insert an assert[sz]ext to capture this, then
3137 // truncate to the right size.
3138 switch (VA.getLocInfo()) {
3139 default: llvm_unreachable("Unknown loc info!");
3140 case CCValAssign::Full: break;
3141 case CCValAssign::BCvt:
3142 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3144 case CCValAssign::SExt:
3145 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3146 DAG.getValueType(VA.getValVT()));
3147 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3149 case CCValAssign::ZExt:
3150 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3151 DAG.getValueType(VA.getValVT()));
3152 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3156 InVals.push_back(ArgValue);
3158 } else { // VA.isRegLoc()
3161 assert(VA.isMemLoc());
3162 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3164 int index = ArgLocs[i].getValNo();
3166 // Some Ins[] entries become multiple ArgLoc[] entries.
3167 // Process them only once.
3168 if (index != lastInsIndex)
3170 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3171 // FIXME: For now, all byval parameter objects are marked mutable.
3172 // This can be changed with more analysis.
3173 // In case of tail call optimization mark all arguments mutable.
3174 // Since they could be overwritten by lowering of arguments in case of
3176 if (Flags.isByVal()) {
3177 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3179 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3180 int FrameIndex = StoreByValRegs(
3181 CCInfo, DAG, dl, Chain, CurOrigArg,
3183 Ins[VA.getValNo()].PartOffset,
3184 VA.getLocMemOffset(),
3185 Flags.getByValSize(),
3186 true /*force mutable frames*/,
3188 TotalArgRegsSaveSize);
3189 ByValStoreOffset += Flags.getByValSize();
3190 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3191 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3192 CCInfo.nextInRegsParam();
3194 unsigned FIOffset = VA.getLocMemOffset();
3195 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3198 // Create load nodes to retrieve arguments from the stack.
3199 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3200 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3201 MachinePointerInfo::getFixedStack(FI),
3202 false, false, false, 0));
3204 lastInsIndex = index;
3210 if (isVarArg && MFI->hasVAStart())
3211 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3212 CCInfo.getNextStackOffset(),
3213 TotalArgRegsSaveSize);
3215 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3220 /// isFloatingPointZero - Return true if this is +0.0.
3221 static bool isFloatingPointZero(SDValue Op) {
3222 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3223 return CFP->getValueAPF().isPosZero();
3224 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3225 // Maybe this has already been legalized into the constant pool?
3226 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3227 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3228 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3229 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3230 return CFP->getValueAPF().isPosZero();
3236 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3237 /// the given operands.
3239 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3240 SDValue &ARMcc, SelectionDAG &DAG,
3242 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3243 unsigned C = RHSC->getZExtValue();
3244 if (!isLegalICmpImmediate(C)) {
3245 // Constant does not fit, try adjusting it by one?
3250 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3251 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3252 RHS = DAG.getConstant(C-1, MVT::i32);
3257 if (C != 0 && isLegalICmpImmediate(C-1)) {
3258 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3259 RHS = DAG.getConstant(C-1, MVT::i32);
3264 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3265 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3266 RHS = DAG.getConstant(C+1, MVT::i32);
3271 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3272 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3273 RHS = DAG.getConstant(C+1, MVT::i32);
3280 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3281 ARMISD::NodeType CompareType;
3284 CompareType = ARMISD::CMP;
3289 CompareType = ARMISD::CMPZ;
3292 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3293 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3296 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3298 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3300 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3302 if (!isFloatingPointZero(RHS))
3303 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3305 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3306 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3309 /// duplicateCmp - Glue values can have only one use, so this function
3310 /// duplicates a comparison node.
3312 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3313 unsigned Opc = Cmp.getOpcode();
3315 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3316 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3318 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3319 Cmp = Cmp.getOperand(0);
3320 Opc = Cmp.getOpcode();
3321 if (Opc == ARMISD::CMPFP)
3322 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3324 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3325 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3327 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3330 std::pair<SDValue, SDValue>
3331 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3332 SDValue &ARMcc) const {
3333 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3335 SDValue Value, OverflowCmp;
3336 SDValue LHS = Op.getOperand(0);
3337 SDValue RHS = Op.getOperand(1);
3340 // FIXME: We are currently always generating CMPs because we don't support
3341 // generating CMN through the backend. This is not as good as the natural
3342 // CMP case because it causes a register dependency and cannot be folded
3345 switch (Op.getOpcode()) {
3347 llvm_unreachable("Unknown overflow instruction!");
3349 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3350 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3351 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3354 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3355 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3356 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3359 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3360 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3361 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3364 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3365 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3366 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3370 return std::make_pair(Value, OverflowCmp);
3375 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3376 // Let legalize expand this if it isn't a legal type yet.
3377 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3380 SDValue Value, OverflowCmp;
3382 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3383 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3384 // We use 0 and 1 as false and true values.
3385 SDValue TVal = DAG.getConstant(1, MVT::i32);
3386 SDValue FVal = DAG.getConstant(0, MVT::i32);
3387 EVT VT = Op.getValueType();
3389 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3390 ARMcc, CCR, OverflowCmp);
3392 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3393 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3397 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3398 SDValue Cond = Op.getOperand(0);
3399 SDValue SelectTrue = Op.getOperand(1);
3400 SDValue SelectFalse = Op.getOperand(2);
3402 unsigned Opc = Cond.getOpcode();
3404 if (Cond.getResNo() == 1 &&
3405 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3406 Opc == ISD::USUBO)) {
3407 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3410 SDValue Value, OverflowCmp;
3412 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3413 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3414 EVT VT = Op.getValueType();
3416 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3422 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3423 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3425 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3426 const ConstantSDNode *CMOVTrue =
3427 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3428 const ConstantSDNode *CMOVFalse =
3429 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3431 if (CMOVTrue && CMOVFalse) {
3432 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3433 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3437 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3439 False = SelectFalse;
3440 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3445 if (True.getNode() && False.getNode()) {
3446 EVT VT = Op.getValueType();
3447 SDValue ARMcc = Cond.getOperand(2);
3448 SDValue CCR = Cond.getOperand(3);
3449 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3450 assert(True.getValueType() == VT);
3451 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3456 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3457 // undefined bits before doing a full-word comparison with zero.
3458 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3459 DAG.getConstant(1, Cond.getValueType()));
3461 return DAG.getSelectCC(dl, Cond,
3462 DAG.getConstant(0, Cond.getValueType()),
3463 SelectTrue, SelectFalse, ISD::SETNE);
3466 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3467 if (CC == ISD::SETNE)
3469 return ISD::getSetCCInverse(CC, true);
3472 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3473 bool &swpCmpOps, bool &swpVselOps) {
3474 // Start by selecting the GE condition code for opcodes that return true for
3476 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3478 CondCode = ARMCC::GE;
3480 // and GT for opcodes that return false for 'equality'.
3481 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3483 CondCode = ARMCC::GT;
3485 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3486 // to swap the compare operands.
3487 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3491 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3492 // If we have an unordered opcode, we need to swap the operands to the VSEL
3493 // instruction (effectively negating the condition).
3495 // This also has the effect of swapping which one of 'less' or 'greater'
3496 // returns true, so we also swap the compare operands. It also switches
3497 // whether we return true for 'equality', so we compensate by picking the
3498 // opposite condition code to our original choice.
3499 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3500 CC == ISD::SETUGT) {
3501 swpCmpOps = !swpCmpOps;
3502 swpVselOps = !swpVselOps;
3503 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3506 // 'ordered' is 'anything but unordered', so use the VS condition code and
3507 // swap the VSEL operands.
3508 if (CC == ISD::SETO) {
3509 CondCode = ARMCC::VS;
3513 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3514 // code and swap the VSEL operands.
3515 if (CC == ISD::SETUNE) {
3516 CondCode = ARMCC::EQ;
3521 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3522 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3523 SDValue Cmp, SelectionDAG &DAG) const {
3524 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3525 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3526 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3527 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3528 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3530 SDValue TrueLow = TrueVal.getValue(0);
3531 SDValue TrueHigh = TrueVal.getValue(1);
3532 SDValue FalseLow = FalseVal.getValue(0);
3533 SDValue FalseHigh = FalseVal.getValue(1);
3535 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3537 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3538 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3540 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3542 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3547 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3548 EVT VT = Op.getValueType();
3549 SDValue LHS = Op.getOperand(0);
3550 SDValue RHS = Op.getOperand(1);
3551 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3552 SDValue TrueVal = Op.getOperand(2);
3553 SDValue FalseVal = Op.getOperand(3);
3556 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3557 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3560 // If softenSetCCOperands only returned one value, we should compare it to
3562 if (!RHS.getNode()) {
3563 RHS = DAG.getConstant(0, LHS.getValueType());
3568 if (LHS.getValueType() == MVT::i32) {
3569 // Try to generate VSEL on ARMv8.
3570 // The VSEL instruction can't use all the usual ARM condition
3571 // codes: it only has two bits to select the condition code, so it's
3572 // constrained to use only GE, GT, VS and EQ.
3574 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3575 // swap the operands of the previous compare instruction (effectively
3576 // inverting the compare condition, swapping 'less' and 'greater') and
3577 // sometimes need to swap the operands to the VSEL (which inverts the
3578 // condition in the sense of firing whenever the previous condition didn't)
3579 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3580 TrueVal.getValueType() == MVT::f64)) {
3581 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3582 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3583 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3584 CC = getInverseCCForVSEL(CC);
3585 std::swap(TrueVal, FalseVal);
3590 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3591 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3592 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3595 ARMCC::CondCodes CondCode, CondCode2;
3596 FPCCToARMCC(CC, CondCode, CondCode2);
3598 // Try to generate VSEL on ARMv8.
3599 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3600 TrueVal.getValueType() == MVT::f64)) {
3601 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3602 // same operands, as follows:
3603 // c = fcmp [ogt, olt, ugt, ult] a, b
3605 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3606 // handled differently than the original code sequence.
3607 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3609 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3610 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3611 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3612 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3615 bool swpCmpOps = false;
3616 bool swpVselOps = false;
3617 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3619 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3620 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3622 std::swap(LHS, RHS);
3624 std::swap(TrueVal, FalseVal);
3628 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3629 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3630 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3631 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3632 if (CondCode2 != ARMCC::AL) {
3633 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3634 // FIXME: Needs another CMP because flag can have but one use.
3635 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3636 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3641 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3642 /// to morph to an integer compare sequence.
3643 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3644 const ARMSubtarget *Subtarget) {
3645 SDNode *N = Op.getNode();
3646 if (!N->hasOneUse())
3647 // Otherwise it requires moving the value from fp to integer registers.
3649 if (!N->getNumValues())
3651 EVT VT = Op.getValueType();
3652 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3653 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3654 // vmrs are very slow, e.g. cortex-a8.
3657 if (isFloatingPointZero(Op)) {
3661 return ISD::isNormalLoad(N);
3664 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3665 if (isFloatingPointZero(Op))
3666 return DAG.getConstant(0, MVT::i32);
3668 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3669 return DAG.getLoad(MVT::i32, SDLoc(Op),
3670 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3671 Ld->isVolatile(), Ld->isNonTemporal(),
3672 Ld->isInvariant(), Ld->getAlignment());
3674 llvm_unreachable("Unknown VFP cmp argument!");
3677 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3678 SDValue &RetVal1, SDValue &RetVal2) {
3679 if (isFloatingPointZero(Op)) {
3680 RetVal1 = DAG.getConstant(0, MVT::i32);
3681 RetVal2 = DAG.getConstant(0, MVT::i32);
3685 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3686 SDValue Ptr = Ld->getBasePtr();
3687 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3688 Ld->getChain(), Ptr,
3689 Ld->getPointerInfo(),
3690 Ld->isVolatile(), Ld->isNonTemporal(),
3691 Ld->isInvariant(), Ld->getAlignment());
3693 EVT PtrType = Ptr.getValueType();
3694 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3695 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3696 PtrType, Ptr, DAG.getConstant(4, PtrType));
3697 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3698 Ld->getChain(), NewPtr,
3699 Ld->getPointerInfo().getWithOffset(4),
3700 Ld->isVolatile(), Ld->isNonTemporal(),
3701 Ld->isInvariant(), NewAlign);
3705 llvm_unreachable("Unknown VFP cmp argument!");
3708 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3709 /// f32 and even f64 comparisons to integer ones.
3711 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3712 SDValue Chain = Op.getOperand(0);
3713 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3714 SDValue LHS = Op.getOperand(2);
3715 SDValue RHS = Op.getOperand(3);
3716 SDValue Dest = Op.getOperand(4);
3719 bool LHSSeenZero = false;
3720 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3721 bool RHSSeenZero = false;
3722 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3723 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3724 // If unsafe fp math optimization is enabled and there are no other uses of
3725 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3726 // to an integer comparison.
3727 if (CC == ISD::SETOEQ)
3729 else if (CC == ISD::SETUNE)
3732 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3734 if (LHS.getValueType() == MVT::f32) {
3735 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3736 bitcastf32Toi32(LHS, DAG), Mask);
3737 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3738 bitcastf32Toi32(RHS, DAG), Mask);
3739 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3740 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3741 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3742 Chain, Dest, ARMcc, CCR, Cmp);
3747 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3748 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3749 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3750 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3751 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3752 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3753 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3754 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3755 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3761 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3762 SDValue Chain = Op.getOperand(0);
3763 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3764 SDValue LHS = Op.getOperand(2);
3765 SDValue RHS = Op.getOperand(3);
3766 SDValue Dest = Op.getOperand(4);
3769 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3770 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3773 // If softenSetCCOperands only returned one value, we should compare it to
3775 if (!RHS.getNode()) {
3776 RHS = DAG.getConstant(0, LHS.getValueType());
3781 if (LHS.getValueType() == MVT::i32) {
3783 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3784 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3785 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3786 Chain, Dest, ARMcc, CCR, Cmp);
3789 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3791 if (getTargetMachine().Options.UnsafeFPMath &&
3792 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3793 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3794 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3795 if (Result.getNode())
3799 ARMCC::CondCodes CondCode, CondCode2;
3800 FPCCToARMCC(CC, CondCode, CondCode2);
3802 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3803 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3804 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3805 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3806 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3807 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3808 if (CondCode2 != ARMCC::AL) {
3809 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3810 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3811 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3816 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3817 SDValue Chain = Op.getOperand(0);
3818 SDValue Table = Op.getOperand(1);
3819 SDValue Index = Op.getOperand(2);
3822 EVT PTy = getPointerTy();
3823 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3824 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3825 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3826 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3827 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3828 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3829 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3830 if (Subtarget->isThumb2()) {
3831 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3832 // which does another jump to the destination. This also makes it easier
3833 // to translate it to TBB / TBH later.
3834 // FIXME: This might not work if the function is extremely large.
3835 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3836 Addr, Op.getOperand(2), JTI, UId);
3838 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3839 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3840 MachinePointerInfo::getJumpTable(),
3841 false, false, false, 0);
3842 Chain = Addr.getValue(1);
3843 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3844 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3846 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3847 MachinePointerInfo::getJumpTable(),
3848 false, false, false, 0);
3849 Chain = Addr.getValue(1);
3850 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3854 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3855 EVT VT = Op.getValueType();
3858 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3859 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3861 return DAG.UnrollVectorOp(Op.getNode());
3864 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3865 "Invalid type for custom lowering!");
3866 if (VT != MVT::v4i16)
3867 return DAG.UnrollVectorOp(Op.getNode());
3869 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3870 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3873 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3874 EVT VT = Op.getValueType();
3876 return LowerVectorFP_TO_INT(Op, DAG);
3878 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3880 if (Op.getOpcode() == ISD::FP_TO_SINT)
3881 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3884 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3886 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3887 /*isSigned*/ false, SDLoc(Op)).first;
3893 switch (Op.getOpcode()) {
3894 default: llvm_unreachable("Invalid opcode!");
3895 case ISD::FP_TO_SINT:
3896 Opc = ARMISD::FTOSI;
3898 case ISD::FP_TO_UINT:
3899 Opc = ARMISD::FTOUI;
3902 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3903 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3906 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3907 EVT VT = Op.getValueType();
3910 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3911 if (VT.getVectorElementType() == MVT::f32)
3913 return DAG.UnrollVectorOp(Op.getNode());
3916 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3917 "Invalid type for custom lowering!");
3918 if (VT != MVT::v4f32)
3919 return DAG.UnrollVectorOp(Op.getNode());
3923 switch (Op.getOpcode()) {
3924 default: llvm_unreachable("Invalid opcode!");
3925 case ISD::SINT_TO_FP:
3926 CastOpc = ISD::SIGN_EXTEND;
3927 Opc = ISD::SINT_TO_FP;
3929 case ISD::UINT_TO_FP:
3930 CastOpc = ISD::ZERO_EXTEND;
3931 Opc = ISD::UINT_TO_FP;
3935 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3936 return DAG.getNode(Opc, dl, VT, Op);
3939 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3940 EVT VT = Op.getValueType();
3942 return LowerVectorINT_TO_FP(Op, DAG);
3944 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3946 if (Op.getOpcode() == ISD::SINT_TO_FP)
3947 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3950 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3952 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3953 /*isSigned*/ false, SDLoc(Op)).first;
3959 switch (Op.getOpcode()) {
3960 default: llvm_unreachable("Invalid opcode!");
3961 case ISD::SINT_TO_FP:
3962 Opc = ARMISD::SITOF;
3964 case ISD::UINT_TO_FP:
3965 Opc = ARMISD::UITOF;
3969 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3970 return DAG.getNode(Opc, dl, VT, Op);
3973 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3974 // Implement fcopysign with a fabs and a conditional fneg.
3975 SDValue Tmp0 = Op.getOperand(0);
3976 SDValue Tmp1 = Op.getOperand(1);
3978 EVT VT = Op.getValueType();
3979 EVT SrcVT = Tmp1.getValueType();
3980 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3981 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3982 bool UseNEON = !InGPR && Subtarget->hasNEON();
3985 // Use VBSL to copy the sign bit.
3986 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3987 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3988 DAG.getTargetConstant(EncodedVal, MVT::i32));
3989 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3991 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3992 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3993 DAG.getConstant(32, MVT::i32));
3994 else /*if (VT == MVT::f32)*/
3995 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3996 if (SrcVT == MVT::f32) {
3997 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3999 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4000 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4001 DAG.getConstant(32, MVT::i32));
4002 } else if (VT == MVT::f32)
4003 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4004 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4005 DAG.getConstant(32, MVT::i32));
4006 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4007 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4009 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4011 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4012 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4013 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4015 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4016 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4017 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4018 if (VT == MVT::f32) {
4019 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4020 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4021 DAG.getConstant(0, MVT::i32));
4023 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4029 // Bitcast operand 1 to i32.
4030 if (SrcVT == MVT::f64)
4031 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4033 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4035 // Or in the signbit with integer operations.
4036 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4037 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4038 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4039 if (VT == MVT::f32) {
4040 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4041 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4042 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4043 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4046 // f64: Or the high part with signbit and then combine two parts.
4047 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4049 SDValue Lo = Tmp0.getValue(0);
4050 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4051 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4052 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4055 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4056 MachineFunction &MF = DAG.getMachineFunction();
4057 MachineFrameInfo *MFI = MF.getFrameInfo();
4058 MFI->setReturnAddressIsTaken(true);
4060 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4063 EVT VT = Op.getValueType();
4065 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4067 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4068 SDValue Offset = DAG.getConstant(4, MVT::i32);
4069 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4070 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4071 MachinePointerInfo(), false, false, false, 0);
4074 // Return LR, which contains the return address. Mark it an implicit live-in.
4075 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4076 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4079 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4080 const ARMBaseRegisterInfo &ARI =
4081 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4082 MachineFunction &MF = DAG.getMachineFunction();
4083 MachineFrameInfo *MFI = MF.getFrameInfo();
4084 MFI->setFrameAddressIsTaken(true);
4086 EVT VT = Op.getValueType();
4087 SDLoc dl(Op); // FIXME probably not meaningful
4088 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4089 unsigned FrameReg = ARI.getFrameRegister(MF);
4090 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4092 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4093 MachinePointerInfo(),
4094 false, false, false, 0);
4098 // FIXME? Maybe this could be a TableGen attribute on some registers and
4099 // this table could be generated automatically from RegInfo.
4100 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4102 unsigned Reg = StringSwitch<unsigned>(RegName)
4103 .Case("sp", ARM::SP)
4107 report_fatal_error("Invalid register name global variable");
4110 /// ExpandBITCAST - If the target supports VFP, this function is called to
4111 /// expand a bit convert where either the source or destination type is i64 to
4112 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4113 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4114 /// vectors), since the legalizer won't know what to do with that.
4115 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4116 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4118 SDValue Op = N->getOperand(0);
4120 // This function is only supposed to be called for i64 types, either as the
4121 // source or destination of the bit convert.
4122 EVT SrcVT = Op.getValueType();
4123 EVT DstVT = N->getValueType(0);
4124 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4125 "ExpandBITCAST called for non-i64 type");
4127 // Turn i64->f64 into VMOVDRR.
4128 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4129 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4130 DAG.getConstant(0, MVT::i32));
4131 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4132 DAG.getConstant(1, MVT::i32));
4133 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4134 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4137 // Turn f64->i64 into VMOVRRD.
4138 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4140 if (TLI.isBigEndian() && SrcVT.isVector() &&
4141 SrcVT.getVectorNumElements() > 1)
4142 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4143 DAG.getVTList(MVT::i32, MVT::i32),
4144 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4146 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4147 DAG.getVTList(MVT::i32, MVT::i32), Op);
4148 // Merge the pieces into a single i64 value.
4149 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4155 /// getZeroVector - Returns a vector of specified type with all zero elements.
4156 /// Zero vectors are used to represent vector negation and in those cases
4157 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4158 /// not support i64 elements, so sometimes the zero vectors will need to be
4159 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4161 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4162 assert(VT.isVector() && "Expected a vector type");
4163 // The canonical modified immediate encoding of a zero vector is....0!
4164 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4165 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4166 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4167 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4170 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4171 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4172 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4173 SelectionDAG &DAG) const {
4174 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4175 EVT VT = Op.getValueType();
4176 unsigned VTBits = VT.getSizeInBits();
4178 SDValue ShOpLo = Op.getOperand(0);
4179 SDValue ShOpHi = Op.getOperand(1);
4180 SDValue ShAmt = Op.getOperand(2);
4182 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4184 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4186 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4187 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4188 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4189 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4190 DAG.getConstant(VTBits, MVT::i32));
4191 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4192 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4193 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4195 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4196 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4198 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4199 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4202 SDValue Ops[2] = { Lo, Hi };
4203 return DAG.getMergeValues(Ops, dl);
4206 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4207 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4208 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4209 SelectionDAG &DAG) const {
4210 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4211 EVT VT = Op.getValueType();
4212 unsigned VTBits = VT.getSizeInBits();
4214 SDValue ShOpLo = Op.getOperand(0);
4215 SDValue ShOpHi = Op.getOperand(1);
4216 SDValue ShAmt = Op.getOperand(2);
4219 assert(Op.getOpcode() == ISD::SHL_PARTS);
4220 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4221 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4222 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4223 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4224 DAG.getConstant(VTBits, MVT::i32));
4225 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4226 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4228 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4229 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4230 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4232 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4233 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4236 SDValue Ops[2] = { Lo, Hi };
4237 return DAG.getMergeValues(Ops, dl);
4240 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4241 SelectionDAG &DAG) const {
4242 // The rounding mode is in bits 23:22 of the FPSCR.
4243 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4244 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4245 // so that the shift + and get folded into a bitfield extract.
4247 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4248 DAG.getConstant(Intrinsic::arm_get_fpscr,
4250 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4251 DAG.getConstant(1U << 22, MVT::i32));
4252 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4253 DAG.getConstant(22, MVT::i32));
4254 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4255 DAG.getConstant(3, MVT::i32));
4258 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4259 const ARMSubtarget *ST) {
4260 EVT VT = N->getValueType(0);
4263 if (!ST->hasV6T2Ops())
4266 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4267 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4270 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4271 /// for each 16-bit element from operand, repeated. The basic idea is to
4272 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4274 /// Trace for v4i16:
4275 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4276 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4277 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4278 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4279 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4280 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4281 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4282 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4283 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4284 EVT VT = N->getValueType(0);
4287 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4288 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4289 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4290 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4291 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4292 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4295 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4296 /// bit-count for each 16-bit element from the operand. We need slightly
4297 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4298 /// 64/128-bit registers.
4300 /// Trace for v4i16:
4301 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4302 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4303 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4304 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4305 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4306 EVT VT = N->getValueType(0);
4309 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4310 if (VT.is64BitVector()) {
4311 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4312 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4313 DAG.getIntPtrConstant(0));
4315 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4316 BitCounts, DAG.getIntPtrConstant(0));
4317 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4321 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4322 /// bit-count for each 32-bit element from the operand. The idea here is
4323 /// to split the vector into 16-bit elements, leverage the 16-bit count
4324 /// routine, and then combine the results.
4326 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4327 /// input = [v0 v1 ] (vi: 32-bit elements)
4328 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4329 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4330 /// vrev: N0 = [k1 k0 k3 k2 ]
4332 /// N1 =+[k1 k0 k3 k2 ]
4334 /// N2 =+[k1 k3 k0 k2 ]
4336 /// Extended =+[k1 k3 k0 k2 ]
4338 /// Extracted=+[k1 k3 ]
4340 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4341 EVT VT = N->getValueType(0);
4344 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4346 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4347 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4348 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4349 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4350 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4352 if (VT.is64BitVector()) {
4353 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4354 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4355 DAG.getIntPtrConstant(0));
4357 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4358 DAG.getIntPtrConstant(0));
4359 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4363 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4364 const ARMSubtarget *ST) {
4365 EVT VT = N->getValueType(0);
4367 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4368 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4369 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4370 "Unexpected type for custom ctpop lowering");
4372 if (VT.getVectorElementType() == MVT::i32)
4373 return lowerCTPOP32BitElements(N, DAG);
4375 return lowerCTPOP16BitElements(N, DAG);
4378 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4379 const ARMSubtarget *ST) {
4380 EVT VT = N->getValueType(0);
4386 // Lower vector shifts on NEON to use VSHL.
4387 assert(ST->hasNEON() && "unexpected vector shift");
4389 // Left shifts translate directly to the vshiftu intrinsic.
4390 if (N->getOpcode() == ISD::SHL)
4391 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4392 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4393 N->getOperand(0), N->getOperand(1));
4395 assert((N->getOpcode() == ISD::SRA ||
4396 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4398 // NEON uses the same intrinsics for both left and right shifts. For
4399 // right shifts, the shift amounts are negative, so negate the vector of
4401 EVT ShiftVT = N->getOperand(1).getValueType();
4402 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4403 getZeroVector(ShiftVT, DAG, dl),
4405 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4406 Intrinsic::arm_neon_vshifts :
4407 Intrinsic::arm_neon_vshiftu);
4408 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4409 DAG.getConstant(vshiftInt, MVT::i32),
4410 N->getOperand(0), NegatedCount);
4413 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4414 const ARMSubtarget *ST) {
4415 EVT VT = N->getValueType(0);
4418 // We can get here for a node like i32 = ISD::SHL i32, i64
4422 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4423 "Unknown shift to lower!");
4425 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4426 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4427 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4430 // If we are in thumb mode, we don't have RRX.
4431 if (ST->isThumb1Only()) return SDValue();
4433 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4434 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4435 DAG.getConstant(0, MVT::i32));
4436 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4437 DAG.getConstant(1, MVT::i32));
4439 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4440 // captures the result into a carry flag.
4441 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4442 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4444 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4445 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4447 // Merge the pieces into a single i64 value.
4448 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4451 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4452 SDValue TmpOp0, TmpOp1;
4453 bool Invert = false;
4457 SDValue Op0 = Op.getOperand(0);
4458 SDValue Op1 = Op.getOperand(1);
4459 SDValue CC = Op.getOperand(2);
4460 EVT VT = Op.getValueType();
4461 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4464 if (Op1.getValueType().isFloatingPoint()) {
4465 switch (SetCCOpcode) {
4466 default: llvm_unreachable("Illegal FP comparison");
4468 case ISD::SETNE: Invert = true; // Fallthrough
4470 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4472 case ISD::SETLT: Swap = true; // Fallthrough
4474 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4476 case ISD::SETLE: Swap = true; // Fallthrough
4478 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4479 case ISD::SETUGE: Swap = true; // Fallthrough
4480 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4481 case ISD::SETUGT: Swap = true; // Fallthrough
4482 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4483 case ISD::SETUEQ: Invert = true; // Fallthrough
4485 // Expand this to (OLT | OGT).
4489 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4490 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4492 case ISD::SETUO: Invert = true; // Fallthrough
4494 // Expand this to (OLT | OGE).
4498 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4499 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4503 // Integer comparisons.
4504 switch (SetCCOpcode) {
4505 default: llvm_unreachable("Illegal integer comparison");
4506 case ISD::SETNE: Invert = true;
4507 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4508 case ISD::SETLT: Swap = true;
4509 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4510 case ISD::SETLE: Swap = true;
4511 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4512 case ISD::SETULT: Swap = true;
4513 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4514 case ISD::SETULE: Swap = true;
4515 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4518 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4519 if (Opc == ARMISD::VCEQ) {
4522 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4524 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4527 // Ignore bitconvert.
4528 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4529 AndOp = AndOp.getOperand(0);
4531 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4533 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4534 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4541 std::swap(Op0, Op1);
4543 // If one of the operands is a constant vector zero, attempt to fold the
4544 // comparison to a specialized compare-against-zero form.
4546 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4548 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4549 if (Opc == ARMISD::VCGE)
4550 Opc = ARMISD::VCLEZ;
4551 else if (Opc == ARMISD::VCGT)
4552 Opc = ARMISD::VCLTZ;
4557 if (SingleOp.getNode()) {
4560 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4562 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4564 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4566 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4568 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4570 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4573 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4577 Result = DAG.getNOT(dl, Result, VT);
4582 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4583 /// valid vector constant for a NEON instruction with a "modified immediate"
4584 /// operand (e.g., VMOV). If so, return the encoded value.
4585 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4586 unsigned SplatBitSize, SelectionDAG &DAG,
4587 EVT &VT, bool is128Bits, NEONModImmType type) {
4588 unsigned OpCmode, Imm;
4590 // SplatBitSize is set to the smallest size that splats the vector, so a
4591 // zero vector will always have SplatBitSize == 8. However, NEON modified
4592 // immediate instructions others than VMOV do not support the 8-bit encoding
4593 // of a zero vector, and the default encoding of zero is supposed to be the
4598 switch (SplatBitSize) {
4600 if (type != VMOVModImm)
4602 // Any 1-byte value is OK. Op=0, Cmode=1110.
4603 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4606 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4610 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4611 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4612 if ((SplatBits & ~0xff) == 0) {
4613 // Value = 0x00nn: Op=x, Cmode=100x.
4618 if ((SplatBits & ~0xff00) == 0) {
4619 // Value = 0xnn00: Op=x, Cmode=101x.
4621 Imm = SplatBits >> 8;
4627 // NEON's 32-bit VMOV supports splat values where:
4628 // * only one byte is nonzero, or
4629 // * the least significant byte is 0xff and the second byte is nonzero, or
4630 // * the least significant 2 bytes are 0xff and the third is nonzero.
4631 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4632 if ((SplatBits & ~0xff) == 0) {
4633 // Value = 0x000000nn: Op=x, Cmode=000x.
4638 if ((SplatBits & ~0xff00) == 0) {
4639 // Value = 0x0000nn00: Op=x, Cmode=001x.
4641 Imm = SplatBits >> 8;
4644 if ((SplatBits & ~0xff0000) == 0) {
4645 // Value = 0x00nn0000: Op=x, Cmode=010x.
4647 Imm = SplatBits >> 16;
4650 if ((SplatBits & ~0xff000000) == 0) {
4651 // Value = 0xnn000000: Op=x, Cmode=011x.
4653 Imm = SplatBits >> 24;
4657 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4658 if (type == OtherModImm) return SDValue();
4660 if ((SplatBits & ~0xffff) == 0 &&
4661 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4662 // Value = 0x0000nnff: Op=x, Cmode=1100.
4664 Imm = SplatBits >> 8;
4668 if ((SplatBits & ~0xffffff) == 0 &&
4669 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4670 // Value = 0x00nnffff: Op=x, Cmode=1101.
4672 Imm = SplatBits >> 16;
4676 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4677 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4678 // VMOV.I32. A (very) minor optimization would be to replicate the value
4679 // and fall through here to test for a valid 64-bit splat. But, then the
4680 // caller would also need to check and handle the change in size.
4684 if (type != VMOVModImm)
4686 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4687 uint64_t BitMask = 0xff;
4689 unsigned ImmMask = 1;
4691 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4692 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4695 } else if ((SplatBits & BitMask) != 0) {
4702 if (DAG.getTargetLoweringInfo().isBigEndian())
4703 // swap higher and lower 32 bit word
4704 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4706 // Op=1, Cmode=1110.
4708 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4713 llvm_unreachable("unexpected size for isNEONModifiedImm");
4716 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4717 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4720 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4721 const ARMSubtarget *ST) const {
4725 bool IsDouble = Op.getValueType() == MVT::f64;
4726 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4728 // Use the default (constant pool) lowering for double constants when we have
4730 if (IsDouble && Subtarget->isFPOnlySP())
4733 // Try splatting with a VMOV.f32...
4734 APFloat FPVal = CFP->getValueAPF();
4735 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4738 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4739 // We have code in place to select a valid ConstantFP already, no need to
4744 // It's a float and we are trying to use NEON operations where
4745 // possible. Lower it to a splat followed by an extract.
4747 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4748 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4750 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4751 DAG.getConstant(0, MVT::i32));
4754 // The rest of our options are NEON only, make sure that's allowed before
4756 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4760 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4762 // It wouldn't really be worth bothering for doubles except for one very
4763 // important value, which does happen to match: 0.0. So make sure we don't do
4765 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4768 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4769 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4771 if (NewVal != SDValue()) {
4773 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4776 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4778 // It's a float: cast and extract a vector element.
4779 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4781 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4782 DAG.getConstant(0, MVT::i32));
4785 // Finally, try a VMVN.i32
4786 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4788 if (NewVal != SDValue()) {
4790 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4793 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4795 // It's a float: cast and extract a vector element.
4796 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4798 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4799 DAG.getConstant(0, MVT::i32));
4805 // check if an VEXT instruction can handle the shuffle mask when the
4806 // vector sources of the shuffle are the same.
4807 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4808 unsigned NumElts = VT.getVectorNumElements();
4810 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4816 // If this is a VEXT shuffle, the immediate value is the index of the first
4817 // element. The other shuffle indices must be the successive elements after
4819 unsigned ExpectedElt = Imm;
4820 for (unsigned i = 1; i < NumElts; ++i) {
4821 // Increment the expected index. If it wraps around, just follow it
4822 // back to index zero and keep going.
4824 if (ExpectedElt == NumElts)
4827 if (M[i] < 0) continue; // ignore UNDEF indices
4828 if (ExpectedElt != static_cast<unsigned>(M[i]))
4836 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4837 bool &ReverseVEXT, unsigned &Imm) {
4838 unsigned NumElts = VT.getVectorNumElements();
4839 ReverseVEXT = false;
4841 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4847 // If this is a VEXT shuffle, the immediate value is the index of the first
4848 // element. The other shuffle indices must be the successive elements after
4850 unsigned ExpectedElt = Imm;
4851 for (unsigned i = 1; i < NumElts; ++i) {
4852 // Increment the expected index. If it wraps around, it may still be
4853 // a VEXT but the source vectors must be swapped.
4855 if (ExpectedElt == NumElts * 2) {
4860 if (M[i] < 0) continue; // ignore UNDEF indices
4861 if (ExpectedElt != static_cast<unsigned>(M[i]))
4865 // Adjust the index value if the source operands will be swapped.
4872 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4873 /// instruction with the specified blocksize. (The order of the elements
4874 /// within each block of the vector is reversed.)
4875 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4876 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4877 "Only possible block sizes for VREV are: 16, 32, 64");
4879 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4883 unsigned NumElts = VT.getVectorNumElements();
4884 unsigned BlockElts = M[0] + 1;
4885 // If the first shuffle index is UNDEF, be optimistic.
4887 BlockElts = BlockSize / EltSz;
4889 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4892 for (unsigned i = 0; i < NumElts; ++i) {
4893 if (M[i] < 0) continue; // ignore UNDEF indices
4894 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4901 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4902 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4903 // range, then 0 is placed into the resulting vector. So pretty much any mask
4904 // of 8 elements can work here.
4905 return VT == MVT::v8i8 && M.size() == 8;
4908 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4909 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4913 unsigned NumElts = VT.getVectorNumElements();
4914 WhichResult = (M[0] == 0 ? 0 : 1);
4915 for (unsigned i = 0; i < NumElts; i += 2) {
4916 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4917 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4923 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4924 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4925 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4926 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4927 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4931 unsigned NumElts = VT.getVectorNumElements();
4932 WhichResult = (M[0] == 0 ? 0 : 1);
4933 for (unsigned i = 0; i < NumElts; i += 2) {
4934 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4935 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4941 static bool isVUZPMask(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) {
4949 if (M[i] < 0) continue; // ignore UNDEF indices
4950 if ((unsigned) M[i] != 2 * i + WhichResult)
4954 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4955 if (VT.is64BitVector() && EltSz == 32)
4961 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4962 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4963 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4964 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4965 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4969 unsigned Half = VT.getVectorNumElements() / 2;
4970 WhichResult = (M[0] == 0 ? 0 : 1);
4971 for (unsigned j = 0; j != 2; ++j) {
4972 unsigned Idx = WhichResult;
4973 for (unsigned i = 0; i != Half; ++i) {
4974 int MIdx = M[i + j * Half];
4975 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4981 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4982 if (VT.is64BitVector() && EltSz == 32)
4988 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4989 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4993 unsigned NumElts = VT.getVectorNumElements();
4994 WhichResult = (M[0] == 0 ? 0 : 1);
4995 unsigned Idx = WhichResult * NumElts / 2;
4996 for (unsigned i = 0; i != NumElts; i += 2) {
4997 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4998 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5003 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5004 if (VT.is64BitVector() && EltSz == 32)
5010 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5011 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5012 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5013 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5014 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5018 unsigned NumElts = VT.getVectorNumElements();
5019 WhichResult = (M[0] == 0 ? 0 : 1);
5020 unsigned Idx = WhichResult * NumElts / 2;
5021 for (unsigned i = 0; i != NumElts; i += 2) {
5022 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5023 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5028 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5029 if (VT.is64BitVector() && EltSz == 32)
5035 /// \return true if this is a reverse operation on an vector.
5036 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5037 unsigned NumElts = VT.getVectorNumElements();
5038 // Make sure the mask has the right size.
5039 if (NumElts != M.size())
5042 // Look for <15, ..., 3, -1, 1, 0>.
5043 for (unsigned i = 0; i != NumElts; ++i)
5044 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5050 // If N is an integer constant that can be moved into a register in one
5051 // instruction, return an SDValue of such a constant (will become a MOV
5052 // instruction). Otherwise return null.
5053 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5054 const ARMSubtarget *ST, SDLoc dl) {
5056 if (!isa<ConstantSDNode>(N))
5058 Val = cast<ConstantSDNode>(N)->getZExtValue();
5060 if (ST->isThumb1Only()) {
5061 if (Val <= 255 || ~Val <= 255)
5062 return DAG.getConstant(Val, MVT::i32);
5064 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5065 return DAG.getConstant(Val, MVT::i32);
5070 // If this is a case we can't handle, return null and let the default
5071 // expansion code take care of it.
5072 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5073 const ARMSubtarget *ST) const {
5074 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5076 EVT VT = Op.getValueType();
5078 APInt SplatBits, SplatUndef;
5079 unsigned SplatBitSize;
5081 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5082 if (SplatBitSize <= 64) {
5083 // Check if an immediate VMOV works.
5085 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5086 SplatUndef.getZExtValue(), SplatBitSize,
5087 DAG, VmovVT, VT.is128BitVector(),
5089 if (Val.getNode()) {
5090 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5091 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5094 // Try an immediate VMVN.
5095 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5096 Val = isNEONModifiedImm(NegatedImm,
5097 SplatUndef.getZExtValue(), SplatBitSize,
5098 DAG, VmovVT, VT.is128BitVector(),
5100 if (Val.getNode()) {
5101 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5102 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5105 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5106 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5107 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5109 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5110 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5116 // Scan through the operands to see if only one value is used.
5118 // As an optimisation, even if more than one value is used it may be more
5119 // profitable to splat with one value then change some lanes.
5121 // Heuristically we decide to do this if the vector has a "dominant" value,
5122 // defined as splatted to more than half of the lanes.
5123 unsigned NumElts = VT.getVectorNumElements();
5124 bool isOnlyLowElement = true;
5125 bool usesOnlyOneValue = true;
5126 bool hasDominantValue = false;
5127 bool isConstant = true;
5129 // Map of the number of times a particular SDValue appears in the
5131 DenseMap<SDValue, unsigned> ValueCounts;
5133 for (unsigned i = 0; i < NumElts; ++i) {
5134 SDValue V = Op.getOperand(i);
5135 if (V.getOpcode() == ISD::UNDEF)
5138 isOnlyLowElement = false;
5139 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5142 ValueCounts.insert(std::make_pair(V, 0));
5143 unsigned &Count = ValueCounts[V];
5145 // Is this value dominant? (takes up more than half of the lanes)
5146 if (++Count > (NumElts / 2)) {
5147 hasDominantValue = true;
5151 if (ValueCounts.size() != 1)
5152 usesOnlyOneValue = false;
5153 if (!Value.getNode() && ValueCounts.size() > 0)
5154 Value = ValueCounts.begin()->first;
5156 if (ValueCounts.size() == 0)
5157 return DAG.getUNDEF(VT);
5159 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5160 // Keep going if we are hitting this case.
5161 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5162 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5164 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5166 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5167 // i32 and try again.
5168 if (hasDominantValue && EltSize <= 32) {
5172 // If we are VDUPing a value that comes directly from a vector, that will
5173 // cause an unnecessary move to and from a GPR, where instead we could
5174 // just use VDUPLANE. We can only do this if the lane being extracted
5175 // is at a constant index, as the VDUP from lane instructions only have
5176 // constant-index forms.
5177 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5178 isa<ConstantSDNode>(Value->getOperand(1))) {
5179 // We need to create a new undef vector to use for the VDUPLANE if the
5180 // size of the vector from which we get the value is different than the
5181 // size of the vector that we need to create. We will insert the element
5182 // such that the register coalescer will remove unnecessary copies.
5183 if (VT != Value->getOperand(0).getValueType()) {
5184 ConstantSDNode *constIndex;
5185 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5186 assert(constIndex && "The index is not a constant!");
5187 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5188 VT.getVectorNumElements();
5189 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5190 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5191 Value, DAG.getConstant(index, MVT::i32)),
5192 DAG.getConstant(index, MVT::i32));
5194 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5195 Value->getOperand(0), Value->getOperand(1));
5197 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5199 if (!usesOnlyOneValue) {
5200 // The dominant value was splatted as 'N', but we now have to insert
5201 // all differing elements.
5202 for (unsigned I = 0; I < NumElts; ++I) {
5203 if (Op.getOperand(I) == Value)
5205 SmallVector<SDValue, 3> Ops;
5207 Ops.push_back(Op.getOperand(I));
5208 Ops.push_back(DAG.getConstant(I, MVT::i32));
5209 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5214 if (VT.getVectorElementType().isFloatingPoint()) {
5215 SmallVector<SDValue, 8> Ops;
5216 for (unsigned i = 0; i < NumElts; ++i)
5217 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5219 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5220 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5221 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5223 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5225 if (usesOnlyOneValue) {
5226 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5227 if (isConstant && Val.getNode())
5228 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5232 // If all elements are constants and the case above didn't get hit, fall back
5233 // to the default expansion, which will generate a load from the constant
5238 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5240 SDValue shuffle = ReconstructShuffle(Op, DAG);
5241 if (shuffle != SDValue())
5245 // Vectors with 32- or 64-bit elements can be built by directly assigning
5246 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5247 // will be legalized.
5248 if (EltSize >= 32) {
5249 // Do the expansion with floating-point types, since that is what the VFP
5250 // registers are defined to use, and since i64 is not legal.
5251 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5252 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5253 SmallVector<SDValue, 8> Ops;
5254 for (unsigned i = 0; i < NumElts; ++i)
5255 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5256 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5257 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5260 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5261 // know the default expansion would otherwise fall back on something even
5262 // worse. For a vector with one or two non-undef values, that's
5263 // scalar_to_vector for the elements followed by a shuffle (provided the
5264 // shuffle is valid for the target) and materialization element by element
5265 // on the stack followed by a load for everything else.
5266 if (!isConstant && !usesOnlyOneValue) {
5267 SDValue Vec = DAG.getUNDEF(VT);
5268 for (unsigned i = 0 ; i < NumElts; ++i) {
5269 SDValue V = Op.getOperand(i);
5270 if (V.getOpcode() == ISD::UNDEF)
5272 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5273 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5281 // Gather data to see if the operation can be modelled as a
5282 // shuffle in combination with VEXTs.
5283 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5284 SelectionDAG &DAG) const {
5286 EVT VT = Op.getValueType();
5287 unsigned NumElts = VT.getVectorNumElements();
5289 SmallVector<SDValue, 2> SourceVecs;
5290 SmallVector<unsigned, 2> MinElts;
5291 SmallVector<unsigned, 2> MaxElts;
5293 for (unsigned i = 0; i < NumElts; ++i) {
5294 SDValue V = Op.getOperand(i);
5295 if (V.getOpcode() == ISD::UNDEF)
5297 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5298 // A shuffle can only come from building a vector from various
5299 // elements of other vectors.
5301 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5302 VT.getVectorElementType()) {
5303 // This code doesn't know how to handle shuffles where the vector
5304 // element types do not match (this happens because type legalization
5305 // promotes the return type of EXTRACT_VECTOR_ELT).
5306 // FIXME: It might be appropriate to extend this code to handle
5307 // mismatched types.
5311 // Record this extraction against the appropriate vector if possible...
5312 SDValue SourceVec = V.getOperand(0);
5313 // If the element number isn't a constant, we can't effectively
5314 // analyze what's going on.
5315 if (!isa<ConstantSDNode>(V.getOperand(1)))
5317 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5318 bool FoundSource = false;
5319 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5320 if (SourceVecs[j] == SourceVec) {
5321 if (MinElts[j] > EltNo)
5323 if (MaxElts[j] < EltNo)
5330 // Or record a new source if not...
5332 SourceVecs.push_back(SourceVec);
5333 MinElts.push_back(EltNo);
5334 MaxElts.push_back(EltNo);
5338 // Currently only do something sane when at most two source vectors
5340 if (SourceVecs.size() > 2)
5343 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5344 int VEXTOffsets[2] = {0, 0};
5346 // This loop extracts the usage patterns of the source vectors
5347 // and prepares appropriate SDValues for a shuffle if possible.
5348 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5349 if (SourceVecs[i].getValueType() == VT) {
5350 // No VEXT necessary
5351 ShuffleSrcs[i] = SourceVecs[i];
5354 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5355 // It probably isn't worth padding out a smaller vector just to
5356 // break it down again in a shuffle.
5360 // Since only 64-bit and 128-bit vectors are legal on ARM and
5361 // we've eliminated the other cases...
5362 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5363 "unexpected vector sizes in ReconstructShuffle");
5365 if (MaxElts[i] - MinElts[i] >= NumElts) {
5366 // Span too large for a VEXT to cope
5370 if (MinElts[i] >= NumElts) {
5371 // The extraction can just take the second half
5372 VEXTOffsets[i] = NumElts;
5373 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5375 DAG.getIntPtrConstant(NumElts));
5376 } else if (MaxElts[i] < NumElts) {
5377 // The extraction can just take the first half
5379 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5381 DAG.getIntPtrConstant(0));
5383 // An actual VEXT is needed
5384 VEXTOffsets[i] = MinElts[i];
5385 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5387 DAG.getIntPtrConstant(0));
5388 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5390 DAG.getIntPtrConstant(NumElts));
5391 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5392 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5396 SmallVector<int, 8> Mask;
5398 for (unsigned i = 0; i < NumElts; ++i) {
5399 SDValue Entry = Op.getOperand(i);
5400 if (Entry.getOpcode() == ISD::UNDEF) {
5405 SDValue ExtractVec = Entry.getOperand(0);
5406 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5407 .getOperand(1))->getSExtValue();
5408 if (ExtractVec == SourceVecs[0]) {
5409 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5411 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5415 // Final check before we try to produce nonsense...
5416 if (isShuffleMaskLegal(Mask, VT))
5417 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5423 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5424 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5425 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5426 /// are assumed to be legal.
5428 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5430 if (VT.getVectorNumElements() == 4 &&
5431 (VT.is128BitVector() || VT.is64BitVector())) {
5432 unsigned PFIndexes[4];
5433 for (unsigned i = 0; i != 4; ++i) {
5437 PFIndexes[i] = M[i];
5440 // Compute the index in the perfect shuffle table.
5441 unsigned PFTableIndex =
5442 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5443 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5444 unsigned Cost = (PFEntry >> 30);
5451 unsigned Imm, WhichResult;
5453 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5454 return (EltSize >= 32 ||
5455 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5456 isVREVMask(M, VT, 64) ||
5457 isVREVMask(M, VT, 32) ||
5458 isVREVMask(M, VT, 16) ||
5459 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5460 isVTBLMask(M, VT) ||
5461 isVTRNMask(M, VT, WhichResult) ||
5462 isVUZPMask(M, VT, WhichResult) ||
5463 isVZIPMask(M, VT, WhichResult) ||
5464 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5465 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5466 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5467 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5470 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5471 /// the specified operations to build the shuffle.
5472 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5473 SDValue RHS, SelectionDAG &DAG,
5475 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5476 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5477 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5480 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5489 OP_VUZPL, // VUZP, left result
5490 OP_VUZPR, // VUZP, right result
5491 OP_VZIPL, // VZIP, left result
5492 OP_VZIPR, // VZIP, right result
5493 OP_VTRNL, // VTRN, left result
5494 OP_VTRNR // VTRN, right result
5497 if (OpNum == OP_COPY) {
5498 if (LHSID == (1*9+2)*9+3) return LHS;
5499 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5503 SDValue OpLHS, OpRHS;
5504 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5505 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5506 EVT VT = OpLHS.getValueType();
5509 default: llvm_unreachable("Unknown shuffle opcode!");
5511 // VREV divides the vector in half and swaps within the half.
5512 if (VT.getVectorElementType() == MVT::i32 ||
5513 VT.getVectorElementType() == MVT::f32)
5514 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5515 // vrev <4 x i16> -> VREV32
5516 if (VT.getVectorElementType() == MVT::i16)
5517 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5518 // vrev <4 x i8> -> VREV16
5519 assert(VT.getVectorElementType() == MVT::i8);
5520 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5525 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5526 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5530 return DAG.getNode(ARMISD::VEXT, dl, VT,
5532 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5535 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5536 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5539 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5540 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5543 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5544 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5548 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5549 ArrayRef<int> ShuffleMask,
5550 SelectionDAG &DAG) {
5551 // Check to see if we can use the VTBL instruction.
5552 SDValue V1 = Op.getOperand(0);
5553 SDValue V2 = Op.getOperand(1);
5556 SmallVector<SDValue, 8> VTBLMask;
5557 for (ArrayRef<int>::iterator
5558 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5559 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5561 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5562 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5563 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5565 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5566 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5569 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5570 SelectionDAG &DAG) {
5572 SDValue OpLHS = Op.getOperand(0);
5573 EVT VT = OpLHS.getValueType();
5575 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5576 "Expect an v8i16/v16i8 type");
5577 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5578 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5579 // extract the first 8 bytes into the top double word and the last 8 bytes
5580 // into the bottom double word. The v8i16 case is similar.
5581 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5582 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5583 DAG.getConstant(ExtractNum, MVT::i32));
5586 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5587 SDValue V1 = Op.getOperand(0);
5588 SDValue V2 = Op.getOperand(1);
5590 EVT VT = Op.getValueType();
5591 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5593 // Convert shuffles that are directly supported on NEON to target-specific
5594 // DAG nodes, instead of keeping them as shuffles and matching them again
5595 // during code selection. This is more efficient and avoids the possibility
5596 // of inconsistencies between legalization and selection.
5597 // FIXME: floating-point vectors should be canonicalized to integer vectors
5598 // of the same time so that they get CSEd properly.
5599 ArrayRef<int> ShuffleMask = SVN->getMask();
5601 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5602 if (EltSize <= 32) {
5603 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5604 int Lane = SVN->getSplatIndex();
5605 // If this is undef splat, generate it via "just" vdup, if possible.
5606 if (Lane == -1) Lane = 0;
5608 // Test if V1 is a SCALAR_TO_VECTOR.
5609 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5610 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5612 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5613 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5615 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5616 !isa<ConstantSDNode>(V1.getOperand(0))) {
5617 bool IsScalarToVector = true;
5618 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5619 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5620 IsScalarToVector = false;
5623 if (IsScalarToVector)
5624 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5626 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5627 DAG.getConstant(Lane, MVT::i32));
5632 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5635 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5636 DAG.getConstant(Imm, MVT::i32));
5639 if (isVREVMask(ShuffleMask, VT, 64))
5640 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5641 if (isVREVMask(ShuffleMask, VT, 32))
5642 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5643 if (isVREVMask(ShuffleMask, VT, 16))
5644 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5646 if (V2->getOpcode() == ISD::UNDEF &&
5647 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5648 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5649 DAG.getConstant(Imm, MVT::i32));
5652 // Check for Neon shuffles that modify both input vectors in place.
5653 // If both results are used, i.e., if there are two shuffles with the same
5654 // source operands and with masks corresponding to both results of one of
5655 // these operations, DAG memoization will ensure that a single node is
5656 // used for both shuffles.
5657 unsigned WhichResult;
5658 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5659 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5660 V1, V2).getValue(WhichResult);
5661 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5662 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5663 V1, V2).getValue(WhichResult);
5664 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5665 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5666 V1, V2).getValue(WhichResult);
5668 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5669 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5670 V1, V1).getValue(WhichResult);
5671 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5672 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5673 V1, V1).getValue(WhichResult);
5674 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5675 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5676 V1, V1).getValue(WhichResult);
5679 // If the shuffle is not directly supported and it has 4 elements, use
5680 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5681 unsigned NumElts = VT.getVectorNumElements();
5683 unsigned PFIndexes[4];
5684 for (unsigned i = 0; i != 4; ++i) {
5685 if (ShuffleMask[i] < 0)
5688 PFIndexes[i] = ShuffleMask[i];
5691 // Compute the index in the perfect shuffle table.
5692 unsigned PFTableIndex =
5693 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5694 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5695 unsigned Cost = (PFEntry >> 30);
5698 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5701 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5702 if (EltSize >= 32) {
5703 // Do the expansion with floating-point types, since that is what the VFP
5704 // registers are defined to use, and since i64 is not legal.
5705 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5706 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5707 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5708 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5709 SmallVector<SDValue, 8> Ops;
5710 for (unsigned i = 0; i < NumElts; ++i) {
5711 if (ShuffleMask[i] < 0)
5712 Ops.push_back(DAG.getUNDEF(EltVT));
5714 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5715 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5716 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5719 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5720 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5723 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5724 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5726 if (VT == MVT::v8i8) {
5727 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5728 if (NewOp.getNode())
5735 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5736 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5737 SDValue Lane = Op.getOperand(2);
5738 if (!isa<ConstantSDNode>(Lane))
5744 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5745 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5746 SDValue Lane = Op.getOperand(1);
5747 if (!isa<ConstantSDNode>(Lane))
5750 SDValue Vec = Op.getOperand(0);
5751 if (Op.getValueType() == MVT::i32 &&
5752 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5754 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5760 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5761 // The only time a CONCAT_VECTORS operation can have legal types is when
5762 // two 64-bit vectors are concatenated to a 128-bit vector.
5763 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5764 "unexpected CONCAT_VECTORS");
5766 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5767 SDValue Op0 = Op.getOperand(0);
5768 SDValue Op1 = Op.getOperand(1);
5769 if (Op0.getOpcode() != ISD::UNDEF)
5770 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5771 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5772 DAG.getIntPtrConstant(0));
5773 if (Op1.getOpcode() != ISD::UNDEF)
5774 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5775 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5776 DAG.getIntPtrConstant(1));
5777 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5780 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5781 /// element has been zero/sign-extended, depending on the isSigned parameter,
5782 /// from an integer type half its size.
5783 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5785 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5786 EVT VT = N->getValueType(0);
5787 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5788 SDNode *BVN = N->getOperand(0).getNode();
5789 if (BVN->getValueType(0) != MVT::v4i32 ||
5790 BVN->getOpcode() != ISD::BUILD_VECTOR)
5792 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5793 unsigned HiElt = 1 - LoElt;
5794 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5795 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5796 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5797 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5798 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5801 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5802 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5805 if (Hi0->isNullValue() && Hi1->isNullValue())
5811 if (N->getOpcode() != ISD::BUILD_VECTOR)
5814 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5815 SDNode *Elt = N->getOperand(i).getNode();
5816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5817 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5818 unsigned HalfSize = EltSize / 2;
5820 if (!isIntN(HalfSize, C->getSExtValue()))
5823 if (!isUIntN(HalfSize, C->getZExtValue()))
5834 /// isSignExtended - Check if a node is a vector value that is sign-extended
5835 /// or a constant BUILD_VECTOR with sign-extended elements.
5836 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5837 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5839 if (isExtendedBUILD_VECTOR(N, DAG, true))
5844 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5845 /// or a constant BUILD_VECTOR with zero-extended elements.
5846 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5847 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5849 if (isExtendedBUILD_VECTOR(N, DAG, false))
5854 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5855 if (OrigVT.getSizeInBits() >= 64)
5858 assert(OrigVT.isSimple() && "Expecting a simple value type");
5860 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5861 switch (OrigSimpleTy) {
5862 default: llvm_unreachable("Unexpected Vector Type");
5871 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5872 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5873 /// We insert the required extension here to get the vector to fill a D register.
5874 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5877 unsigned ExtOpcode) {
5878 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5879 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5880 // 64-bits we need to insert a new extension so that it will be 64-bits.
5881 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5882 if (OrigTy.getSizeInBits() >= 64)
5885 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5886 EVT NewVT = getExtensionTo64Bits(OrigTy);
5888 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5891 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5892 /// does not do any sign/zero extension. If the original vector is less
5893 /// than 64 bits, an appropriate extension will be added after the load to
5894 /// reach a total size of 64 bits. We have to add the extension separately
5895 /// because ARM does not have a sign/zero extending load for vectors.
5896 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5897 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5899 // The load already has the right type.
5900 if (ExtendedTy == LD->getMemoryVT())
5901 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5902 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5903 LD->isNonTemporal(), LD->isInvariant(),
5904 LD->getAlignment());
5906 // We need to create a zextload/sextload. We cannot just create a load
5907 // followed by a zext/zext node because LowerMUL is also run during normal
5908 // operation legalization where we can't create illegal types.
5909 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5910 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5911 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5912 LD->isNonTemporal(), LD->getAlignment());
5915 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5916 /// extending load, or BUILD_VECTOR with extended elements, return the
5917 /// unextended value. The unextended vector should be 64 bits so that it can
5918 /// be used as an operand to a VMULL instruction. If the original vector size
5919 /// before extension is less than 64 bits we add a an extension to resize
5920 /// the vector to 64 bits.
5921 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5922 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5923 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5924 N->getOperand(0)->getValueType(0),
5928 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5929 return SkipLoadExtensionForVMULL(LD, DAG);
5931 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5932 // have been legalized as a BITCAST from v4i32.
5933 if (N->getOpcode() == ISD::BITCAST) {
5934 SDNode *BVN = N->getOperand(0).getNode();
5935 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5936 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5937 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5938 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5939 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5941 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5942 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5943 EVT VT = N->getValueType(0);
5944 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5945 unsigned NumElts = VT.getVectorNumElements();
5946 MVT TruncVT = MVT::getIntegerVT(EltSize);
5947 SmallVector<SDValue, 8> Ops;
5948 for (unsigned i = 0; i != NumElts; ++i) {
5949 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5950 const APInt &CInt = C->getAPIntValue();
5951 // Element types smaller than 32 bits are not legal, so use i32 elements.
5952 // The values are implicitly truncated so sext vs. zext doesn't matter.
5953 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5955 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5956 MVT::getVectorVT(TruncVT, NumElts), Ops);
5959 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5960 unsigned Opcode = N->getOpcode();
5961 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5962 SDNode *N0 = N->getOperand(0).getNode();
5963 SDNode *N1 = N->getOperand(1).getNode();
5964 return N0->hasOneUse() && N1->hasOneUse() &&
5965 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5970 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5971 unsigned Opcode = N->getOpcode();
5972 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5973 SDNode *N0 = N->getOperand(0).getNode();
5974 SDNode *N1 = N->getOperand(1).getNode();
5975 return N0->hasOneUse() && N1->hasOneUse() &&
5976 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5981 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5982 // Multiplications are only custom-lowered for 128-bit vectors so that
5983 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5984 EVT VT = Op.getValueType();
5985 assert(VT.is128BitVector() && VT.isInteger() &&
5986 "unexpected type for custom-lowering ISD::MUL");
5987 SDNode *N0 = Op.getOperand(0).getNode();
5988 SDNode *N1 = Op.getOperand(1).getNode();
5989 unsigned NewOpc = 0;
5991 bool isN0SExt = isSignExtended(N0, DAG);
5992 bool isN1SExt = isSignExtended(N1, DAG);
5993 if (isN0SExt && isN1SExt)
5994 NewOpc = ARMISD::VMULLs;
5996 bool isN0ZExt = isZeroExtended(N0, DAG);
5997 bool isN1ZExt = isZeroExtended(N1, DAG);
5998 if (isN0ZExt && isN1ZExt)
5999 NewOpc = ARMISD::VMULLu;
6000 else if (isN1SExt || isN1ZExt) {
6001 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6002 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6003 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6004 NewOpc = ARMISD::VMULLs;
6006 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6007 NewOpc = ARMISD::VMULLu;
6009 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6011 NewOpc = ARMISD::VMULLu;
6017 if (VT == MVT::v2i64)
6018 // Fall through to expand this. It is not legal.
6021 // Other vector multiplications are legal.
6026 // Legalize to a VMULL instruction.
6029 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6031 Op0 = SkipExtensionForVMULL(N0, DAG);
6032 assert(Op0.getValueType().is64BitVector() &&
6033 Op1.getValueType().is64BitVector() &&
6034 "unexpected types for extended operands to VMULL");
6035 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6038 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6039 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6046 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6047 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6048 EVT Op1VT = Op1.getValueType();
6049 return DAG.getNode(N0->getOpcode(), DL, VT,
6050 DAG.getNode(NewOpc, DL, VT,
6051 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6052 DAG.getNode(NewOpc, DL, VT,
6053 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6057 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6059 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6060 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6061 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6062 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6063 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6064 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6065 // Get reciprocal estimate.
6066 // float4 recip = vrecpeq_f32(yf);
6067 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6068 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6069 // Because char has a smaller range than uchar, we can actually get away
6070 // without any newton steps. This requires that we use a weird bias
6071 // of 0xb000, however (again, this has been exhaustively tested).
6072 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6073 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6074 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6075 Y = DAG.getConstant(0xb000, MVT::i32);
6076 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6077 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6078 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6079 // Convert back to short.
6080 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6081 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6086 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6088 // Convert to float.
6089 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6090 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6091 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6092 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6093 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6094 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6096 // Use reciprocal estimate and one refinement step.
6097 // float4 recip = vrecpeq_f32(yf);
6098 // recip *= vrecpsq_f32(yf, recip);
6099 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6100 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6101 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6102 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6104 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6105 // Because short has a smaller range than ushort, we can actually get away
6106 // with only a single newton step. This requires that we use a weird bias
6107 // of 89, however (again, this has been exhaustively tested).
6108 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6109 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6110 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6111 N1 = DAG.getConstant(0x89, MVT::i32);
6112 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6113 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6114 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6115 // Convert back to integer and return.
6116 // return vmovn_s32(vcvt_s32_f32(result));
6117 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6118 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6122 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6123 EVT VT = Op.getValueType();
6124 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6125 "unexpected type for custom-lowering ISD::SDIV");
6128 SDValue N0 = Op.getOperand(0);
6129 SDValue N1 = Op.getOperand(1);
6132 if (VT == MVT::v8i8) {
6133 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6134 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6136 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6137 DAG.getIntPtrConstant(4));
6138 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6139 DAG.getIntPtrConstant(4));
6140 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6141 DAG.getIntPtrConstant(0));
6142 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6143 DAG.getIntPtrConstant(0));
6145 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6146 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6148 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6149 N0 = LowerCONCAT_VECTORS(N0, DAG);
6151 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6154 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6157 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6158 EVT VT = Op.getValueType();
6159 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6160 "unexpected type for custom-lowering ISD::UDIV");
6163 SDValue N0 = Op.getOperand(0);
6164 SDValue N1 = Op.getOperand(1);
6167 if (VT == MVT::v8i8) {
6168 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6169 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6171 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6172 DAG.getIntPtrConstant(4));
6173 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6174 DAG.getIntPtrConstant(4));
6175 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6176 DAG.getIntPtrConstant(0));
6177 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6178 DAG.getIntPtrConstant(0));
6180 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6181 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6183 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6184 N0 = LowerCONCAT_VECTORS(N0, DAG);
6186 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6187 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6192 // v4i16 sdiv ... Convert to float.
6193 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6194 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6195 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6196 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6197 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6198 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6200 // Use reciprocal estimate and two refinement steps.
6201 // float4 recip = vrecpeq_f32(yf);
6202 // recip *= vrecpsq_f32(yf, recip);
6203 // recip *= vrecpsq_f32(yf, recip);
6204 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6205 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6206 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6207 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6209 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6210 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6211 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6213 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6214 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6215 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6216 // and that it will never cause us to return an answer too large).
6217 // float4 result = as_float4(as_int4(xf*recip) + 2);
6218 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6219 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6220 N1 = DAG.getConstant(2, MVT::i32);
6221 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6222 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6223 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6224 // Convert back to integer and return.
6225 // return vmovn_u32(vcvt_s32_f32(result));
6226 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6227 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6231 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6232 EVT VT = Op.getNode()->getValueType(0);
6233 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6236 bool ExtraOp = false;
6237 switch (Op.getOpcode()) {
6238 default: llvm_unreachable("Invalid code");
6239 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6240 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6241 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6242 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6246 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6248 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6249 Op.getOperand(1), Op.getOperand(2));
6252 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6253 assert(Subtarget->isTargetDarwin());
6255 // For iOS, we want to call an alternative entry point: __sincos_stret,
6256 // return values are passed via sret.
6258 SDValue Arg = Op.getOperand(0);
6259 EVT ArgVT = Arg.getValueType();
6260 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6262 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6263 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6265 // Pair of floats / doubles used to pass the result.
6266 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6268 // Create stack object for sret.
6269 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6270 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6271 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6272 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6278 Entry.Ty = RetTy->getPointerTo();
6279 Entry.isSExt = false;
6280 Entry.isZExt = false;
6281 Entry.isSRet = true;
6282 Args.push_back(Entry);
6286 Entry.isSExt = false;
6287 Entry.isZExt = false;
6288 Args.push_back(Entry);
6290 const char *LibcallName = (ArgVT == MVT::f64)
6291 ? "__sincos_stret" : "__sincosf_stret";
6292 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6294 TargetLowering::CallLoweringInfo CLI(DAG);
6295 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6296 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6298 .setDiscardResult();
6300 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6302 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6303 MachinePointerInfo(), false, false, false, 0);
6305 // Address of cos field.
6306 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6307 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6308 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6309 MachinePointerInfo(), false, false, false, 0);
6311 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6312 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6313 LoadSin.getValue(0), LoadCos.getValue(0));
6316 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6317 // Monotonic load/store is legal for all targets
6318 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6321 // Acquire/Release load/store is not legal for targets without a
6322 // dmb or equivalent available.
6326 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6327 SmallVectorImpl<SDValue> &Results,
6329 const ARMSubtarget *Subtarget) {
6331 SDValue Cycles32, OutChain;
6333 if (Subtarget->hasPerfMon()) {
6334 // Under Power Management extensions, the cycle-count is:
6335 // mrc p15, #0, <Rt>, c9, c13, #0
6336 SDValue Ops[] = { N->getOperand(0), // Chain
6337 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6338 DAG.getConstant(15, MVT::i32),
6339 DAG.getConstant(0, MVT::i32),
6340 DAG.getConstant(9, MVT::i32),
6341 DAG.getConstant(13, MVT::i32),
6342 DAG.getConstant(0, MVT::i32)
6345 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6346 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6347 OutChain = Cycles32.getValue(1);
6349 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6350 // there are older ARM CPUs that have implementation-specific ways of
6351 // obtaining this information (FIXME!).
6352 Cycles32 = DAG.getConstant(0, MVT::i32);
6353 OutChain = DAG.getEntryNode();
6357 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6358 Cycles32, DAG.getConstant(0, MVT::i32));
6359 Results.push_back(Cycles64);
6360 Results.push_back(OutChain);
6363 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6364 switch (Op.getOpcode()) {
6365 default: llvm_unreachable("Don't know how to custom lower this!");
6366 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6367 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6368 case ISD::GlobalAddress:
6369 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6370 default: llvm_unreachable("unknown object format");
6372 return LowerGlobalAddressWindows(Op, DAG);
6374 return LowerGlobalAddressELF(Op, DAG);
6376 return LowerGlobalAddressDarwin(Op, DAG);
6378 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6379 case ISD::SELECT: return LowerSELECT(Op, DAG);
6380 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6381 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6382 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6383 case ISD::VASTART: return LowerVASTART(Op, DAG);
6384 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6385 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6386 case ISD::SINT_TO_FP:
6387 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6388 case ISD::FP_TO_SINT:
6389 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6390 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6391 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6392 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6393 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6394 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6395 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6396 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6398 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6401 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6402 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6403 case ISD::SRL_PARTS:
6404 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6405 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6406 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6407 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6408 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6409 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6410 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6411 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6412 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6413 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6414 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6415 case ISD::MUL: return LowerMUL(Op, DAG);
6416 case ISD::SDIV: return LowerSDIV(Op, DAG);
6417 case ISD::UDIV: return LowerUDIV(Op, DAG);
6421 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6426 return LowerXALUO(Op, DAG);
6427 case ISD::ATOMIC_LOAD:
6428 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6429 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6431 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6432 case ISD::DYNAMIC_STACKALLOC:
6433 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6434 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6435 llvm_unreachable("Don't know how to custom lower this!");
6436 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6437 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6441 /// ReplaceNodeResults - Replace the results of node with an illegal result
6442 /// type with new values built out of custom code.
6443 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6444 SmallVectorImpl<SDValue>&Results,
6445 SelectionDAG &DAG) const {
6447 switch (N->getOpcode()) {
6449 llvm_unreachable("Don't know how to custom expand this!");
6451 Res = ExpandBITCAST(N, DAG);
6455 Res = Expand64BitShift(N, DAG, Subtarget);
6457 case ISD::READCYCLECOUNTER:
6458 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6462 Results.push_back(Res);
6465 //===----------------------------------------------------------------------===//
6466 // ARM Scheduler Hooks
6467 //===----------------------------------------------------------------------===//
6469 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6470 /// registers the function context.
6471 void ARMTargetLowering::
6472 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6473 MachineBasicBlock *DispatchBB, int FI) const {
6474 const TargetInstrInfo *TII =
6475 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6476 DebugLoc dl = MI->getDebugLoc();
6477 MachineFunction *MF = MBB->getParent();
6478 MachineRegisterInfo *MRI = &MF->getRegInfo();
6479 MachineConstantPool *MCP = MF->getConstantPool();
6480 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6481 const Function *F = MF->getFunction();
6483 bool isThumb = Subtarget->isThumb();
6484 bool isThumb2 = Subtarget->isThumb2();
6486 unsigned PCLabelId = AFI->createPICLabelUId();
6487 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6488 ARMConstantPoolValue *CPV =
6489 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6490 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6492 const TargetRegisterClass *TRC = isThumb ?
6493 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6494 (const TargetRegisterClass*)&ARM::GPRRegClass;
6496 // Grab constant pool and fixed stack memory operands.
6497 MachineMemOperand *CPMMO =
6498 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6499 MachineMemOperand::MOLoad, 4, 4);
6501 MachineMemOperand *FIMMOSt =
6502 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6503 MachineMemOperand::MOStore, 4, 4);
6505 // Load the address of the dispatch MBB into the jump buffer.
6507 // Incoming value: jbuf
6508 // ldr.n r5, LCPI1_1
6511 // str r5, [$jbuf, #+4] ; &jbuf[1]
6512 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6513 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6514 .addConstantPoolIndex(CPI)
6515 .addMemOperand(CPMMO));
6516 // Set the low bit because of thumb mode.
6517 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6519 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6520 .addReg(NewVReg1, RegState::Kill)
6522 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6523 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6524 .addReg(NewVReg2, RegState::Kill)
6526 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6527 .addReg(NewVReg3, RegState::Kill)
6529 .addImm(36) // &jbuf[1] :: pc
6530 .addMemOperand(FIMMOSt));
6531 } else if (isThumb) {
6532 // Incoming value: jbuf
6533 // ldr.n r1, LCPI1_4
6537 // add r2, $jbuf, #+4 ; &jbuf[1]
6539 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6540 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6541 .addConstantPoolIndex(CPI)
6542 .addMemOperand(CPMMO));
6543 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6544 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6545 .addReg(NewVReg1, RegState::Kill)
6547 // Set the low bit because of thumb mode.
6548 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6549 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6550 .addReg(ARM::CPSR, RegState::Define)
6552 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6553 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6554 .addReg(ARM::CPSR, RegState::Define)
6555 .addReg(NewVReg2, RegState::Kill)
6556 .addReg(NewVReg3, RegState::Kill));
6557 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6558 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6560 .addImm(36)); // &jbuf[1] :: pc
6561 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6562 .addReg(NewVReg4, RegState::Kill)
6563 .addReg(NewVReg5, RegState::Kill)
6565 .addMemOperand(FIMMOSt));
6567 // Incoming value: jbuf
6570 // str r1, [$jbuf, #+4] ; &jbuf[1]
6571 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6572 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6573 .addConstantPoolIndex(CPI)
6575 .addMemOperand(CPMMO));
6576 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6577 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6578 .addReg(NewVReg1, RegState::Kill)
6579 .addImm(PCLabelId));
6580 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6581 .addReg(NewVReg2, RegState::Kill)
6583 .addImm(36) // &jbuf[1] :: pc
6584 .addMemOperand(FIMMOSt));
6588 MachineBasicBlock *ARMTargetLowering::
6589 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6590 const TargetInstrInfo *TII =
6591 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6592 DebugLoc dl = MI->getDebugLoc();
6593 MachineFunction *MF = MBB->getParent();
6594 MachineRegisterInfo *MRI = &MF->getRegInfo();
6595 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6596 MachineFrameInfo *MFI = MF->getFrameInfo();
6597 int FI = MFI->getFunctionContextIndex();
6599 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6600 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6601 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6603 // Get a mapping of the call site numbers to all of the landing pads they're
6605 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6606 unsigned MaxCSNum = 0;
6607 MachineModuleInfo &MMI = MF->getMMI();
6608 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6610 if (!BB->isLandingPad()) continue;
6612 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6614 for (MachineBasicBlock::iterator
6615 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6616 if (!II->isEHLabel()) continue;
6618 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6619 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6621 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6622 for (SmallVectorImpl<unsigned>::iterator
6623 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6624 CSI != CSE; ++CSI) {
6625 CallSiteNumToLPad[*CSI].push_back(BB);
6626 MaxCSNum = std::max(MaxCSNum, *CSI);
6632 // Get an ordered list of the machine basic blocks for the jump table.
6633 std::vector<MachineBasicBlock*> LPadList;
6634 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6635 LPadList.reserve(CallSiteNumToLPad.size());
6636 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6637 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6638 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6639 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6640 LPadList.push_back(*II);
6641 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6645 assert(!LPadList.empty() &&
6646 "No landing pad destinations for the dispatch jump table!");
6648 // Create the jump table and associated information.
6649 MachineJumpTableInfo *JTI =
6650 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6651 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6652 unsigned UId = AFI->createJumpTableUId();
6653 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6655 // Create the MBBs for the dispatch code.
6657 // Shove the dispatch's address into the return slot in the function context.
6658 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6659 DispatchBB->setIsLandingPad();
6661 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6662 unsigned trap_opcode;
6663 if (Subtarget->isThumb())
6664 trap_opcode = ARM::tTRAP;
6666 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6668 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6669 DispatchBB->addSuccessor(TrapBB);
6671 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6672 DispatchBB->addSuccessor(DispContBB);
6675 MF->insert(MF->end(), DispatchBB);
6676 MF->insert(MF->end(), DispContBB);
6677 MF->insert(MF->end(), TrapBB);
6679 // Insert code into the entry block that creates and registers the function
6681 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6683 MachineMemOperand *FIMMOLd =
6684 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6685 MachineMemOperand::MOLoad |
6686 MachineMemOperand::MOVolatile, 4, 4);
6688 MachineInstrBuilder MIB;
6689 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6691 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6692 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6694 // Add a register mask with no preserved registers. This results in all
6695 // registers being marked as clobbered.
6696 MIB.addRegMask(RI.getNoPreservedMask());
6698 unsigned NumLPads = LPadList.size();
6699 if (Subtarget->isThumb2()) {
6700 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6701 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6704 .addMemOperand(FIMMOLd));
6706 if (NumLPads < 256) {
6707 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6709 .addImm(LPadList.size()));
6711 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6712 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6713 .addImm(NumLPads & 0xFFFF));
6715 unsigned VReg2 = VReg1;
6716 if ((NumLPads & 0xFFFF0000) != 0) {
6717 VReg2 = MRI->createVirtualRegister(TRC);
6718 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6720 .addImm(NumLPads >> 16));
6723 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6728 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6733 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6734 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6735 .addJumpTableIndex(MJTI)
6738 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6741 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6742 .addReg(NewVReg3, RegState::Kill)
6744 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6746 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6747 .addReg(NewVReg4, RegState::Kill)
6749 .addJumpTableIndex(MJTI)
6751 } else if (Subtarget->isThumb()) {
6752 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6753 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6756 .addMemOperand(FIMMOLd));
6758 if (NumLPads < 256) {
6759 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6763 MachineConstantPool *ConstantPool = MF->getConstantPool();
6764 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6765 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6767 // MachineConstantPool wants an explicit alignment.
6768 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6770 Align = getDataLayout()->getTypeAllocSize(C->getType());
6771 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6773 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6774 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6775 .addReg(VReg1, RegState::Define)
6776 .addConstantPoolIndex(Idx));
6777 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6782 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6787 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6788 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6789 .addReg(ARM::CPSR, RegState::Define)
6793 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6794 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6795 .addJumpTableIndex(MJTI)
6798 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6799 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6800 .addReg(ARM::CPSR, RegState::Define)
6801 .addReg(NewVReg2, RegState::Kill)
6804 MachineMemOperand *JTMMOLd =
6805 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6806 MachineMemOperand::MOLoad, 4, 4);
6808 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6809 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6810 .addReg(NewVReg4, RegState::Kill)
6812 .addMemOperand(JTMMOLd));
6814 unsigned NewVReg6 = NewVReg5;
6815 if (RelocM == Reloc::PIC_) {
6816 NewVReg6 = MRI->createVirtualRegister(TRC);
6817 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6818 .addReg(ARM::CPSR, RegState::Define)
6819 .addReg(NewVReg5, RegState::Kill)
6823 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6824 .addReg(NewVReg6, RegState::Kill)
6825 .addJumpTableIndex(MJTI)
6828 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6829 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6832 .addMemOperand(FIMMOLd));
6834 if (NumLPads < 256) {
6835 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6838 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6839 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6840 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6841 .addImm(NumLPads & 0xFFFF));
6843 unsigned VReg2 = VReg1;
6844 if ((NumLPads & 0xFFFF0000) != 0) {
6845 VReg2 = MRI->createVirtualRegister(TRC);
6846 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6848 .addImm(NumLPads >> 16));
6851 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6855 MachineConstantPool *ConstantPool = MF->getConstantPool();
6856 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6857 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6859 // MachineConstantPool wants an explicit alignment.
6860 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6862 Align = getDataLayout()->getTypeAllocSize(C->getType());
6863 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6865 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6866 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6867 .addReg(VReg1, RegState::Define)
6868 .addConstantPoolIndex(Idx)
6870 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6872 .addReg(VReg1, RegState::Kill));
6875 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6880 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6882 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6884 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6885 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6886 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6887 .addJumpTableIndex(MJTI)
6890 MachineMemOperand *JTMMOLd =
6891 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6892 MachineMemOperand::MOLoad, 4, 4);
6893 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6895 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6896 .addReg(NewVReg3, RegState::Kill)
6899 .addMemOperand(JTMMOLd));
6901 if (RelocM == Reloc::PIC_) {
6902 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6903 .addReg(NewVReg5, RegState::Kill)
6905 .addJumpTableIndex(MJTI)
6908 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6909 .addReg(NewVReg5, RegState::Kill)
6910 .addJumpTableIndex(MJTI)
6915 // Add the jump table entries as successors to the MBB.
6916 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6917 for (std::vector<MachineBasicBlock*>::iterator
6918 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6919 MachineBasicBlock *CurMBB = *I;
6920 if (SeenMBBs.insert(CurMBB))
6921 DispContBB->addSuccessor(CurMBB);
6924 // N.B. the order the invoke BBs are processed in doesn't matter here.
6925 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6926 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6927 for (MachineBasicBlock *BB : InvokeBBs) {
6929 // Remove the landing pad successor from the invoke block and replace it
6930 // with the new dispatch block.
6931 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6933 while (!Successors.empty()) {
6934 MachineBasicBlock *SMBB = Successors.pop_back_val();
6935 if (SMBB->isLandingPad()) {
6936 BB->removeSuccessor(SMBB);
6937 MBBLPads.push_back(SMBB);
6941 BB->addSuccessor(DispatchBB);
6943 // Find the invoke call and mark all of the callee-saved registers as
6944 // 'implicit defined' so that they're spilled. This prevents code from
6945 // moving instructions to before the EH block, where they will never be
6947 for (MachineBasicBlock::reverse_iterator
6948 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6949 if (!II->isCall()) continue;
6951 DenseMap<unsigned, bool> DefRegs;
6952 for (MachineInstr::mop_iterator
6953 OI = II->operands_begin(), OE = II->operands_end();
6955 if (!OI->isReg()) continue;
6956 DefRegs[OI->getReg()] = true;
6959 MachineInstrBuilder MIB(*MF, &*II);
6961 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6962 unsigned Reg = SavedRegs[i];
6963 if (Subtarget->isThumb2() &&
6964 !ARM::tGPRRegClass.contains(Reg) &&
6965 !ARM::hGPRRegClass.contains(Reg))
6967 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6969 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6972 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6979 // Mark all former landing pads as non-landing pads. The dispatch is the only
6981 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6982 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6983 (*I)->setIsLandingPad(false);
6985 // The instruction is gone now.
6986 MI->eraseFromParent();
6992 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6993 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6994 E = MBB->succ_end(); I != E; ++I)
6997 llvm_unreachable("Expecting a BB with two successors!");
7000 /// Return the load opcode for a given load size. If load size >= 8,
7001 /// neon opcode will be returned.
7002 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7004 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7005 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7007 return LdSize == 4 ? ARM::tLDRi
7008 : LdSize == 2 ? ARM::tLDRHi
7009 : LdSize == 1 ? ARM::tLDRBi : 0;
7011 return LdSize == 4 ? ARM::t2LDR_POST
7012 : LdSize == 2 ? ARM::t2LDRH_POST
7013 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7014 return LdSize == 4 ? ARM::LDR_POST_IMM
7015 : LdSize == 2 ? ARM::LDRH_POST
7016 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7019 /// Return the store opcode for a given store size. If store size >= 8,
7020 /// neon opcode will be returned.
7021 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7023 return StSize == 16 ? ARM::VST1q32wb_fixed
7024 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7026 return StSize == 4 ? ARM::tSTRi
7027 : StSize == 2 ? ARM::tSTRHi
7028 : StSize == 1 ? ARM::tSTRBi : 0;
7030 return StSize == 4 ? ARM::t2STR_POST
7031 : StSize == 2 ? ARM::t2STRH_POST
7032 : StSize == 1 ? ARM::t2STRB_POST : 0;
7033 return StSize == 4 ? ARM::STR_POST_IMM
7034 : StSize == 2 ? ARM::STRH_POST
7035 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7038 /// Emit a post-increment load operation with given size. The instructions
7039 /// will be added to BB at Pos.
7040 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7041 const TargetInstrInfo *TII, DebugLoc dl,
7042 unsigned LdSize, unsigned Data, unsigned AddrIn,
7043 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7044 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7045 assert(LdOpc != 0 && "Should have a load opcode");
7047 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7048 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7050 } else if (IsThumb1) {
7051 // load + update AddrIn
7052 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7053 .addReg(AddrIn).addImm(0));
7054 MachineInstrBuilder MIB =
7055 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7056 MIB = AddDefaultT1CC(MIB);
7057 MIB.addReg(AddrIn).addImm(LdSize);
7058 AddDefaultPred(MIB);
7059 } else if (IsThumb2) {
7060 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7061 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7064 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7065 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7066 .addReg(0).addImm(LdSize));
7070 /// Emit a post-increment store operation with given size. The instructions
7071 /// will be added to BB at Pos.
7072 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7073 const TargetInstrInfo *TII, DebugLoc dl,
7074 unsigned StSize, unsigned Data, unsigned AddrIn,
7075 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7076 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7077 assert(StOpc != 0 && "Should have a store opcode");
7079 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7080 .addReg(AddrIn).addImm(0).addReg(Data));
7081 } else if (IsThumb1) {
7082 // store + update AddrIn
7083 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7084 .addReg(AddrIn).addImm(0));
7085 MachineInstrBuilder MIB =
7086 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7087 MIB = AddDefaultT1CC(MIB);
7088 MIB.addReg(AddrIn).addImm(StSize);
7089 AddDefaultPred(MIB);
7090 } else if (IsThumb2) {
7091 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7092 .addReg(Data).addReg(AddrIn).addImm(StSize));
7094 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7095 .addReg(Data).addReg(AddrIn).addReg(0)
7101 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7102 MachineBasicBlock *BB) const {
7103 // This pseudo instruction has 3 operands: dst, src, size
7104 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7105 // Otherwise, we will generate unrolled scalar copies.
7106 const TargetInstrInfo *TII =
7107 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7108 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7109 MachineFunction::iterator It = BB;
7112 unsigned dest = MI->getOperand(0).getReg();
7113 unsigned src = MI->getOperand(1).getReg();
7114 unsigned SizeVal = MI->getOperand(2).getImm();
7115 unsigned Align = MI->getOperand(3).getImm();
7116 DebugLoc dl = MI->getDebugLoc();
7118 MachineFunction *MF = BB->getParent();
7119 MachineRegisterInfo &MRI = MF->getRegInfo();
7120 unsigned UnitSize = 0;
7121 const TargetRegisterClass *TRC = nullptr;
7122 const TargetRegisterClass *VecTRC = nullptr;
7124 bool IsThumb1 = Subtarget->isThumb1Only();
7125 bool IsThumb2 = Subtarget->isThumb2();
7129 } else if (Align & 2) {
7132 // Check whether we can use NEON instructions.
7133 if (!MF->getFunction()->getAttributes().
7134 hasAttribute(AttributeSet::FunctionIndex,
7135 Attribute::NoImplicitFloat) &&
7136 Subtarget->hasNEON()) {
7137 if ((Align % 16 == 0) && SizeVal >= 16)
7139 else if ((Align % 8 == 0) && SizeVal >= 8)
7142 // Can't use NEON instructions.
7147 // Select the correct opcode and register class for unit size load/store
7148 bool IsNeon = UnitSize >= 8;
7149 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7150 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7152 VecTRC = UnitSize == 16
7153 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7155 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7158 unsigned BytesLeft = SizeVal % UnitSize;
7159 unsigned LoopSize = SizeVal - BytesLeft;
7161 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7162 // Use LDR and STR to copy.
7163 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7164 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7165 unsigned srcIn = src;
7166 unsigned destIn = dest;
7167 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7168 unsigned srcOut = MRI.createVirtualRegister(TRC);
7169 unsigned destOut = MRI.createVirtualRegister(TRC);
7170 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7171 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7172 IsThumb1, IsThumb2);
7173 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7174 IsThumb1, IsThumb2);
7179 // Handle the leftover bytes with LDRB and STRB.
7180 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7181 // [destOut] = STRB_POST(scratch, destIn, 1)
7182 for (unsigned i = 0; i < BytesLeft; i++) {
7183 unsigned srcOut = MRI.createVirtualRegister(TRC);
7184 unsigned destOut = MRI.createVirtualRegister(TRC);
7185 unsigned scratch = MRI.createVirtualRegister(TRC);
7186 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7187 IsThumb1, IsThumb2);
7188 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7189 IsThumb1, IsThumb2);
7193 MI->eraseFromParent(); // The instruction is gone now.
7197 // Expand the pseudo op to a loop.
7200 // movw varEnd, # --> with thumb2
7202 // ldrcp varEnd, idx --> without thumb2
7203 // fallthrough --> loopMBB
7205 // PHI varPhi, varEnd, varLoop
7206 // PHI srcPhi, src, srcLoop
7207 // PHI destPhi, dst, destLoop
7208 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7209 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7210 // subs varLoop, varPhi, #UnitSize
7212 // fallthrough --> exitMBB
7214 // epilogue to handle left-over bytes
7215 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7216 // [destOut] = STRB_POST(scratch, destLoop, 1)
7217 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7218 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7219 MF->insert(It, loopMBB);
7220 MF->insert(It, exitMBB);
7222 // Transfer the remainder of BB and its successor edges to exitMBB.
7223 exitMBB->splice(exitMBB->begin(), BB,
7224 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7225 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7227 // Load an immediate to varEnd.
7228 unsigned varEnd = MRI.createVirtualRegister(TRC);
7230 unsigned Vtmp = varEnd;
7231 if ((LoopSize & 0xFFFF0000) != 0)
7232 Vtmp = MRI.createVirtualRegister(TRC);
7233 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7234 .addImm(LoopSize & 0xFFFF));
7236 if ((LoopSize & 0xFFFF0000) != 0)
7237 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7238 .addReg(Vtmp).addImm(LoopSize >> 16));
7240 MachineConstantPool *ConstantPool = MF->getConstantPool();
7241 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7242 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7244 // MachineConstantPool wants an explicit alignment.
7245 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7247 Align = getDataLayout()->getTypeAllocSize(C->getType());
7248 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7251 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7252 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7254 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7255 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7257 BB->addSuccessor(loopMBB);
7259 // Generate the loop body:
7260 // varPhi = PHI(varLoop, varEnd)
7261 // srcPhi = PHI(srcLoop, src)
7262 // destPhi = PHI(destLoop, dst)
7263 MachineBasicBlock *entryBB = BB;
7265 unsigned varLoop = MRI.createVirtualRegister(TRC);
7266 unsigned varPhi = MRI.createVirtualRegister(TRC);
7267 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7268 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7269 unsigned destLoop = MRI.createVirtualRegister(TRC);
7270 unsigned destPhi = MRI.createVirtualRegister(TRC);
7272 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7273 .addReg(varLoop).addMBB(loopMBB)
7274 .addReg(varEnd).addMBB(entryBB);
7275 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7276 .addReg(srcLoop).addMBB(loopMBB)
7277 .addReg(src).addMBB(entryBB);
7278 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7279 .addReg(destLoop).addMBB(loopMBB)
7280 .addReg(dest).addMBB(entryBB);
7282 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7283 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7284 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7285 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7286 IsThumb1, IsThumb2);
7287 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7288 IsThumb1, IsThumb2);
7290 // Decrement loop variable by UnitSize.
7292 MachineInstrBuilder MIB =
7293 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7294 MIB = AddDefaultT1CC(MIB);
7295 MIB.addReg(varPhi).addImm(UnitSize);
7296 AddDefaultPred(MIB);
7298 MachineInstrBuilder MIB =
7299 BuildMI(*BB, BB->end(), dl,
7300 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7301 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7302 MIB->getOperand(5).setReg(ARM::CPSR);
7303 MIB->getOperand(5).setIsDef(true);
7305 BuildMI(*BB, BB->end(), dl,
7306 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7307 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7309 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7310 BB->addSuccessor(loopMBB);
7311 BB->addSuccessor(exitMBB);
7313 // Add epilogue to handle BytesLeft.
7315 MachineInstr *StartOfExit = exitMBB->begin();
7317 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7318 // [destOut] = STRB_POST(scratch, destLoop, 1)
7319 unsigned srcIn = srcLoop;
7320 unsigned destIn = destLoop;
7321 for (unsigned i = 0; i < BytesLeft; i++) {
7322 unsigned srcOut = MRI.createVirtualRegister(TRC);
7323 unsigned destOut = MRI.createVirtualRegister(TRC);
7324 unsigned scratch = MRI.createVirtualRegister(TRC);
7325 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7326 IsThumb1, IsThumb2);
7327 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7328 IsThumb1, IsThumb2);
7333 MI->eraseFromParent(); // The instruction is gone now.
7338 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7339 MachineBasicBlock *MBB) const {
7340 const TargetMachine &TM = getTargetMachine();
7341 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7342 DebugLoc DL = MI->getDebugLoc();
7344 assert(Subtarget->isTargetWindows() &&
7345 "__chkstk is only supported on Windows");
7346 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7348 // __chkstk takes the number of words to allocate on the stack in R4, and
7349 // returns the stack adjustment in number of bytes in R4. This will not
7350 // clober any other registers (other than the obvious lr).
7352 // Although, technically, IP should be considered a register which may be
7353 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7354 // thumb-2 environment, so there is no interworking required. As a result, we
7355 // do not expect a veneer to be emitted by the linker, clobbering IP.
7357 // Each module receives its own copy of __chkstk, so no import thunk is
7358 // required, again, ensuring that IP is not clobbered.
7360 // Finally, although some linkers may theoretically provide a trampoline for
7361 // out of range calls (which is quite common due to a 32M range limitation of
7362 // branches for Thumb), we can generate the long-call version via
7363 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7366 switch (TM.getCodeModel()) {
7367 case CodeModel::Small:
7368 case CodeModel::Medium:
7369 case CodeModel::Default:
7370 case CodeModel::Kernel:
7371 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7372 .addImm((unsigned)ARMCC::AL).addReg(0)
7373 .addExternalSymbol("__chkstk")
7374 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7375 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7376 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7378 case CodeModel::Large:
7379 case CodeModel::JITDefault: {
7380 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7381 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7383 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7384 .addExternalSymbol("__chkstk");
7385 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7386 .addImm((unsigned)ARMCC::AL).addReg(0)
7387 .addReg(Reg, RegState::Kill)
7388 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7389 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7390 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7395 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7397 .addReg(ARM::SP).addReg(ARM::R4)));
7399 MI->eraseFromParent();
7404 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7405 MachineBasicBlock *BB) const {
7406 const TargetInstrInfo *TII =
7407 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7408 DebugLoc dl = MI->getDebugLoc();
7409 bool isThumb2 = Subtarget->isThumb2();
7410 switch (MI->getOpcode()) {
7413 llvm_unreachable("Unexpected instr type to insert");
7415 // The Thumb2 pre-indexed stores have the same MI operands, they just
7416 // define them differently in the .td files from the isel patterns, so
7417 // they need pseudos.
7418 case ARM::t2STR_preidx:
7419 MI->setDesc(TII->get(ARM::t2STR_PRE));
7421 case ARM::t2STRB_preidx:
7422 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7424 case ARM::t2STRH_preidx:
7425 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7428 case ARM::STRi_preidx:
7429 case ARM::STRBi_preidx: {
7430 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7431 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7432 // Decode the offset.
7433 unsigned Offset = MI->getOperand(4).getImm();
7434 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7435 Offset = ARM_AM::getAM2Offset(Offset);
7439 MachineMemOperand *MMO = *MI->memoperands_begin();
7440 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7441 .addOperand(MI->getOperand(0)) // Rn_wb
7442 .addOperand(MI->getOperand(1)) // Rt
7443 .addOperand(MI->getOperand(2)) // Rn
7444 .addImm(Offset) // offset (skip GPR==zero_reg)
7445 .addOperand(MI->getOperand(5)) // pred
7446 .addOperand(MI->getOperand(6))
7447 .addMemOperand(MMO);
7448 MI->eraseFromParent();
7451 case ARM::STRr_preidx:
7452 case ARM::STRBr_preidx:
7453 case ARM::STRH_preidx: {
7455 switch (MI->getOpcode()) {
7456 default: llvm_unreachable("unexpected opcode!");
7457 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7458 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7459 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7461 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7462 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7463 MIB.addOperand(MI->getOperand(i));
7464 MI->eraseFromParent();
7468 case ARM::tMOVCCr_pseudo: {
7469 // To "insert" a SELECT_CC instruction, we actually have to insert the
7470 // diamond control-flow pattern. The incoming instruction knows the
7471 // destination vreg to set, the condition code register to branch on, the
7472 // true/false values to select between, and a branch opcode to use.
7473 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7474 MachineFunction::iterator It = BB;
7480 // cmpTY ccX, r1, r2
7482 // fallthrough --> copy0MBB
7483 MachineBasicBlock *thisMBB = BB;
7484 MachineFunction *F = BB->getParent();
7485 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7486 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7487 F->insert(It, copy0MBB);
7488 F->insert(It, sinkMBB);
7490 // Transfer the remainder of BB and its successor edges to sinkMBB.
7491 sinkMBB->splice(sinkMBB->begin(), BB,
7492 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7493 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7495 BB->addSuccessor(copy0MBB);
7496 BB->addSuccessor(sinkMBB);
7498 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7499 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7502 // %FalseValue = ...
7503 // # fallthrough to sinkMBB
7506 // Update machine-CFG edges
7507 BB->addSuccessor(sinkMBB);
7510 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7513 BuildMI(*BB, BB->begin(), dl,
7514 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7515 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7516 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7518 MI->eraseFromParent(); // The pseudo instruction is gone now.
7523 case ARM::BCCZi64: {
7524 // If there is an unconditional branch to the other successor, remove it.
7525 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7527 // Compare both parts that make up the double comparison separately for
7529 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7531 unsigned LHS1 = MI->getOperand(1).getReg();
7532 unsigned LHS2 = MI->getOperand(2).getReg();
7534 AddDefaultPred(BuildMI(BB, dl,
7535 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7536 .addReg(LHS1).addImm(0));
7537 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7538 .addReg(LHS2).addImm(0)
7539 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7541 unsigned RHS1 = MI->getOperand(3).getReg();
7542 unsigned RHS2 = MI->getOperand(4).getReg();
7543 AddDefaultPred(BuildMI(BB, dl,
7544 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7545 .addReg(LHS1).addReg(RHS1));
7546 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7547 .addReg(LHS2).addReg(RHS2)
7548 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7551 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7552 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7553 if (MI->getOperand(0).getImm() == ARMCC::NE)
7554 std::swap(destMBB, exitMBB);
7556 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7557 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7559 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7561 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7563 MI->eraseFromParent(); // The pseudo instruction is gone now.
7567 case ARM::Int_eh_sjlj_setjmp:
7568 case ARM::Int_eh_sjlj_setjmp_nofp:
7569 case ARM::tInt_eh_sjlj_setjmp:
7570 case ARM::t2Int_eh_sjlj_setjmp:
7571 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7572 EmitSjLjDispatchBlock(MI, BB);
7577 // To insert an ABS instruction, we have to insert the
7578 // diamond control-flow pattern. The incoming instruction knows the
7579 // source vreg to test against 0, the destination vreg to set,
7580 // the condition code register to branch on, the
7581 // true/false values to select between, and a branch opcode to use.
7586 // BCC (branch to SinkBB if V0 >= 0)
7587 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7588 // SinkBB: V1 = PHI(V2, V3)
7589 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7590 MachineFunction::iterator BBI = BB;
7592 MachineFunction *Fn = BB->getParent();
7593 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7594 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7595 Fn->insert(BBI, RSBBB);
7596 Fn->insert(BBI, SinkBB);
7598 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7599 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7600 bool isThumb2 = Subtarget->isThumb2();
7601 MachineRegisterInfo &MRI = Fn->getRegInfo();
7602 // In Thumb mode S must not be specified if source register is the SP or
7603 // PC and if destination register is the SP, so restrict register class
7604 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7605 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7606 (const TargetRegisterClass*)&ARM::GPRRegClass);
7608 // Transfer the remainder of BB and its successor edges to sinkMBB.
7609 SinkBB->splice(SinkBB->begin(), BB,
7610 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7611 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7613 BB->addSuccessor(RSBBB);
7614 BB->addSuccessor(SinkBB);
7616 // fall through to SinkMBB
7617 RSBBB->addSuccessor(SinkBB);
7619 // insert a cmp at the end of BB
7620 AddDefaultPred(BuildMI(BB, dl,
7621 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7622 .addReg(ABSSrcReg).addImm(0));
7624 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7626 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7627 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7629 // insert rsbri in RSBBB
7630 // Note: BCC and rsbri will be converted into predicated rsbmi
7631 // by if-conversion pass
7632 BuildMI(*RSBBB, RSBBB->begin(), dl,
7633 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7634 .addReg(ABSSrcReg, RegState::Kill)
7635 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7637 // insert PHI in SinkBB,
7638 // reuse ABSDstReg to not change uses of ABS instruction
7639 BuildMI(*SinkBB, SinkBB->begin(), dl,
7640 TII->get(ARM::PHI), ABSDstReg)
7641 .addReg(NewRsbDstReg).addMBB(RSBBB)
7642 .addReg(ABSSrcReg).addMBB(BB);
7644 // remove ABS instruction
7645 MI->eraseFromParent();
7647 // return last added BB
7650 case ARM::COPY_STRUCT_BYVAL_I32:
7652 return EmitStructByval(MI, BB);
7653 case ARM::WIN__CHKSTK:
7654 return EmitLowered__chkstk(MI, BB);
7658 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7659 SDNode *Node) const {
7660 if (!MI->hasPostISelHook()) {
7661 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7662 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7666 const MCInstrDesc *MCID = &MI->getDesc();
7667 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7668 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7669 // operand is still set to noreg. If needed, set the optional operand's
7670 // register to CPSR, and remove the redundant implicit def.
7672 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7674 // Rename pseudo opcodes.
7675 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7677 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7678 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7679 MCID = &TII->get(NewOpc);
7681 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7682 "converted opcode should be the same except for cc_out");
7686 // Add the optional cc_out operand
7687 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7689 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7691 // Any ARM instruction that sets the 's' bit should specify an optional
7692 // "cc_out" operand in the last operand position.
7693 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7694 assert(!NewOpc && "Optional cc_out operand required");
7697 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7698 // since we already have an optional CPSR def.
7699 bool definesCPSR = false;
7700 bool deadCPSR = false;
7701 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7703 const MachineOperand &MO = MI->getOperand(i);
7704 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7708 MI->RemoveOperand(i);
7713 assert(!NewOpc && "Optional cc_out operand required");
7716 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7718 assert(!MI->getOperand(ccOutIdx).getReg() &&
7719 "expect uninitialized optional cc_out operand");
7723 // If this instruction was defined with an optional CPSR def and its dag node
7724 // had a live implicit CPSR def, then activate the optional CPSR def.
7725 MachineOperand &MO = MI->getOperand(ccOutIdx);
7726 MO.setReg(ARM::CPSR);
7730 //===----------------------------------------------------------------------===//
7731 // ARM Optimization Hooks
7732 //===----------------------------------------------------------------------===//
7734 // Helper function that checks if N is a null or all ones constant.
7735 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7736 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7739 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7742 // Return true if N is conditionally 0 or all ones.
7743 // Detects these expressions where cc is an i1 value:
7745 // (select cc 0, y) [AllOnes=0]
7746 // (select cc y, 0) [AllOnes=0]
7747 // (zext cc) [AllOnes=0]
7748 // (sext cc) [AllOnes=0/1]
7749 // (select cc -1, y) [AllOnes=1]
7750 // (select cc y, -1) [AllOnes=1]
7752 // Invert is set when N is the null/all ones constant when CC is false.
7753 // OtherOp is set to the alternative value of N.
7754 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7755 SDValue &CC, bool &Invert,
7757 SelectionDAG &DAG) {
7758 switch (N->getOpcode()) {
7759 default: return false;
7761 CC = N->getOperand(0);
7762 SDValue N1 = N->getOperand(1);
7763 SDValue N2 = N->getOperand(2);
7764 if (isZeroOrAllOnes(N1, AllOnes)) {
7769 if (isZeroOrAllOnes(N2, AllOnes)) {
7776 case ISD::ZERO_EXTEND:
7777 // (zext cc) can never be the all ones value.
7781 case ISD::SIGN_EXTEND: {
7782 EVT VT = N->getValueType(0);
7783 CC = N->getOperand(0);
7784 if (CC.getValueType() != MVT::i1)
7788 // When looking for an AllOnes constant, N is an sext, and the 'other'
7790 OtherOp = DAG.getConstant(0, VT);
7791 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7792 // When looking for a 0 constant, N can be zext or sext.
7793 OtherOp = DAG.getConstant(1, VT);
7795 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7801 // Combine a constant select operand into its use:
7803 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7804 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7805 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7806 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7807 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7809 // The transform is rejected if the select doesn't have a constant operand that
7810 // is null, or all ones when AllOnes is set.
7812 // Also recognize sext/zext from i1:
7814 // (add (zext cc), x) -> (select cc (add x, 1), x)
7815 // (add (sext cc), x) -> (select cc (add x, -1), x)
7817 // These transformations eventually create predicated instructions.
7819 // @param N The node to transform.
7820 // @param Slct The N operand that is a select.
7821 // @param OtherOp The other N operand (x above).
7822 // @param DCI Context.
7823 // @param AllOnes Require the select constant to be all ones instead of null.
7824 // @returns The new node, or SDValue() on failure.
7826 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7827 TargetLowering::DAGCombinerInfo &DCI,
7828 bool AllOnes = false) {
7829 SelectionDAG &DAG = DCI.DAG;
7830 EVT VT = N->getValueType(0);
7831 SDValue NonConstantVal;
7834 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7835 NonConstantVal, DAG))
7838 // Slct is now know to be the desired identity constant when CC is true.
7839 SDValue TrueVal = OtherOp;
7840 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7841 OtherOp, NonConstantVal);
7842 // Unless SwapSelectOps says CC should be false.
7844 std::swap(TrueVal, FalseVal);
7846 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7847 CCOp, TrueVal, FalseVal);
7850 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7852 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7853 TargetLowering::DAGCombinerInfo &DCI) {
7854 SDValue N0 = N->getOperand(0);
7855 SDValue N1 = N->getOperand(1);
7856 if (N0.getNode()->hasOneUse()) {
7857 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7858 if (Result.getNode())
7861 if (N1.getNode()->hasOneUse()) {
7862 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7863 if (Result.getNode())
7869 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7870 // (only after legalization).
7871 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7872 TargetLowering::DAGCombinerInfo &DCI,
7873 const ARMSubtarget *Subtarget) {
7875 // Only perform optimization if after legalize, and if NEON is available. We
7876 // also expected both operands to be BUILD_VECTORs.
7877 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7878 || N0.getOpcode() != ISD::BUILD_VECTOR
7879 || N1.getOpcode() != ISD::BUILD_VECTOR)
7882 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7883 EVT VT = N->getValueType(0);
7884 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7887 // Check that the vector operands are of the right form.
7888 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7889 // operands, where N is the size of the formed vector.
7890 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7891 // index such that we have a pair wise add pattern.
7893 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7894 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7896 SDValue Vec = N0->getOperand(0)->getOperand(0);
7897 SDNode *V = Vec.getNode();
7898 unsigned nextIndex = 0;
7900 // For each operands to the ADD which are BUILD_VECTORs,
7901 // check to see if each of their operands are an EXTRACT_VECTOR with
7902 // the same vector and appropriate index.
7903 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7904 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7905 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7907 SDValue ExtVec0 = N0->getOperand(i);
7908 SDValue ExtVec1 = N1->getOperand(i);
7910 // First operand is the vector, verify its the same.
7911 if (V != ExtVec0->getOperand(0).getNode() ||
7912 V != ExtVec1->getOperand(0).getNode())
7915 // Second is the constant, verify its correct.
7916 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7917 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7919 // For the constant, we want to see all the even or all the odd.
7920 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7921 || C1->getZExtValue() != nextIndex+1)
7930 // Create VPADDL node.
7931 SelectionDAG &DAG = DCI.DAG;
7932 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7934 // Build operand list.
7935 SmallVector<SDValue, 8> Ops;
7936 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7937 TLI.getPointerTy()));
7939 // Input is the vector.
7942 // Get widened type and narrowed type.
7944 unsigned numElem = VT.getVectorNumElements();
7946 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7947 switch (inputLaneType.getSimpleVT().SimpleTy) {
7948 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7949 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7950 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7952 llvm_unreachable("Invalid vector element type for padd optimization.");
7955 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7956 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7957 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7960 static SDValue findMUL_LOHI(SDValue V) {
7961 if (V->getOpcode() == ISD::UMUL_LOHI ||
7962 V->getOpcode() == ISD::SMUL_LOHI)
7967 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7968 TargetLowering::DAGCombinerInfo &DCI,
7969 const ARMSubtarget *Subtarget) {
7971 if (Subtarget->isThumb1Only()) return SDValue();
7973 // Only perform the checks after legalize when the pattern is available.
7974 if (DCI.isBeforeLegalize()) return SDValue();
7976 // Look for multiply add opportunities.
7977 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7978 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7979 // a glue link from the first add to the second add.
7980 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7981 // a S/UMLAL instruction.
7984 // \ / \ [no multiline comment]
7990 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7991 SDValue AddcOp0 = AddcNode->getOperand(0);
7992 SDValue AddcOp1 = AddcNode->getOperand(1);
7994 // Check if the two operands are from the same mul_lohi node.
7995 if (AddcOp0.getNode() == AddcOp1.getNode())
7998 assert(AddcNode->getNumValues() == 2 &&
7999 AddcNode->getValueType(0) == MVT::i32 &&
8000 "Expect ADDC with two result values. First: i32");
8002 // Check that we have a glued ADDC node.
8003 if (AddcNode->getValueType(1) != MVT::Glue)
8006 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8007 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8008 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8009 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8010 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8013 // Look for the glued ADDE.
8014 SDNode* AddeNode = AddcNode->getGluedUser();
8018 // Make sure it is really an ADDE.
8019 if (AddeNode->getOpcode() != ISD::ADDE)
8022 assert(AddeNode->getNumOperands() == 3 &&
8023 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8024 "ADDE node has the wrong inputs");
8026 // Check for the triangle shape.
8027 SDValue AddeOp0 = AddeNode->getOperand(0);
8028 SDValue AddeOp1 = AddeNode->getOperand(1);
8030 // Make sure that the ADDE operands are not coming from the same node.
8031 if (AddeOp0.getNode() == AddeOp1.getNode())
8034 // Find the MUL_LOHI node walking up ADDE's operands.
8035 bool IsLeftOperandMUL = false;
8036 SDValue MULOp = findMUL_LOHI(AddeOp0);
8037 if (MULOp == SDValue())
8038 MULOp = findMUL_LOHI(AddeOp1);
8040 IsLeftOperandMUL = true;
8041 if (MULOp == SDValue())
8044 // Figure out the right opcode.
8045 unsigned Opc = MULOp->getOpcode();
8046 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8048 // Figure out the high and low input values to the MLAL node.
8049 SDValue* HiMul = &MULOp;
8050 SDValue* HiAdd = nullptr;
8051 SDValue* LoMul = nullptr;
8052 SDValue* LowAdd = nullptr;
8054 if (IsLeftOperandMUL)
8060 if (AddcOp0->getOpcode() == Opc) {
8064 if (AddcOp1->getOpcode() == Opc) {
8072 if (LoMul->getNode() != HiMul->getNode())
8075 // Create the merged node.
8076 SelectionDAG &DAG = DCI.DAG;
8078 // Build operand list.
8079 SmallVector<SDValue, 8> Ops;
8080 Ops.push_back(LoMul->getOperand(0));
8081 Ops.push_back(LoMul->getOperand(1));
8082 Ops.push_back(*LowAdd);
8083 Ops.push_back(*HiAdd);
8085 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8086 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8088 // Replace the ADDs' nodes uses by the MLA node's values.
8089 SDValue HiMLALResult(MLALNode.getNode(), 1);
8090 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8092 SDValue LoMLALResult(MLALNode.getNode(), 0);
8093 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8095 // Return original node to notify the driver to stop replacing.
8096 SDValue resNode(AddcNode, 0);
8100 /// PerformADDCCombine - Target-specific dag combine transform from
8101 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8102 static SDValue PerformADDCCombine(SDNode *N,
8103 TargetLowering::DAGCombinerInfo &DCI,
8104 const ARMSubtarget *Subtarget) {
8106 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8110 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8111 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8112 /// called with the default operands, and if that fails, with commuted
8114 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8115 TargetLowering::DAGCombinerInfo &DCI,
8116 const ARMSubtarget *Subtarget){
8118 // Attempt to create vpaddl for this add.
8119 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8120 if (Result.getNode())
8123 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8124 if (N0.getNode()->hasOneUse()) {
8125 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8126 if (Result.getNode()) return Result;
8131 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8133 static SDValue PerformADDCombine(SDNode *N,
8134 TargetLowering::DAGCombinerInfo &DCI,
8135 const ARMSubtarget *Subtarget) {
8136 SDValue N0 = N->getOperand(0);
8137 SDValue N1 = N->getOperand(1);
8139 // First try with the default operand order.
8140 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8141 if (Result.getNode())
8144 // If that didn't work, try again with the operands commuted.
8145 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8148 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8150 static SDValue PerformSUBCombine(SDNode *N,
8151 TargetLowering::DAGCombinerInfo &DCI) {
8152 SDValue N0 = N->getOperand(0);
8153 SDValue N1 = N->getOperand(1);
8155 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8156 if (N1.getNode()->hasOneUse()) {
8157 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8158 if (Result.getNode()) return Result;
8164 /// PerformVMULCombine
8165 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8166 /// special multiplier accumulator forwarding.
8172 // However, for (A + B) * (A + B),
8179 static SDValue PerformVMULCombine(SDNode *N,
8180 TargetLowering::DAGCombinerInfo &DCI,
8181 const ARMSubtarget *Subtarget) {
8182 if (!Subtarget->hasVMLxForwarding())
8185 SelectionDAG &DAG = DCI.DAG;
8186 SDValue N0 = N->getOperand(0);
8187 SDValue N1 = N->getOperand(1);
8188 unsigned Opcode = N0.getOpcode();
8189 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8190 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8191 Opcode = N1.getOpcode();
8192 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8193 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8201 EVT VT = N->getValueType(0);
8203 SDValue N00 = N0->getOperand(0);
8204 SDValue N01 = N0->getOperand(1);
8205 return DAG.getNode(Opcode, DL, VT,
8206 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8207 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8210 static SDValue PerformMULCombine(SDNode *N,
8211 TargetLowering::DAGCombinerInfo &DCI,
8212 const ARMSubtarget *Subtarget) {
8213 SelectionDAG &DAG = DCI.DAG;
8215 if (Subtarget->isThumb1Only())
8218 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8221 EVT VT = N->getValueType(0);
8222 if (VT.is64BitVector() || VT.is128BitVector())
8223 return PerformVMULCombine(N, DCI, Subtarget);
8227 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8231 int64_t MulAmt = C->getSExtValue();
8232 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8234 ShiftAmt = ShiftAmt & (32 - 1);
8235 SDValue V = N->getOperand(0);
8239 MulAmt >>= ShiftAmt;
8242 if (isPowerOf2_32(MulAmt - 1)) {
8243 // (mul x, 2^N + 1) => (add (shl x, N), x)
8244 Res = DAG.getNode(ISD::ADD, DL, VT,
8246 DAG.getNode(ISD::SHL, DL, VT,
8248 DAG.getConstant(Log2_32(MulAmt - 1),
8250 } else if (isPowerOf2_32(MulAmt + 1)) {
8251 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8252 Res = DAG.getNode(ISD::SUB, DL, VT,
8253 DAG.getNode(ISD::SHL, DL, VT,
8255 DAG.getConstant(Log2_32(MulAmt + 1),
8261 uint64_t MulAmtAbs = -MulAmt;
8262 if (isPowerOf2_32(MulAmtAbs + 1)) {
8263 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8264 Res = DAG.getNode(ISD::SUB, DL, VT,
8266 DAG.getNode(ISD::SHL, DL, VT,
8268 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8270 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8271 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8272 Res = DAG.getNode(ISD::ADD, DL, VT,
8274 DAG.getNode(ISD::SHL, DL, VT,
8276 DAG.getConstant(Log2_32(MulAmtAbs-1),
8278 Res = DAG.getNode(ISD::SUB, DL, VT,
8279 DAG.getConstant(0, MVT::i32),Res);
8286 Res = DAG.getNode(ISD::SHL, DL, VT,
8287 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8289 // Do not add new nodes to DAG combiner worklist.
8290 DCI.CombineTo(N, Res, false);
8294 static SDValue PerformANDCombine(SDNode *N,
8295 TargetLowering::DAGCombinerInfo &DCI,
8296 const ARMSubtarget *Subtarget) {
8298 // Attempt to use immediate-form VBIC
8299 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8301 EVT VT = N->getValueType(0);
8302 SelectionDAG &DAG = DCI.DAG;
8304 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8307 APInt SplatBits, SplatUndef;
8308 unsigned SplatBitSize;
8311 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8312 if (SplatBitSize <= 64) {
8314 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8315 SplatUndef.getZExtValue(), SplatBitSize,
8316 DAG, VbicVT, VT.is128BitVector(),
8318 if (Val.getNode()) {
8320 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8321 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8322 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8327 if (!Subtarget->isThumb1Only()) {
8328 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8329 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8330 if (Result.getNode())
8337 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8338 static SDValue PerformORCombine(SDNode *N,
8339 TargetLowering::DAGCombinerInfo &DCI,
8340 const ARMSubtarget *Subtarget) {
8341 // Attempt to use immediate-form VORR
8342 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8344 EVT VT = N->getValueType(0);
8345 SelectionDAG &DAG = DCI.DAG;
8347 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8350 APInt SplatBits, SplatUndef;
8351 unsigned SplatBitSize;
8353 if (BVN && Subtarget->hasNEON() &&
8354 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8355 if (SplatBitSize <= 64) {
8357 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8358 SplatUndef.getZExtValue(), SplatBitSize,
8359 DAG, VorrVT, VT.is128BitVector(),
8361 if (Val.getNode()) {
8363 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8364 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8365 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8370 if (!Subtarget->isThumb1Only()) {
8371 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8372 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8373 if (Result.getNode())
8377 // The code below optimizes (or (and X, Y), Z).
8378 // The AND operand needs to have a single user to make these optimizations
8380 SDValue N0 = N->getOperand(0);
8381 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8383 SDValue N1 = N->getOperand(1);
8385 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8386 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8387 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8389 unsigned SplatBitSize;
8392 APInt SplatBits0, SplatBits1;
8393 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8394 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8395 // Ensure that the second operand of both ands are constants
8396 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8397 HasAnyUndefs) && !HasAnyUndefs) {
8398 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8399 HasAnyUndefs) && !HasAnyUndefs) {
8400 // Ensure that the bit width of the constants are the same and that
8401 // the splat arguments are logical inverses as per the pattern we
8402 // are trying to simplify.
8403 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8404 SplatBits0 == ~SplatBits1) {
8405 // Canonicalize the vector type to make instruction selection
8407 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8408 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8412 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8418 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8421 // BFI is only available on V6T2+
8422 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8426 // 1) or (and A, mask), val => ARMbfi A, val, mask
8427 // iff (val & mask) == val
8429 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8430 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8431 // && mask == ~mask2
8432 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8433 // && ~mask == mask2
8434 // (i.e., copy a bitfield value into another bitfield of the same width)
8439 SDValue N00 = N0.getOperand(0);
8441 // The value and the mask need to be constants so we can verify this is
8442 // actually a bitfield set. If the mask is 0xffff, we can do better
8443 // via a movt instruction, so don't use BFI in that case.
8444 SDValue MaskOp = N0.getOperand(1);
8445 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8448 unsigned Mask = MaskC->getZExtValue();
8452 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8453 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8455 unsigned Val = N1C->getZExtValue();
8456 if ((Val & ~Mask) != Val)
8459 if (ARM::isBitFieldInvertedMask(Mask)) {
8460 Val >>= countTrailingZeros(~Mask);
8462 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8463 DAG.getConstant(Val, MVT::i32),
8464 DAG.getConstant(Mask, MVT::i32));
8466 // Do not add new nodes to DAG combiner worklist.
8467 DCI.CombineTo(N, Res, false);
8470 } else if (N1.getOpcode() == ISD::AND) {
8471 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8472 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8475 unsigned Mask2 = N11C->getZExtValue();
8477 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8479 if (ARM::isBitFieldInvertedMask(Mask) &&
8481 // The pack halfword instruction works better for masks that fit it,
8482 // so use that when it's available.
8483 if (Subtarget->hasT2ExtractPack() &&
8484 (Mask == 0xffff || Mask == 0xffff0000))
8487 unsigned amt = countTrailingZeros(Mask2);
8488 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8489 DAG.getConstant(amt, MVT::i32));
8490 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8491 DAG.getConstant(Mask, MVT::i32));
8492 // Do not add new nodes to DAG combiner worklist.
8493 DCI.CombineTo(N, Res, false);
8495 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8497 // The pack halfword instruction works better for masks that fit it,
8498 // so use that when it's available.
8499 if (Subtarget->hasT2ExtractPack() &&
8500 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8503 unsigned lsb = countTrailingZeros(Mask);
8504 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8505 DAG.getConstant(lsb, MVT::i32));
8506 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8507 DAG.getConstant(Mask2, MVT::i32));
8508 // Do not add new nodes to DAG combiner worklist.
8509 DCI.CombineTo(N, Res, false);
8514 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8515 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8516 ARM::isBitFieldInvertedMask(~Mask)) {
8517 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8518 // where lsb(mask) == #shamt and masked bits of B are known zero.
8519 SDValue ShAmt = N00.getOperand(1);
8520 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8521 unsigned LSB = countTrailingZeros(Mask);
8525 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8526 DAG.getConstant(~Mask, MVT::i32));
8528 // Do not add new nodes to DAG combiner worklist.
8529 DCI.CombineTo(N, Res, false);
8535 static SDValue PerformXORCombine(SDNode *N,
8536 TargetLowering::DAGCombinerInfo &DCI,
8537 const ARMSubtarget *Subtarget) {
8538 EVT VT = N->getValueType(0);
8539 SelectionDAG &DAG = DCI.DAG;
8541 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8544 if (!Subtarget->isThumb1Only()) {
8545 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8546 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8547 if (Result.getNode())
8554 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8555 /// the bits being cleared by the AND are not demanded by the BFI.
8556 static SDValue PerformBFICombine(SDNode *N,
8557 TargetLowering::DAGCombinerInfo &DCI) {
8558 SDValue N1 = N->getOperand(1);
8559 if (N1.getOpcode() == ISD::AND) {
8560 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8563 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8564 unsigned LSB = countTrailingZeros(~InvMask);
8565 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8566 unsigned Mask = (1 << Width)-1;
8567 unsigned Mask2 = N11C->getZExtValue();
8568 if ((Mask & (~Mask2)) == 0)
8569 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8570 N->getOperand(0), N1.getOperand(0),
8576 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8577 /// ARMISD::VMOVRRD.
8578 static SDValue PerformVMOVRRDCombine(SDNode *N,
8579 TargetLowering::DAGCombinerInfo &DCI,
8580 const ARMSubtarget *Subtarget) {
8581 // vmovrrd(vmovdrr x, y) -> x,y
8582 SDValue InDouble = N->getOperand(0);
8583 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8584 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8586 // vmovrrd(load f64) -> (load i32), (load i32)
8587 SDNode *InNode = InDouble.getNode();
8588 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8589 InNode->getValueType(0) == MVT::f64 &&
8590 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8591 !cast<LoadSDNode>(InNode)->isVolatile()) {
8592 // TODO: Should this be done for non-FrameIndex operands?
8593 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8595 SelectionDAG &DAG = DCI.DAG;
8597 SDValue BasePtr = LD->getBasePtr();
8598 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8599 LD->getPointerInfo(), LD->isVolatile(),
8600 LD->isNonTemporal(), LD->isInvariant(),
8601 LD->getAlignment());
8603 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8604 DAG.getConstant(4, MVT::i32));
8605 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8606 LD->getPointerInfo(), LD->isVolatile(),
8607 LD->isNonTemporal(), LD->isInvariant(),
8608 std::min(4U, LD->getAlignment() / 2));
8610 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8611 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8612 std::swap (NewLD1, NewLD2);
8613 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8620 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8621 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8622 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8623 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8624 SDValue Op0 = N->getOperand(0);
8625 SDValue Op1 = N->getOperand(1);
8626 if (Op0.getOpcode() == ISD::BITCAST)
8627 Op0 = Op0.getOperand(0);
8628 if (Op1.getOpcode() == ISD::BITCAST)
8629 Op1 = Op1.getOperand(0);
8630 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8631 Op0.getNode() == Op1.getNode() &&
8632 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8633 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8634 N->getValueType(0), Op0.getOperand(0));
8638 /// PerformSTORECombine - Target-specific dag combine xforms for
8640 static SDValue PerformSTORECombine(SDNode *N,
8641 TargetLowering::DAGCombinerInfo &DCI) {
8642 StoreSDNode *St = cast<StoreSDNode>(N);
8643 if (St->isVolatile())
8646 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8647 // pack all of the elements in one place. Next, store to memory in fewer
8649 SDValue StVal = St->getValue();
8650 EVT VT = StVal.getValueType();
8651 if (St->isTruncatingStore() && VT.isVector()) {
8652 SelectionDAG &DAG = DCI.DAG;
8653 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8654 EVT StVT = St->getMemoryVT();
8655 unsigned NumElems = VT.getVectorNumElements();
8656 assert(StVT != VT && "Cannot truncate to the same type");
8657 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8658 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8660 // From, To sizes and ElemCount must be pow of two
8661 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8663 // We are going to use the original vector elt for storing.
8664 // Accumulated smaller vector elements must be a multiple of the store size.
8665 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8667 unsigned SizeRatio = FromEltSz / ToEltSz;
8668 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8670 // Create a type on which we perform the shuffle.
8671 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8672 NumElems*SizeRatio);
8673 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8676 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8677 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8678 for (unsigned i = 0; i < NumElems; ++i)
8679 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8681 // Can't shuffle using an illegal type.
8682 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8684 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8685 DAG.getUNDEF(WideVec.getValueType()),
8687 // At this point all of the data is stored at the bottom of the
8688 // register. We now need to save it to mem.
8690 // Find the largest store unit
8691 MVT StoreType = MVT::i8;
8692 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8693 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8694 MVT Tp = (MVT::SimpleValueType)tp;
8695 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8698 // Didn't find a legal store type.
8699 if (!TLI.isTypeLegal(StoreType))
8702 // Bitcast the original vector into a vector of store-size units
8703 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8704 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8705 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8706 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8707 SmallVector<SDValue, 8> Chains;
8708 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8709 TLI.getPointerTy());
8710 SDValue BasePtr = St->getBasePtr();
8712 // Perform one or more big stores into memory.
8713 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8714 for (unsigned I = 0; I < E; I++) {
8715 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8716 StoreType, ShuffWide,
8717 DAG.getIntPtrConstant(I));
8718 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8719 St->getPointerInfo(), St->isVolatile(),
8720 St->isNonTemporal(), St->getAlignment());
8721 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8723 Chains.push_back(Ch);
8725 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8728 if (!ISD::isNormalStore(St))
8731 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8732 // ARM stores of arguments in the same cache line.
8733 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8734 StVal.getNode()->hasOneUse()) {
8735 SelectionDAG &DAG = DCI.DAG;
8736 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8738 SDValue BasePtr = St->getBasePtr();
8739 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8740 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8741 BasePtr, St->getPointerInfo(), St->isVolatile(),
8742 St->isNonTemporal(), St->getAlignment());
8744 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8745 DAG.getConstant(4, MVT::i32));
8746 return DAG.getStore(NewST1.getValue(0), DL,
8747 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8748 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8749 St->isNonTemporal(),
8750 std::min(4U, St->getAlignment() / 2));
8753 if (StVal.getValueType() != MVT::i64 ||
8754 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8757 // Bitcast an i64 store extracted from a vector to f64.
8758 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8759 SelectionDAG &DAG = DCI.DAG;
8761 SDValue IntVec = StVal.getOperand(0);
8762 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8763 IntVec.getValueType().getVectorNumElements());
8764 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8765 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8766 Vec, StVal.getOperand(1));
8768 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8769 // Make the DAGCombiner fold the bitcasts.
8770 DCI.AddToWorklist(Vec.getNode());
8771 DCI.AddToWorklist(ExtElt.getNode());
8772 DCI.AddToWorklist(V.getNode());
8773 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8774 St->getPointerInfo(), St->isVolatile(),
8775 St->isNonTemporal(), St->getAlignment(),
8779 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8780 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8781 /// i64 vector to have f64 elements, since the value can then be loaded
8782 /// directly into a VFP register.
8783 static bool hasNormalLoadOperand(SDNode *N) {
8784 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8785 for (unsigned i = 0; i < NumElts; ++i) {
8786 SDNode *Elt = N->getOperand(i).getNode();
8787 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8793 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8794 /// ISD::BUILD_VECTOR.
8795 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8796 TargetLowering::DAGCombinerInfo &DCI,
8797 const ARMSubtarget *Subtarget) {
8798 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8799 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8800 // into a pair of GPRs, which is fine when the value is used as a scalar,
8801 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8802 SelectionDAG &DAG = DCI.DAG;
8803 if (N->getNumOperands() == 2) {
8804 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8809 // Load i64 elements as f64 values so that type legalization does not split
8810 // them up into i32 values.
8811 EVT VT = N->getValueType(0);
8812 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8815 SmallVector<SDValue, 8> Ops;
8816 unsigned NumElts = VT.getVectorNumElements();
8817 for (unsigned i = 0; i < NumElts; ++i) {
8818 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8820 // Make the DAGCombiner fold the bitcast.
8821 DCI.AddToWorklist(V.getNode());
8823 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8824 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8825 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8828 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8830 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8831 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8832 // At that time, we may have inserted bitcasts from integer to float.
8833 // If these bitcasts have survived DAGCombine, change the lowering of this
8834 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8835 // force to use floating point types.
8837 // Make sure we can change the type of the vector.
8838 // This is possible iff:
8839 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8840 // 1.1. Vector is used only once.
8841 // 1.2. Use is a bit convert to an integer type.
8842 // 2. The size of its operands are 32-bits (64-bits are not legal).
8843 EVT VT = N->getValueType(0);
8844 EVT EltVT = VT.getVectorElementType();
8846 // Check 1.1. and 2.
8847 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8850 // By construction, the input type must be float.
8851 assert(EltVT == MVT::f32 && "Unexpected type!");
8854 SDNode *Use = *N->use_begin();
8855 if (Use->getOpcode() != ISD::BITCAST ||
8856 Use->getValueType(0).isFloatingPoint())
8859 // Check profitability.
8860 // Model is, if more than half of the relevant operands are bitcast from
8861 // i32, turn the build_vector into a sequence of insert_vector_elt.
8862 // Relevant operands are everything that is not statically
8863 // (i.e., at compile time) bitcasted.
8864 unsigned NumOfBitCastedElts = 0;
8865 unsigned NumElts = VT.getVectorNumElements();
8866 unsigned NumOfRelevantElts = NumElts;
8867 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8868 SDValue Elt = N->getOperand(Idx);
8869 if (Elt->getOpcode() == ISD::BITCAST) {
8870 // Assume only bit cast to i32 will go away.
8871 if (Elt->getOperand(0).getValueType() == MVT::i32)
8872 ++NumOfBitCastedElts;
8873 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8874 // Constants are statically casted, thus do not count them as
8875 // relevant operands.
8876 --NumOfRelevantElts;
8879 // Check if more than half of the elements require a non-free bitcast.
8880 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8883 SelectionDAG &DAG = DCI.DAG;
8884 // Create the new vector type.
8885 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8886 // Check if the type is legal.
8887 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8888 if (!TLI.isTypeLegal(VecVT))
8892 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8893 // => BITCAST INSERT_VECTOR_ELT
8894 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8896 SDValue Vec = DAG.getUNDEF(VecVT);
8898 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8899 SDValue V = N->getOperand(Idx);
8900 if (V.getOpcode() == ISD::UNDEF)
8902 if (V.getOpcode() == ISD::BITCAST &&
8903 V->getOperand(0).getValueType() == MVT::i32)
8904 // Fold obvious case.
8905 V = V.getOperand(0);
8907 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8908 // Make the DAGCombiner fold the bitcasts.
8909 DCI.AddToWorklist(V.getNode());
8911 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8912 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8914 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8915 // Make the DAGCombiner fold the bitcasts.
8916 DCI.AddToWorklist(Vec.getNode());
8920 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8921 /// ISD::INSERT_VECTOR_ELT.
8922 static SDValue PerformInsertEltCombine(SDNode *N,
8923 TargetLowering::DAGCombinerInfo &DCI) {
8924 // Bitcast an i64 load inserted into a vector to f64.
8925 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8926 EVT VT = N->getValueType(0);
8927 SDNode *Elt = N->getOperand(1).getNode();
8928 if (VT.getVectorElementType() != MVT::i64 ||
8929 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8932 SelectionDAG &DAG = DCI.DAG;
8934 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8935 VT.getVectorNumElements());
8936 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8937 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8938 // Make the DAGCombiner fold the bitcasts.
8939 DCI.AddToWorklist(Vec.getNode());
8940 DCI.AddToWorklist(V.getNode());
8941 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8942 Vec, V, N->getOperand(2));
8943 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8946 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8947 /// ISD::VECTOR_SHUFFLE.
8948 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8949 // The LLVM shufflevector instruction does not require the shuffle mask
8950 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8951 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8952 // operands do not match the mask length, they are extended by concatenating
8953 // them with undef vectors. That is probably the right thing for other
8954 // targets, but for NEON it is better to concatenate two double-register
8955 // size vector operands into a single quad-register size vector. Do that
8956 // transformation here:
8957 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8958 // shuffle(concat(v1, v2), undef)
8959 SDValue Op0 = N->getOperand(0);
8960 SDValue Op1 = N->getOperand(1);
8961 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8962 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8963 Op0.getNumOperands() != 2 ||
8964 Op1.getNumOperands() != 2)
8966 SDValue Concat0Op1 = Op0.getOperand(1);
8967 SDValue Concat1Op1 = Op1.getOperand(1);
8968 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8969 Concat1Op1.getOpcode() != ISD::UNDEF)
8971 // Skip the transformation if any of the types are illegal.
8972 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8973 EVT VT = N->getValueType(0);
8974 if (!TLI.isTypeLegal(VT) ||
8975 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8976 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8979 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8980 Op0.getOperand(0), Op1.getOperand(0));
8981 // Translate the shuffle mask.
8982 SmallVector<int, 16> NewMask;
8983 unsigned NumElts = VT.getVectorNumElements();
8984 unsigned HalfElts = NumElts/2;
8985 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8986 for (unsigned n = 0; n < NumElts; ++n) {
8987 int MaskElt = SVN->getMaskElt(n);
8989 if (MaskElt < (int)HalfElts)
8991 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8992 NewElt = HalfElts + MaskElt - NumElts;
8993 NewMask.push_back(NewElt);
8995 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8996 DAG.getUNDEF(VT), NewMask.data());
8999 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9000 /// NEON load/store intrinsics to merge base address updates.
9001 static SDValue CombineBaseUpdate(SDNode *N,
9002 TargetLowering::DAGCombinerInfo &DCI) {
9003 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9006 SelectionDAG &DAG = DCI.DAG;
9007 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9008 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9009 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9010 SDValue Addr = N->getOperand(AddrOpIdx);
9012 // Search for a use of the address operand that is an increment.
9013 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9014 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9016 if (User->getOpcode() != ISD::ADD ||
9017 UI.getUse().getResNo() != Addr.getResNo())
9020 // Check that the add is independent of the load/store. Otherwise, folding
9021 // it would create a cycle.
9022 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9025 // Find the new opcode for the updating load/store.
9027 bool isLaneOp = false;
9028 unsigned NewOpc = 0;
9029 unsigned NumVecs = 0;
9031 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9033 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9034 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9036 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9038 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9040 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9042 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9043 NumVecs = 2; isLaneOp = true; break;
9044 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9045 NumVecs = 3; isLaneOp = true; break;
9046 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9047 NumVecs = 4; isLaneOp = true; break;
9048 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9049 NumVecs = 1; isLoad = false; break;
9050 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9051 NumVecs = 2; isLoad = false; break;
9052 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9053 NumVecs = 3; isLoad = false; break;
9054 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9055 NumVecs = 4; isLoad = false; break;
9056 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9057 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9058 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9059 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9060 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9061 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9065 switch (N->getOpcode()) {
9066 default: llvm_unreachable("unexpected opcode for Neon base update");
9067 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9068 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9069 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9073 // Find the size of memory referenced by the load/store.
9076 VecTy = N->getValueType(0);
9078 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9079 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9081 NumBytes /= VecTy.getVectorNumElements();
9083 // If the increment is a constant, it must match the memory ref size.
9084 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9085 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9086 uint64_t IncVal = CInc->getZExtValue();
9087 if (IncVal != NumBytes)
9089 } else if (NumBytes >= 3 * 16) {
9090 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9091 // separate instructions that make it harder to use a non-constant update.
9095 // Create the new updating load/store node.
9097 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9099 for (n = 0; n < NumResultVecs; ++n)
9101 Tys[n++] = MVT::i32;
9102 Tys[n] = MVT::Other;
9103 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9104 SmallVector<SDValue, 8> Ops;
9105 Ops.push_back(N->getOperand(0)); // incoming chain
9106 Ops.push_back(N->getOperand(AddrOpIdx));
9108 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9109 Ops.push_back(N->getOperand(i));
9111 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9112 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9113 Ops, MemInt->getMemoryVT(),
9114 MemInt->getMemOperand());
9117 std::vector<SDValue> NewResults;
9118 for (unsigned i = 0; i < NumResultVecs; ++i) {
9119 NewResults.push_back(SDValue(UpdN.getNode(), i));
9121 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9122 DCI.CombineTo(N, NewResults);
9123 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9130 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9131 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9132 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9134 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9135 SelectionDAG &DAG = DCI.DAG;
9136 EVT VT = N->getValueType(0);
9137 // vldN-dup instructions only support 64-bit vectors for N > 1.
9138 if (!VT.is64BitVector())
9141 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9142 SDNode *VLD = N->getOperand(0).getNode();
9143 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9145 unsigned NumVecs = 0;
9146 unsigned NewOpc = 0;
9147 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9148 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9150 NewOpc = ARMISD::VLD2DUP;
9151 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9153 NewOpc = ARMISD::VLD3DUP;
9154 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9156 NewOpc = ARMISD::VLD4DUP;
9161 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9162 // numbers match the load.
9163 unsigned VLDLaneNo =
9164 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9165 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9167 // Ignore uses of the chain result.
9168 if (UI.getUse().getResNo() == NumVecs)
9171 if (User->getOpcode() != ARMISD::VDUPLANE ||
9172 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9176 // Create the vldN-dup node.
9179 for (n = 0; n < NumVecs; ++n)
9181 Tys[n] = MVT::Other;
9182 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9183 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9184 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9185 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9186 Ops, VLDMemInt->getMemoryVT(),
9187 VLDMemInt->getMemOperand());
9190 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9192 unsigned ResNo = UI.getUse().getResNo();
9193 // Ignore uses of the chain result.
9194 if (ResNo == NumVecs)
9197 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9200 // Now the vldN-lane intrinsic is dead except for its chain result.
9201 // Update uses of the chain.
9202 std::vector<SDValue> VLDDupResults;
9203 for (unsigned n = 0; n < NumVecs; ++n)
9204 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9205 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9206 DCI.CombineTo(VLD, VLDDupResults);
9211 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9212 /// ARMISD::VDUPLANE.
9213 static SDValue PerformVDUPLANECombine(SDNode *N,
9214 TargetLowering::DAGCombinerInfo &DCI) {
9215 SDValue Op = N->getOperand(0);
9217 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9218 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9219 if (CombineVLDDUP(N, DCI))
9220 return SDValue(N, 0);
9222 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9223 // redundant. Ignore bit_converts for now; element sizes are checked below.
9224 while (Op.getOpcode() == ISD::BITCAST)
9225 Op = Op.getOperand(0);
9226 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9229 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9230 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9231 // The canonical VMOV for a zero vector uses a 32-bit element size.
9232 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9234 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9236 EVT VT = N->getValueType(0);
9237 if (EltSize > VT.getVectorElementType().getSizeInBits())
9240 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9243 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9244 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9245 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9249 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9251 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9256 APFloat APF = C->getValueAPF();
9257 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9258 != APFloat::opOK || !isExact)
9261 c0 = (I == 0) ? cN : c0;
9262 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9269 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9270 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9271 /// when the VMUL has a constant operand that is a power of 2.
9273 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9274 /// vmul.f32 d16, d17, d16
9275 /// vcvt.s32.f32 d16, d16
9277 /// vcvt.s32.f32 d16, d16, #3
9278 static SDValue PerformVCVTCombine(SDNode *N,
9279 TargetLowering::DAGCombinerInfo &DCI,
9280 const ARMSubtarget *Subtarget) {
9281 SelectionDAG &DAG = DCI.DAG;
9282 SDValue Op = N->getOperand(0);
9284 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9285 Op.getOpcode() != ISD::FMUL)
9289 SDValue N0 = Op->getOperand(0);
9290 SDValue ConstVec = Op->getOperand(1);
9291 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9293 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9294 !isConstVecPow2(ConstVec, isSigned, C))
9297 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9298 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9299 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9300 // These instructions only exist converting from f32 to i32. We can handle
9301 // smaller integers by generating an extra truncate, but larger ones would
9306 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9307 Intrinsic::arm_neon_vcvtfp2fxu;
9308 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9309 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9310 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9311 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9312 DAG.getConstant(Log2_64(C), MVT::i32));
9314 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9315 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9320 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9321 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9322 /// when the VDIV has a constant operand that is a power of 2.
9324 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9325 /// vcvt.f32.s32 d16, d16
9326 /// vdiv.f32 d16, d17, d16
9328 /// vcvt.f32.s32 d16, d16, #3
9329 static SDValue PerformVDIVCombine(SDNode *N,
9330 TargetLowering::DAGCombinerInfo &DCI,
9331 const ARMSubtarget *Subtarget) {
9332 SelectionDAG &DAG = DCI.DAG;
9333 SDValue Op = N->getOperand(0);
9334 unsigned OpOpcode = Op.getNode()->getOpcode();
9336 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9337 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9341 SDValue ConstVec = N->getOperand(1);
9342 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9344 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9345 !isConstVecPow2(ConstVec, isSigned, C))
9348 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9349 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9350 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9351 // These instructions only exist converting from i32 to f32. We can handle
9352 // smaller integers by generating an extra extend, but larger ones would
9357 SDValue ConvInput = Op.getOperand(0);
9358 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9359 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9360 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9361 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9364 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9365 Intrinsic::arm_neon_vcvtfxu2fp;
9366 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9368 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9369 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9372 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9373 /// operand of a vector shift operation, where all the elements of the
9374 /// build_vector must have the same constant integer value.
9375 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9376 // Ignore bit_converts.
9377 while (Op.getOpcode() == ISD::BITCAST)
9378 Op = Op.getOperand(0);
9379 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9380 APInt SplatBits, SplatUndef;
9381 unsigned SplatBitSize;
9383 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9384 HasAnyUndefs, ElementBits) ||
9385 SplatBitSize > ElementBits)
9387 Cnt = SplatBits.getSExtValue();
9391 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9392 /// operand of a vector shift left operation. That value must be in the range:
9393 /// 0 <= Value < ElementBits for a left shift; or
9394 /// 0 <= Value <= ElementBits for a long left shift.
9395 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9396 assert(VT.isVector() && "vector shift count is not a vector type");
9397 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9398 if (! getVShiftImm(Op, ElementBits, Cnt))
9400 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9403 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9404 /// operand of a vector shift right operation. For a shift opcode, the value
9405 /// is positive, but for an intrinsic the value count must be negative. The
9406 /// absolute value must be in the range:
9407 /// 1 <= |Value| <= ElementBits for a right shift; or
9408 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9409 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9411 assert(VT.isVector() && "vector shift count is not a vector type");
9412 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9413 if (! getVShiftImm(Op, ElementBits, Cnt))
9417 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9420 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9421 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9422 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9425 // Don't do anything for most intrinsics.
9428 // Vector shifts: check for immediate versions and lower them.
9429 // Note: This is done during DAG combining instead of DAG legalizing because
9430 // the build_vectors for 64-bit vector element shift counts are generally
9431 // not legal, and it is hard to see their values after they get legalized to
9432 // loads from a constant pool.
9433 case Intrinsic::arm_neon_vshifts:
9434 case Intrinsic::arm_neon_vshiftu:
9435 case Intrinsic::arm_neon_vrshifts:
9436 case Intrinsic::arm_neon_vrshiftu:
9437 case Intrinsic::arm_neon_vrshiftn:
9438 case Intrinsic::arm_neon_vqshifts:
9439 case Intrinsic::arm_neon_vqshiftu:
9440 case Intrinsic::arm_neon_vqshiftsu:
9441 case Intrinsic::arm_neon_vqshiftns:
9442 case Intrinsic::arm_neon_vqshiftnu:
9443 case Intrinsic::arm_neon_vqshiftnsu:
9444 case Intrinsic::arm_neon_vqrshiftns:
9445 case Intrinsic::arm_neon_vqrshiftnu:
9446 case Intrinsic::arm_neon_vqrshiftnsu: {
9447 EVT VT = N->getOperand(1).getValueType();
9449 unsigned VShiftOpc = 0;
9452 case Intrinsic::arm_neon_vshifts:
9453 case Intrinsic::arm_neon_vshiftu:
9454 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9455 VShiftOpc = ARMISD::VSHL;
9458 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9459 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9460 ARMISD::VSHRs : ARMISD::VSHRu);
9465 case Intrinsic::arm_neon_vrshifts:
9466 case Intrinsic::arm_neon_vrshiftu:
9467 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9471 case Intrinsic::arm_neon_vqshifts:
9472 case Intrinsic::arm_neon_vqshiftu:
9473 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9477 case Intrinsic::arm_neon_vqshiftsu:
9478 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9480 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9482 case Intrinsic::arm_neon_vrshiftn:
9483 case Intrinsic::arm_neon_vqshiftns:
9484 case Intrinsic::arm_neon_vqshiftnu:
9485 case Intrinsic::arm_neon_vqshiftnsu:
9486 case Intrinsic::arm_neon_vqrshiftns:
9487 case Intrinsic::arm_neon_vqrshiftnu:
9488 case Intrinsic::arm_neon_vqrshiftnsu:
9489 // Narrowing shifts require an immediate right shift.
9490 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9492 llvm_unreachable("invalid shift count for narrowing vector shift "
9496 llvm_unreachable("unhandled vector shift");
9500 case Intrinsic::arm_neon_vshifts:
9501 case Intrinsic::arm_neon_vshiftu:
9502 // Opcode already set above.
9504 case Intrinsic::arm_neon_vrshifts:
9505 VShiftOpc = ARMISD::VRSHRs; break;
9506 case Intrinsic::arm_neon_vrshiftu:
9507 VShiftOpc = ARMISD::VRSHRu; break;
9508 case Intrinsic::arm_neon_vrshiftn:
9509 VShiftOpc = ARMISD::VRSHRN; break;
9510 case Intrinsic::arm_neon_vqshifts:
9511 VShiftOpc = ARMISD::VQSHLs; break;
9512 case Intrinsic::arm_neon_vqshiftu:
9513 VShiftOpc = ARMISD::VQSHLu; break;
9514 case Intrinsic::arm_neon_vqshiftsu:
9515 VShiftOpc = ARMISD::VQSHLsu; break;
9516 case Intrinsic::arm_neon_vqshiftns:
9517 VShiftOpc = ARMISD::VQSHRNs; break;
9518 case Intrinsic::arm_neon_vqshiftnu:
9519 VShiftOpc = ARMISD::VQSHRNu; break;
9520 case Intrinsic::arm_neon_vqshiftnsu:
9521 VShiftOpc = ARMISD::VQSHRNsu; break;
9522 case Intrinsic::arm_neon_vqrshiftns:
9523 VShiftOpc = ARMISD::VQRSHRNs; break;
9524 case Intrinsic::arm_neon_vqrshiftnu:
9525 VShiftOpc = ARMISD::VQRSHRNu; break;
9526 case Intrinsic::arm_neon_vqrshiftnsu:
9527 VShiftOpc = ARMISD::VQRSHRNsu; break;
9530 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9531 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9534 case Intrinsic::arm_neon_vshiftins: {
9535 EVT VT = N->getOperand(1).getValueType();
9537 unsigned VShiftOpc = 0;
9539 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9540 VShiftOpc = ARMISD::VSLI;
9541 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9542 VShiftOpc = ARMISD::VSRI;
9544 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9547 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9548 N->getOperand(1), N->getOperand(2),
9549 DAG.getConstant(Cnt, MVT::i32));
9552 case Intrinsic::arm_neon_vqrshifts:
9553 case Intrinsic::arm_neon_vqrshiftu:
9554 // No immediate versions of these to check for.
9561 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9562 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9563 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9564 /// vector element shift counts are generally not legal, and it is hard to see
9565 /// their values after they get legalized to loads from a constant pool.
9566 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9567 const ARMSubtarget *ST) {
9568 EVT VT = N->getValueType(0);
9569 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9570 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9571 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9572 SDValue N1 = N->getOperand(1);
9573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9574 SDValue N0 = N->getOperand(0);
9575 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9576 DAG.MaskedValueIsZero(N0.getOperand(0),
9577 APInt::getHighBitsSet(32, 16)))
9578 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9582 // Nothing to be done for scalar shifts.
9583 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9584 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9587 assert(ST->hasNEON() && "unexpected vector shift");
9590 switch (N->getOpcode()) {
9591 default: llvm_unreachable("unexpected shift opcode");
9594 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9595 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9596 DAG.getConstant(Cnt, MVT::i32));
9601 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9602 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9603 ARMISD::VSHRs : ARMISD::VSHRu);
9604 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9605 DAG.getConstant(Cnt, MVT::i32));
9611 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9612 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9613 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9614 const ARMSubtarget *ST) {
9615 SDValue N0 = N->getOperand(0);
9617 // Check for sign- and zero-extensions of vector extract operations of 8-
9618 // and 16-bit vector elements. NEON supports these directly. They are
9619 // handled during DAG combining because type legalization will promote them
9620 // to 32-bit types and it is messy to recognize the operations after that.
9621 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9622 SDValue Vec = N0.getOperand(0);
9623 SDValue Lane = N0.getOperand(1);
9624 EVT VT = N->getValueType(0);
9625 EVT EltVT = N0.getValueType();
9626 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9628 if (VT == MVT::i32 &&
9629 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9630 TLI.isTypeLegal(Vec.getValueType()) &&
9631 isa<ConstantSDNode>(Lane)) {
9634 switch (N->getOpcode()) {
9635 default: llvm_unreachable("unexpected opcode");
9636 case ISD::SIGN_EXTEND:
9637 Opc = ARMISD::VGETLANEs;
9639 case ISD::ZERO_EXTEND:
9640 case ISD::ANY_EXTEND:
9641 Opc = ARMISD::VGETLANEu;
9644 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9651 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9652 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9653 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9654 const ARMSubtarget *ST) {
9655 // If the target supports NEON, try to use vmax/vmin instructions for f32
9656 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9657 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9658 // a NaN; only do the transformation when it matches that behavior.
9660 // For now only do this when using NEON for FP operations; if using VFP, it
9661 // is not obvious that the benefit outweighs the cost of switching to the
9663 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9664 N->getValueType(0) != MVT::f32)
9667 SDValue CondLHS = N->getOperand(0);
9668 SDValue CondRHS = N->getOperand(1);
9669 SDValue LHS = N->getOperand(2);
9670 SDValue RHS = N->getOperand(3);
9671 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9673 unsigned Opcode = 0;
9675 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9676 IsReversed = false; // x CC y ? x : y
9677 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9678 IsReversed = true ; // x CC y ? y : x
9692 // If LHS is NaN, an ordered comparison will be false and the result will
9693 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9694 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9695 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9696 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9698 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9699 // will return -0, so vmin can only be used for unsafe math or if one of
9700 // the operands is known to be nonzero.
9701 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9702 !DAG.getTarget().Options.UnsafeFPMath &&
9703 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9705 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9714 // If LHS is NaN, an ordered comparison will be false and the result will
9715 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9716 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9717 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9718 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9720 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9721 // will return +0, so vmax can only be used for unsafe math or if one of
9722 // the operands is known to be nonzero.
9723 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9724 !DAG.getTarget().Options.UnsafeFPMath &&
9725 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9727 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9733 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9736 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9738 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9739 SDValue Cmp = N->getOperand(4);
9740 if (Cmp.getOpcode() != ARMISD::CMPZ)
9741 // Only looking at EQ and NE cases.
9744 EVT VT = N->getValueType(0);
9746 SDValue LHS = Cmp.getOperand(0);
9747 SDValue RHS = Cmp.getOperand(1);
9748 SDValue FalseVal = N->getOperand(0);
9749 SDValue TrueVal = N->getOperand(1);
9750 SDValue ARMcc = N->getOperand(2);
9751 ARMCC::CondCodes CC =
9752 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9770 /// FIXME: Turn this into a target neutral optimization?
9772 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9773 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9774 N->getOperand(3), Cmp);
9775 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9777 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9778 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9779 N->getOperand(3), NewCmp);
9782 if (Res.getNode()) {
9783 APInt KnownZero, KnownOne;
9784 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9785 // Capture demanded bits information that would be otherwise lost.
9786 if (KnownZero == 0xfffffffe)
9787 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9788 DAG.getValueType(MVT::i1));
9789 else if (KnownZero == 0xffffff00)
9790 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9791 DAG.getValueType(MVT::i8));
9792 else if (KnownZero == 0xffff0000)
9793 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9794 DAG.getValueType(MVT::i16));
9800 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9801 DAGCombinerInfo &DCI) const {
9802 switch (N->getOpcode()) {
9804 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9805 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9806 case ISD::SUB: return PerformSUBCombine(N, DCI);
9807 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9808 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9809 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9810 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9811 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9812 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9813 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9814 case ISD::STORE: return PerformSTORECombine(N, DCI);
9815 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9816 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9817 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9818 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9819 case ISD::FP_TO_SINT:
9820 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9821 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9822 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9825 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9826 case ISD::SIGN_EXTEND:
9827 case ISD::ZERO_EXTEND:
9828 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9829 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9830 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9831 case ARMISD::VLD2DUP:
9832 case ARMISD::VLD3DUP:
9833 case ARMISD::VLD4DUP:
9834 return CombineBaseUpdate(N, DCI);
9835 case ARMISD::BUILD_VECTOR:
9836 return PerformARMBUILD_VECTORCombine(N, DCI);
9837 case ISD::INTRINSIC_VOID:
9838 case ISD::INTRINSIC_W_CHAIN:
9839 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9840 case Intrinsic::arm_neon_vld1:
9841 case Intrinsic::arm_neon_vld2:
9842 case Intrinsic::arm_neon_vld3:
9843 case Intrinsic::arm_neon_vld4:
9844 case Intrinsic::arm_neon_vld2lane:
9845 case Intrinsic::arm_neon_vld3lane:
9846 case Intrinsic::arm_neon_vld4lane:
9847 case Intrinsic::arm_neon_vst1:
9848 case Intrinsic::arm_neon_vst2:
9849 case Intrinsic::arm_neon_vst3:
9850 case Intrinsic::arm_neon_vst4:
9851 case Intrinsic::arm_neon_vst2lane:
9852 case Intrinsic::arm_neon_vst3lane:
9853 case Intrinsic::arm_neon_vst4lane:
9854 return CombineBaseUpdate(N, DCI);
9862 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9864 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9867 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9871 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9872 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9874 switch (VT.getSimpleVT().SimpleTy) {
9880 // Unaligned access can use (for example) LRDB, LRDH, LDR
9881 if (AllowsUnaligned) {
9883 *Fast = Subtarget->hasV7Ops();
9890 // For any little-endian targets with neon, we can support unaligned ld/st
9891 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9892 // A big-endian target may also explicitly support unaligned accesses
9893 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9903 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9904 unsigned AlignCheck) {
9905 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9906 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9909 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9910 unsigned DstAlign, unsigned SrcAlign,
9911 bool IsMemset, bool ZeroMemset,
9913 MachineFunction &MF) const {
9914 const Function *F = MF.getFunction();
9916 // See if we can use NEON instructions for this...
9917 if ((!IsMemset || ZeroMemset) &&
9918 Subtarget->hasNEON() &&
9919 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9920 Attribute::NoImplicitFloat)) {
9923 (memOpAlign(SrcAlign, DstAlign, 16) ||
9924 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9926 } else if (Size >= 8 &&
9927 (memOpAlign(SrcAlign, DstAlign, 8) ||
9928 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9934 // Lowering to i32/i16 if the size permits.
9940 // Let the target-independent logic figure it out.
9944 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9945 if (Val.getOpcode() != ISD::LOAD)
9948 EVT VT1 = Val.getValueType();
9949 if (!VT1.isSimple() || !VT1.isInteger() ||
9950 !VT2.isSimple() || !VT2.isInteger())
9953 switch (VT1.getSimpleVT().SimpleTy) {
9958 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9965 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9966 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9969 if (!isTypeLegal(EVT::getEVT(Ty1)))
9972 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9974 // Assuming the caller doesn't have a zeroext or signext return parameter,
9975 // truncation all the way down to i1 is valid.
9980 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9985 switch (VT.getSimpleVT().SimpleTy) {
9986 default: return false;
10001 if ((V & (Scale - 1)) != 0)
10004 return V == (V & ((1LL << 5) - 1));
10007 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10008 const ARMSubtarget *Subtarget) {
10009 bool isNeg = false;
10015 switch (VT.getSimpleVT().SimpleTy) {
10016 default: return false;
10021 // + imm12 or - imm8
10023 return V == (V & ((1LL << 8) - 1));
10024 return V == (V & ((1LL << 12) - 1));
10027 // Same as ARM mode. FIXME: NEON?
10028 if (!Subtarget->hasVFP2())
10033 return V == (V & ((1LL << 8) - 1));
10037 /// isLegalAddressImmediate - Return true if the integer value can be used
10038 /// as the offset of the target addressing mode for load / store of the
10040 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10041 const ARMSubtarget *Subtarget) {
10045 if (!VT.isSimple())
10048 if (Subtarget->isThumb1Only())
10049 return isLegalT1AddressImmediate(V, VT);
10050 else if (Subtarget->isThumb2())
10051 return isLegalT2AddressImmediate(V, VT, Subtarget);
10056 switch (VT.getSimpleVT().SimpleTy) {
10057 default: return false;
10062 return V == (V & ((1LL << 12) - 1));
10065 return V == (V & ((1LL << 8) - 1));
10068 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10073 return V == (V & ((1LL << 8) - 1));
10077 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10079 int Scale = AM.Scale;
10083 switch (VT.getSimpleVT().SimpleTy) {
10084 default: return false;
10092 Scale = Scale & ~1;
10093 return Scale == 2 || Scale == 4 || Scale == 8;
10096 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10100 // Note, we allow "void" uses (basically, uses that aren't loads or
10101 // stores), because arm allows folding a scale into many arithmetic
10102 // operations. This should be made more precise and revisited later.
10104 // Allow r << imm, but the imm has to be a multiple of two.
10105 if (Scale & 1) return false;
10106 return isPowerOf2_32(Scale);
10110 /// isLegalAddressingMode - Return true if the addressing mode represented
10111 /// by AM is legal for this target, for a load/store of the specified type.
10112 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10114 EVT VT = getValueType(Ty, true);
10115 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10118 // Can never fold addr of global into load/store.
10122 switch (AM.Scale) {
10123 case 0: // no scale reg, must be "r+i" or "r", or "i".
10126 if (Subtarget->isThumb1Only())
10130 // ARM doesn't support any R+R*scale+imm addr modes.
10134 if (!VT.isSimple())
10137 if (Subtarget->isThumb2())
10138 return isLegalT2ScaledAddressingMode(AM, VT);
10140 int Scale = AM.Scale;
10141 switch (VT.getSimpleVT().SimpleTy) {
10142 default: return false;
10146 if (Scale < 0) Scale = -Scale;
10150 return isPowerOf2_32(Scale & ~1);
10154 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10159 // Note, we allow "void" uses (basically, uses that aren't loads or
10160 // stores), because arm allows folding a scale into many arithmetic
10161 // operations. This should be made more precise and revisited later.
10163 // Allow r << imm, but the imm has to be a multiple of two.
10164 if (Scale & 1) return false;
10165 return isPowerOf2_32(Scale);
10171 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10172 /// icmp immediate, that is the target has icmp instructions which can compare
10173 /// a register against the immediate without having to materialize the
10174 /// immediate into a register.
10175 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10176 // Thumb2 and ARM modes can use cmn for negative immediates.
10177 if (!Subtarget->isThumb())
10178 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10179 if (Subtarget->isThumb2())
10180 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10181 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10182 return Imm >= 0 && Imm <= 255;
10185 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10186 /// *or sub* immediate, that is the target has add or sub instructions which can
10187 /// add a register with the immediate without having to materialize the
10188 /// immediate into a register.
10189 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10190 // Same encoding for add/sub, just flip the sign.
10191 int64_t AbsImm = llvm::abs64(Imm);
10192 if (!Subtarget->isThumb())
10193 return ARM_AM::getSOImmVal(AbsImm) != -1;
10194 if (Subtarget->isThumb2())
10195 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10196 // Thumb1 only has 8-bit unsigned immediate.
10197 return AbsImm >= 0 && AbsImm <= 255;
10200 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10201 bool isSEXTLoad, SDValue &Base,
10202 SDValue &Offset, bool &isInc,
10203 SelectionDAG &DAG) {
10204 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10207 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10208 // AddressingMode 3
10209 Base = Ptr->getOperand(0);
10210 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10211 int RHSC = (int)RHS->getZExtValue();
10212 if (RHSC < 0 && RHSC > -256) {
10213 assert(Ptr->getOpcode() == ISD::ADD);
10215 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10219 isInc = (Ptr->getOpcode() == ISD::ADD);
10220 Offset = Ptr->getOperand(1);
10222 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10223 // AddressingMode 2
10224 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10225 int RHSC = (int)RHS->getZExtValue();
10226 if (RHSC < 0 && RHSC > -0x1000) {
10227 assert(Ptr->getOpcode() == ISD::ADD);
10229 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10230 Base = Ptr->getOperand(0);
10235 if (Ptr->getOpcode() == ISD::ADD) {
10237 ARM_AM::ShiftOpc ShOpcVal=
10238 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10239 if (ShOpcVal != ARM_AM::no_shift) {
10240 Base = Ptr->getOperand(1);
10241 Offset = Ptr->getOperand(0);
10243 Base = Ptr->getOperand(0);
10244 Offset = Ptr->getOperand(1);
10249 isInc = (Ptr->getOpcode() == ISD::ADD);
10250 Base = Ptr->getOperand(0);
10251 Offset = Ptr->getOperand(1);
10255 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10259 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10260 bool isSEXTLoad, SDValue &Base,
10261 SDValue &Offset, bool &isInc,
10262 SelectionDAG &DAG) {
10263 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10266 Base = Ptr->getOperand(0);
10267 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10268 int RHSC = (int)RHS->getZExtValue();
10269 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10270 assert(Ptr->getOpcode() == ISD::ADD);
10272 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10274 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10275 isInc = Ptr->getOpcode() == ISD::ADD;
10276 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10284 /// getPreIndexedAddressParts - returns true by value, base pointer and
10285 /// offset pointer and addressing mode by reference if the node's address
10286 /// can be legally represented as pre-indexed load / store address.
10288 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10290 ISD::MemIndexedMode &AM,
10291 SelectionDAG &DAG) const {
10292 if (Subtarget->isThumb1Only())
10297 bool isSEXTLoad = false;
10298 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10299 Ptr = LD->getBasePtr();
10300 VT = LD->getMemoryVT();
10301 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10302 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10303 Ptr = ST->getBasePtr();
10304 VT = ST->getMemoryVT();
10309 bool isLegal = false;
10310 if (Subtarget->isThumb2())
10311 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10312 Offset, isInc, DAG);
10314 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10315 Offset, isInc, DAG);
10319 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10323 /// getPostIndexedAddressParts - returns true by value, base pointer and
10324 /// offset pointer and addressing mode by reference if this node can be
10325 /// combined with a load / store to form a post-indexed load / store.
10326 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10329 ISD::MemIndexedMode &AM,
10330 SelectionDAG &DAG) const {
10331 if (Subtarget->isThumb1Only())
10336 bool isSEXTLoad = false;
10337 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10338 VT = LD->getMemoryVT();
10339 Ptr = LD->getBasePtr();
10340 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10341 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10342 VT = ST->getMemoryVT();
10343 Ptr = ST->getBasePtr();
10348 bool isLegal = false;
10349 if (Subtarget->isThumb2())
10350 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10353 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10359 // Swap base ptr and offset to catch more post-index load / store when
10360 // it's legal. In Thumb2 mode, offset must be an immediate.
10361 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10362 !Subtarget->isThumb2())
10363 std::swap(Base, Offset);
10365 // Post-indexed load / store update the base pointer.
10370 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10374 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10377 const SelectionDAG &DAG,
10378 unsigned Depth) const {
10379 unsigned BitWidth = KnownOne.getBitWidth();
10380 KnownZero = KnownOne = APInt(BitWidth, 0);
10381 switch (Op.getOpcode()) {
10387 // These nodes' second result is a boolean
10388 if (Op.getResNo() == 0)
10390 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10392 case ARMISD::CMOV: {
10393 // Bits are known zero/one if known on the LHS and RHS.
10394 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10395 if (KnownZero == 0 && KnownOne == 0) return;
10397 APInt KnownZeroRHS, KnownOneRHS;
10398 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10399 KnownZero &= KnownZeroRHS;
10400 KnownOne &= KnownOneRHS;
10403 case ISD::INTRINSIC_W_CHAIN: {
10404 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10405 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10408 case Intrinsic::arm_ldaex:
10409 case Intrinsic::arm_ldrex: {
10410 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10411 unsigned MemBits = VT.getScalarType().getSizeInBits();
10412 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10420 //===----------------------------------------------------------------------===//
10421 // ARM Inline Assembly Support
10422 //===----------------------------------------------------------------------===//
10424 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10425 // Looking for "rev" which is V6+.
10426 if (!Subtarget->hasV6Ops())
10429 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10430 std::string AsmStr = IA->getAsmString();
10431 SmallVector<StringRef, 4> AsmPieces;
10432 SplitString(AsmStr, AsmPieces, ";\n");
10434 switch (AsmPieces.size()) {
10435 default: return false;
10437 AsmStr = AsmPieces[0];
10439 SplitString(AsmStr, AsmPieces, " \t,");
10442 if (AsmPieces.size() == 3 &&
10443 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10444 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10445 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10446 if (Ty && Ty->getBitWidth() == 32)
10447 return IntrinsicLowering::LowerToByteSwap(CI);
10455 /// getConstraintType - Given a constraint letter, return the type of
10456 /// constraint it is for this target.
10457 ARMTargetLowering::ConstraintType
10458 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10459 if (Constraint.size() == 1) {
10460 switch (Constraint[0]) {
10462 case 'l': return C_RegisterClass;
10463 case 'w': return C_RegisterClass;
10464 case 'h': return C_RegisterClass;
10465 case 'x': return C_RegisterClass;
10466 case 't': return C_RegisterClass;
10467 case 'j': return C_Other; // Constant for movw.
10468 // An address with a single base register. Due to the way we
10469 // currently handle addresses it is the same as an 'r' memory constraint.
10470 case 'Q': return C_Memory;
10472 } else if (Constraint.size() == 2) {
10473 switch (Constraint[0]) {
10475 // All 'U+' constraints are addresses.
10476 case 'U': return C_Memory;
10479 return TargetLowering::getConstraintType(Constraint);
10482 /// Examine constraint type and operand type and determine a weight value.
10483 /// This object must already have been set up with the operand type
10484 /// and the current alternative constraint selected.
10485 TargetLowering::ConstraintWeight
10486 ARMTargetLowering::getSingleConstraintMatchWeight(
10487 AsmOperandInfo &info, const char *constraint) const {
10488 ConstraintWeight weight = CW_Invalid;
10489 Value *CallOperandVal = info.CallOperandVal;
10490 // If we don't have a value, we can't do a match,
10491 // but allow it at the lowest weight.
10492 if (!CallOperandVal)
10494 Type *type = CallOperandVal->getType();
10495 // Look at the constraint type.
10496 switch (*constraint) {
10498 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10501 if (type->isIntegerTy()) {
10502 if (Subtarget->isThumb())
10503 weight = CW_SpecificReg;
10505 weight = CW_Register;
10509 if (type->isFloatingPointTy())
10510 weight = CW_Register;
10516 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10518 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10520 if (Constraint.size() == 1) {
10521 // GCC ARM Constraint Letters
10522 switch (Constraint[0]) {
10523 case 'l': // Low regs or general regs.
10524 if (Subtarget->isThumb())
10525 return RCPair(0U, &ARM::tGPRRegClass);
10526 return RCPair(0U, &ARM::GPRRegClass);
10527 case 'h': // High regs or no regs.
10528 if (Subtarget->isThumb())
10529 return RCPair(0U, &ARM::hGPRRegClass);
10532 return RCPair(0U, &ARM::GPRRegClass);
10534 if (VT == MVT::Other)
10536 if (VT == MVT::f32)
10537 return RCPair(0U, &ARM::SPRRegClass);
10538 if (VT.getSizeInBits() == 64)
10539 return RCPair(0U, &ARM::DPRRegClass);
10540 if (VT.getSizeInBits() == 128)
10541 return RCPair(0U, &ARM::QPRRegClass);
10544 if (VT == MVT::Other)
10546 if (VT == MVT::f32)
10547 return RCPair(0U, &ARM::SPR_8RegClass);
10548 if (VT.getSizeInBits() == 64)
10549 return RCPair(0U, &ARM::DPR_8RegClass);
10550 if (VT.getSizeInBits() == 128)
10551 return RCPair(0U, &ARM::QPR_8RegClass);
10554 if (VT == MVT::f32)
10555 return RCPair(0U, &ARM::SPRRegClass);
10559 if (StringRef("{cc}").equals_lower(Constraint))
10560 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10562 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10565 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10566 /// vector. If it is invalid, don't add anything to Ops.
10567 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10568 std::string &Constraint,
10569 std::vector<SDValue>&Ops,
10570 SelectionDAG &DAG) const {
10573 // Currently only support length 1 constraints.
10574 if (Constraint.length() != 1) return;
10576 char ConstraintLetter = Constraint[0];
10577 switch (ConstraintLetter) {
10580 case 'I': case 'J': case 'K': case 'L':
10581 case 'M': case 'N': case 'O':
10582 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10586 int64_t CVal64 = C->getSExtValue();
10587 int CVal = (int) CVal64;
10588 // None of these constraints allow values larger than 32 bits. Check
10589 // that the value fits in an int.
10590 if (CVal != CVal64)
10593 switch (ConstraintLetter) {
10595 // Constant suitable for movw, must be between 0 and
10597 if (Subtarget->hasV6T2Ops())
10598 if (CVal >= 0 && CVal <= 65535)
10602 if (Subtarget->isThumb1Only()) {
10603 // This must be a constant between 0 and 255, for ADD
10605 if (CVal >= 0 && CVal <= 255)
10607 } else if (Subtarget->isThumb2()) {
10608 // A constant that can be used as an immediate value in a
10609 // data-processing instruction.
10610 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10613 // A constant that can be used as an immediate value in a
10614 // data-processing instruction.
10615 if (ARM_AM::getSOImmVal(CVal) != -1)
10621 if (Subtarget->isThumb()) { // FIXME thumb2
10622 // This must be a constant between -255 and -1, for negated ADD
10623 // immediates. This can be used in GCC with an "n" modifier that
10624 // prints the negated value, for use with SUB instructions. It is
10625 // not useful otherwise but is implemented for compatibility.
10626 if (CVal >= -255 && CVal <= -1)
10629 // This must be a constant between -4095 and 4095. It is not clear
10630 // what this constraint is intended for. Implemented for
10631 // compatibility with GCC.
10632 if (CVal >= -4095 && CVal <= 4095)
10638 if (Subtarget->isThumb1Only()) {
10639 // A 32-bit value where only one byte has a nonzero value. Exclude
10640 // zero to match GCC. This constraint is used by GCC internally for
10641 // constants that can be loaded with a move/shift combination.
10642 // It is not useful otherwise but is implemented for compatibility.
10643 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10645 } else if (Subtarget->isThumb2()) {
10646 // A constant whose bitwise inverse can be used as an immediate
10647 // value in a data-processing instruction. This can be used in GCC
10648 // with a "B" modifier that prints the inverted value, for use with
10649 // BIC and MVN instructions. It is not useful otherwise but is
10650 // implemented for compatibility.
10651 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10654 // A constant whose bitwise inverse can be used as an immediate
10655 // value in a data-processing instruction. This can be used in GCC
10656 // with a "B" modifier that prints the inverted value, for use with
10657 // BIC and MVN instructions. It is not useful otherwise but is
10658 // implemented for compatibility.
10659 if (ARM_AM::getSOImmVal(~CVal) != -1)
10665 if (Subtarget->isThumb1Only()) {
10666 // This must be a constant between -7 and 7,
10667 // for 3-operand ADD/SUB immediate instructions.
10668 if (CVal >= -7 && CVal < 7)
10670 } else if (Subtarget->isThumb2()) {
10671 // A constant whose negation can be used as an immediate value in a
10672 // data-processing instruction. This can be used in GCC with an "n"
10673 // modifier that prints the negated value, for use with SUB
10674 // instructions. It is not useful otherwise but is implemented for
10676 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10679 // A constant whose negation can be used as an immediate value in a
10680 // data-processing instruction. This can be used in GCC with an "n"
10681 // modifier that prints the negated value, for use with SUB
10682 // instructions. It is not useful otherwise but is implemented for
10684 if (ARM_AM::getSOImmVal(-CVal) != -1)
10690 if (Subtarget->isThumb()) { // FIXME thumb2
10691 // This must be a multiple of 4 between 0 and 1020, for
10692 // ADD sp + immediate.
10693 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10696 // A power of two or a constant between 0 and 32. This is used in
10697 // GCC for the shift amount on shifted register operands, but it is
10698 // useful in general for any shift amounts.
10699 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10705 if (Subtarget->isThumb()) { // FIXME thumb2
10706 // This must be a constant between 0 and 31, for shift amounts.
10707 if (CVal >= 0 && CVal <= 31)
10713 if (Subtarget->isThumb()) { // FIXME thumb2
10714 // This must be a multiple of 4 between -508 and 508, for
10715 // ADD/SUB sp = sp + immediate.
10716 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10721 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10725 if (Result.getNode()) {
10726 Ops.push_back(Result);
10729 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10732 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10733 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10734 unsigned Opcode = Op->getOpcode();
10735 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10736 "Invalid opcode for Div/Rem lowering");
10737 bool isSigned = (Opcode == ISD::SDIVREM);
10738 EVT VT = Op->getValueType(0);
10739 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10742 switch (VT.getSimpleVT().SimpleTy) {
10743 default: llvm_unreachable("Unexpected request for libcall!");
10744 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10745 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10746 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10747 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10750 SDValue InChain = DAG.getEntryNode();
10752 TargetLowering::ArgListTy Args;
10753 TargetLowering::ArgListEntry Entry;
10754 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10755 EVT ArgVT = Op->getOperand(i).getValueType();
10756 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10757 Entry.Node = Op->getOperand(i);
10759 Entry.isSExt = isSigned;
10760 Entry.isZExt = !isSigned;
10761 Args.push_back(Entry);
10764 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10767 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10770 TargetLowering::CallLoweringInfo CLI(DAG);
10771 CLI.setDebugLoc(dl).setChain(InChain)
10772 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10773 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10775 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10776 return CallInfo.first;
10780 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10781 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10785 SDValue Chain = Op.getOperand(0);
10786 SDValue Size = Op.getOperand(1);
10788 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10789 DAG.getConstant(2, MVT::i32));
10792 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10793 Flag = Chain.getValue(1);
10795 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10796 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10798 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10799 Chain = NewSP.getValue(1);
10801 SDValue Ops[2] = { NewSP, Chain };
10802 return DAG.getMergeValues(Ops, DL);
10805 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10806 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10807 "Unexpected type for custom-lowering FP_EXTEND");
10810 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10812 SDValue SrcVal = Op.getOperand(0);
10813 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10814 /*isSigned*/ false, SDLoc(Op)).first;
10817 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10818 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10819 Subtarget->isFPOnlySP() &&
10820 "Unexpected type for custom-lowering FP_ROUND");
10823 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10825 SDValue SrcVal = Op.getOperand(0);
10826 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10827 /*isSigned*/ false, SDLoc(Op)).first;
10831 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10832 // The ARM target isn't yet aware of offsets.
10836 bool ARM::isBitFieldInvertedMask(unsigned v) {
10837 if (v == 0xffffffff)
10840 // there can be 1's on either or both "outsides", all the "inside"
10841 // bits must be 0's
10842 unsigned TO = CountTrailingOnes_32(v);
10843 unsigned LO = CountLeadingOnes_32(v);
10844 v = (v >> TO) << TO;
10845 v = (v << LO) >> LO;
10849 /// isFPImmLegal - Returns true if the target can instruction select the
10850 /// specified FP immediate natively. If false, the legalizer will
10851 /// materialize the FP immediate as a load from a constant pool.
10852 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10853 if (!Subtarget->hasVFP3())
10855 if (VT == MVT::f32)
10856 return ARM_AM::getFP32Imm(Imm) != -1;
10857 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10858 return ARM_AM::getFP64Imm(Imm) != -1;
10862 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10863 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10864 /// specified in the intrinsic calls.
10865 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10867 unsigned Intrinsic) const {
10868 switch (Intrinsic) {
10869 case Intrinsic::arm_neon_vld1:
10870 case Intrinsic::arm_neon_vld2:
10871 case Intrinsic::arm_neon_vld3:
10872 case Intrinsic::arm_neon_vld4:
10873 case Intrinsic::arm_neon_vld2lane:
10874 case Intrinsic::arm_neon_vld3lane:
10875 case Intrinsic::arm_neon_vld4lane: {
10876 Info.opc = ISD::INTRINSIC_W_CHAIN;
10877 // Conservatively set memVT to the entire set of vectors loaded.
10878 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10879 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10880 Info.ptrVal = I.getArgOperand(0);
10882 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10883 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10884 Info.vol = false; // volatile loads with NEON intrinsics not supported
10885 Info.readMem = true;
10886 Info.writeMem = false;
10889 case Intrinsic::arm_neon_vst1:
10890 case Intrinsic::arm_neon_vst2:
10891 case Intrinsic::arm_neon_vst3:
10892 case Intrinsic::arm_neon_vst4:
10893 case Intrinsic::arm_neon_vst2lane:
10894 case Intrinsic::arm_neon_vst3lane:
10895 case Intrinsic::arm_neon_vst4lane: {
10896 Info.opc = ISD::INTRINSIC_VOID;
10897 // Conservatively set memVT to the entire set of vectors stored.
10898 unsigned NumElts = 0;
10899 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10900 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10901 if (!ArgTy->isVectorTy())
10903 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10905 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10906 Info.ptrVal = I.getArgOperand(0);
10908 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10909 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10910 Info.vol = false; // volatile stores with NEON intrinsics not supported
10911 Info.readMem = false;
10912 Info.writeMem = true;
10915 case Intrinsic::arm_ldaex:
10916 case Intrinsic::arm_ldrex: {
10917 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10918 Info.opc = ISD::INTRINSIC_W_CHAIN;
10919 Info.memVT = MVT::getVT(PtrTy->getElementType());
10920 Info.ptrVal = I.getArgOperand(0);
10922 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10924 Info.readMem = true;
10925 Info.writeMem = false;
10928 case Intrinsic::arm_stlex:
10929 case Intrinsic::arm_strex: {
10930 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10931 Info.opc = ISD::INTRINSIC_W_CHAIN;
10932 Info.memVT = MVT::getVT(PtrTy->getElementType());
10933 Info.ptrVal = I.getArgOperand(1);
10935 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10937 Info.readMem = false;
10938 Info.writeMem = true;
10941 case Intrinsic::arm_stlexd:
10942 case Intrinsic::arm_strexd: {
10943 Info.opc = ISD::INTRINSIC_W_CHAIN;
10944 Info.memVT = MVT::i64;
10945 Info.ptrVal = I.getArgOperand(2);
10949 Info.readMem = false;
10950 Info.writeMem = true;
10953 case Intrinsic::arm_ldaexd:
10954 case Intrinsic::arm_ldrexd: {
10955 Info.opc = ISD::INTRINSIC_W_CHAIN;
10956 Info.memVT = MVT::i64;
10957 Info.ptrVal = I.getArgOperand(0);
10961 Info.readMem = true;
10962 Info.writeMem = false;
10972 /// \brief Returns true if it is beneficial to convert a load of a constant
10973 /// to just the constant itself.
10974 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10976 assert(Ty->isIntegerTy());
10978 unsigned Bits = Ty->getPrimitiveSizeInBits();
10979 if (Bits == 0 || Bits > 32)
10984 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10985 // Loads and stores less than 64-bits are already atomic; ones above that
10986 // are doomed anyway, so defer to the default libcall and blame the OS when
10987 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10988 // anything for those.
10989 bool IsMClass = Subtarget->isMClass();
10990 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10991 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10992 return Size == 64 && !IsMClass;
10993 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10994 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10997 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10998 // and up to 64 bits on the non-M profiles
10999 unsigned AtomicLimit = IsMClass ? 32 : 64;
11000 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
11003 // This has so far only been implemented for MachO.
11004 bool ARMTargetLowering::useLoadStackGuardNode() const {
11005 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11008 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11009 AtomicOrdering Ord) const {
11010 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11011 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11012 bool IsAcquire = isAtLeastAcquire(Ord);
11014 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11015 // intrinsic must return {i32, i32} and we have to recombine them into a
11016 // single i64 here.
11017 if (ValTy->getPrimitiveSizeInBits() == 64) {
11018 Intrinsic::ID Int =
11019 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11020 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11022 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11023 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11025 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11026 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11027 if (!Subtarget->isLittle())
11028 std::swap (Lo, Hi);
11029 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11030 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11031 return Builder.CreateOr(
11032 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11035 Type *Tys[] = { Addr->getType() };
11036 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11037 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11039 return Builder.CreateTruncOrBitCast(
11040 Builder.CreateCall(Ldrex, Addr),
11041 cast<PointerType>(Addr->getType())->getElementType());
11044 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11046 AtomicOrdering Ord) const {
11047 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11048 bool IsRelease = isAtLeastRelease(Ord);
11050 // Since the intrinsics must have legal type, the i64 intrinsics take two
11051 // parameters: "i32, i32". We must marshal Val into the appropriate form
11052 // before the call.
11053 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11054 Intrinsic::ID Int =
11055 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11056 Function *Strex = Intrinsic::getDeclaration(M, Int);
11057 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11059 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11060 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11061 if (!Subtarget->isLittle())
11062 std::swap (Lo, Hi);
11063 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11064 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11067 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11068 Type *Tys[] = { Addr->getType() };
11069 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11071 return Builder.CreateCall2(
11072 Strex, Builder.CreateZExtOrBitCast(
11073 Val, Strex->getFunctionType()->getParamType(0)),
11085 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11086 uint64_t &Members) {
11087 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11088 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11089 uint64_t SubMembers = 0;
11090 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11092 Members += SubMembers;
11094 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11095 uint64_t SubMembers = 0;
11096 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11098 Members += SubMembers * AT->getNumElements();
11099 } else if (Ty->isFloatTy()) {
11100 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11104 } else if (Ty->isDoubleTy()) {
11105 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11109 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11116 return VT->getBitWidth() == 64;
11118 return VT->getBitWidth() == 128;
11120 switch (VT->getBitWidth()) {
11133 return (Members > 0 && Members <= 4);
11136 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11137 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11138 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11139 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11140 CallingConv::ARM_AAPCS_VFP)
11143 HABaseType Base = HA_UNKNOWN;
11144 uint64_t Members = 0;
11145 bool result = isHomogeneousAggregate(Ty, Base, Members);
11146 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());