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 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74 LLVMContext &C, ParmContext PC)
75 : CCState(CC, isVarArg, MF, TM, 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 if (Subtarget->isThumb1Only())
392 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
394 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
395 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
396 !Subtarget->isThumb1Only()) {
397 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
398 if (!Subtarget->isFPOnlySP())
399 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
402 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
403 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
404 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
405 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
406 setTruncStoreAction((MVT::SimpleValueType)VT,
407 (MVT::SimpleValueType)InnerVT, Expand);
408 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
413 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
414 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
415 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
420 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423 if (Subtarget->hasNEON()) {
424 addDRTypeForNEON(MVT::v2f32);
425 addDRTypeForNEON(MVT::v8i8);
426 addDRTypeForNEON(MVT::v4i16);
427 addDRTypeForNEON(MVT::v2i32);
428 addDRTypeForNEON(MVT::v1i64);
430 addQRTypeForNEON(MVT::v4f32);
431 addQRTypeForNEON(MVT::v2f64);
432 addQRTypeForNEON(MVT::v16i8);
433 addQRTypeForNEON(MVT::v8i16);
434 addQRTypeForNEON(MVT::v4i32);
435 addQRTypeForNEON(MVT::v2i64);
437 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
438 // neither Neon nor VFP support any arithmetic operations on it.
439 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
440 // supported for v4f32.
441 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
442 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
443 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
444 // FIXME: Code duplication: FDIV and FREM are expanded always, see
445 // ARMTargetLowering::addTypeForNEON method for details.
446 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
447 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
448 // FIXME: Create unittest.
449 // In another words, find a way when "copysign" appears in DAG with vector
451 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
452 // FIXME: Code duplication: SETCC has custom operation action, see
453 // ARMTargetLowering::addTypeForNEON method for details.
454 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
455 // FIXME: Create unittest for FNEG and for FABS.
456 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
457 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
458 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
459 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
460 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
461 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
462 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
463 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
464 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
465 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
466 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
467 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
469 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
470 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
471 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
473 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
474 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
477 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
478 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
479 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
480 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
481 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
482 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
483 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
484 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
485 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
486 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
487 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
488 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
489 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492 // Mark v2f32 intrinsics.
493 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
494 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
495 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
496 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
497 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
498 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
499 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
500 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
501 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
502 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
503 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
504 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
505 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
506 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509 // Neon does not support some operations on v1i64 and v2i64 types.
510 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
511 // Custom handling for some quad-vector types to detect VMULL.
512 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
515 // Custom handling for some vector types to avoid expensive expansions
516 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
517 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
518 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
519 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
520 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
521 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
522 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
523 // a destination type that is wider than the source, and nor does
524 // it have a FP_TO_[SU]INT instruction with a narrower destination than
526 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
527 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
528 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
529 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
532 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
534 // NEON does not have single instruction CTPOP for vectors with element
535 // types wider than 8-bits. However, custom lowering can leverage the
536 // v8i8/v16i8 vcnt instruction.
537 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
538 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
539 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
540 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
542 // NEON only has FMA instructions as of VFP4.
543 if (!Subtarget->hasVFP4()) {
544 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
545 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
548 setTargetDAGCombine(ISD::INTRINSIC_VOID);
549 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
550 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
551 setTargetDAGCombine(ISD::SHL);
552 setTargetDAGCombine(ISD::SRL);
553 setTargetDAGCombine(ISD::SRA);
554 setTargetDAGCombine(ISD::SIGN_EXTEND);
555 setTargetDAGCombine(ISD::ZERO_EXTEND);
556 setTargetDAGCombine(ISD::ANY_EXTEND);
557 setTargetDAGCombine(ISD::SELECT_CC);
558 setTargetDAGCombine(ISD::BUILD_VECTOR);
559 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
560 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
561 setTargetDAGCombine(ISD::STORE);
562 setTargetDAGCombine(ISD::FP_TO_SINT);
563 setTargetDAGCombine(ISD::FP_TO_UINT);
564 setTargetDAGCombine(ISD::FDIV);
566 // It is legal to extload from v4i8 to v4i16 or v4i32.
567 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
568 MVT::v4i16, MVT::v2i16,
570 for (unsigned i = 0; i < 6; ++i) {
571 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
572 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
573 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
577 // ARM and Thumb2 support UMLAL/SMLAL.
578 if (!Subtarget->isThumb1Only())
579 setTargetDAGCombine(ISD::ADDC);
582 computeRegisterProperties();
584 // ARM does not have floating-point extending loads.
585 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
586 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
588 // ... or truncating stores
589 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
590 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
591 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
593 // ARM does not have i1 sign extending load.
594 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
596 // ARM supports all 4 flavors of integer indexed load / store.
597 if (!Subtarget->isThumb1Only()) {
598 for (unsigned im = (unsigned)ISD::PRE_INC;
599 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
600 setIndexedLoadAction(im, MVT::i1, Legal);
601 setIndexedLoadAction(im, MVT::i8, Legal);
602 setIndexedLoadAction(im, MVT::i16, Legal);
603 setIndexedLoadAction(im, MVT::i32, Legal);
604 setIndexedStoreAction(im, MVT::i1, Legal);
605 setIndexedStoreAction(im, MVT::i8, Legal);
606 setIndexedStoreAction(im, MVT::i16, Legal);
607 setIndexedStoreAction(im, MVT::i32, Legal);
611 setOperationAction(ISD::SADDO, MVT::i32, Custom);
612 setOperationAction(ISD::UADDO, MVT::i32, Custom);
613 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
614 setOperationAction(ISD::USUBO, MVT::i32, Custom);
616 // i64 operation support.
617 setOperationAction(ISD::MUL, MVT::i64, Expand);
618 setOperationAction(ISD::MULHU, MVT::i32, Expand);
619 if (Subtarget->isThumb1Only()) {
620 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
621 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
623 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
624 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
625 setOperationAction(ISD::MULHS, MVT::i32, Expand);
627 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
628 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
629 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
630 setOperationAction(ISD::SRL, MVT::i64, Custom);
631 setOperationAction(ISD::SRA, MVT::i64, Custom);
633 if (!Subtarget->isThumb1Only()) {
634 // FIXME: We should do this for Thumb1 as well.
635 setOperationAction(ISD::ADDC, MVT::i32, Custom);
636 setOperationAction(ISD::ADDE, MVT::i32, Custom);
637 setOperationAction(ISD::SUBC, MVT::i32, Custom);
638 setOperationAction(ISD::SUBE, MVT::i32, Custom);
641 // ARM does not have ROTL.
642 setOperationAction(ISD::ROTL, MVT::i32, Expand);
643 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
644 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
645 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
646 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
648 // These just redirect to CTTZ and CTLZ on ARM.
649 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
650 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
652 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
654 // Only ARMv6 has BSWAP.
655 if (!Subtarget->hasV6Ops())
656 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
658 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
659 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
660 // These are expanded into libcalls if the cpu doesn't have HW divider.
661 setOperationAction(ISD::SDIV, MVT::i32, Expand);
662 setOperationAction(ISD::UDIV, MVT::i32, Expand);
665 // FIXME: Also set divmod for SREM on EABI
666 setOperationAction(ISD::SREM, MVT::i32, Expand);
667 setOperationAction(ISD::UREM, MVT::i32, Expand);
668 // Register based DivRem for AEABI (RTABI 4.2)
669 if (Subtarget->isTargetAEABI()) {
670 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
671 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
672 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
673 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
674 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
675 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
676 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
677 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
679 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
680 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
681 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
682 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
683 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
684 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
685 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
686 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
688 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
689 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
691 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
692 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
695 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
696 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
697 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
698 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
699 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
701 setOperationAction(ISD::TRAP, MVT::Other, Legal);
703 // Use the default implementation.
704 setOperationAction(ISD::VASTART, MVT::Other, Custom);
705 setOperationAction(ISD::VAARG, MVT::Other, Expand);
706 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
707 setOperationAction(ISD::VAEND, MVT::Other, Expand);
708 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
709 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
711 if (!Subtarget->isTargetMachO()) {
712 // Non-MachO platforms may return values in these registers via the
713 // personality function.
714 setExceptionPointerRegister(ARM::R0);
715 setExceptionSelectorRegister(ARM::R1);
718 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
719 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
721 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
723 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
724 // the default expansion.
725 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
726 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
727 // to ldrex/strex loops already.
728 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
730 // On v8, we have particularly efficient implementations of atomic fences
731 // if they can be combined with nearby atomic loads and stores.
732 if (!Subtarget->hasV8Ops()) {
733 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
734 setInsertFencesForAtomic(true);
737 // If there's anything we can use as a barrier, go through custom lowering
739 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
740 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
742 // Set them all for expansion, which will force libcalls.
743 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
744 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
745 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
746 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
747 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
748 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
749 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
750 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
751 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
752 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
753 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
754 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
755 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
756 // Unordered/Monotonic case.
757 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
758 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
761 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
763 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
764 if (!Subtarget->hasV6Ops()) {
765 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
766 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
768 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
770 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
771 !Subtarget->isThumb1Only()) {
772 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
773 // iff target supports vfp2.
774 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
775 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
778 // We want to custom lower some of our intrinsics.
779 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780 if (Subtarget->isTargetDarwin()) {
781 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
782 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
783 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
786 setOperationAction(ISD::SETCC, MVT::i32, Expand);
787 setOperationAction(ISD::SETCC, MVT::f32, Expand);
788 setOperationAction(ISD::SETCC, MVT::f64, Expand);
789 setOperationAction(ISD::SELECT, MVT::i32, Custom);
790 setOperationAction(ISD::SELECT, MVT::f32, Custom);
791 setOperationAction(ISD::SELECT, MVT::f64, Custom);
792 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
793 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
794 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
796 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
797 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
798 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
799 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
800 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
802 // We don't support sin/cos/fmod/copysign/pow
803 setOperationAction(ISD::FSIN, MVT::f64, Expand);
804 setOperationAction(ISD::FSIN, MVT::f32, Expand);
805 setOperationAction(ISD::FCOS, MVT::f32, Expand);
806 setOperationAction(ISD::FCOS, MVT::f64, Expand);
807 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
808 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
809 setOperationAction(ISD::FREM, MVT::f64, Expand);
810 setOperationAction(ISD::FREM, MVT::f32, Expand);
811 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
812 !Subtarget->isThumb1Only()) {
813 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
814 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
816 setOperationAction(ISD::FPOW, MVT::f64, Expand);
817 setOperationAction(ISD::FPOW, MVT::f32, Expand);
819 if (!Subtarget->hasVFP4()) {
820 setOperationAction(ISD::FMA, MVT::f64, Expand);
821 setOperationAction(ISD::FMA, MVT::f32, Expand);
824 // Various VFP goodness
825 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
826 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
827 if (Subtarget->hasVFP2()) {
828 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
829 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
830 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
831 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
834 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
835 if (!Subtarget->hasV8Ops()) {
836 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
837 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
840 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
841 if (!Subtarget->hasFP16()) {
842 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
843 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
847 // Combine sin / cos into one node or libcall if possible.
848 if (Subtarget->hasSinCos()) {
849 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
850 setLibcallName(RTLIB::SINCOS_F64, "sincos");
851 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
852 // For iOS, we don't want to the normal expansion of a libcall to
853 // sincos. We want to issue a libcall to __sincos_stret.
854 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
855 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
859 // We have target-specific dag combine patterns for the following nodes:
860 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
861 setTargetDAGCombine(ISD::ADD);
862 setTargetDAGCombine(ISD::SUB);
863 setTargetDAGCombine(ISD::MUL);
864 setTargetDAGCombine(ISD::AND);
865 setTargetDAGCombine(ISD::OR);
866 setTargetDAGCombine(ISD::XOR);
868 if (Subtarget->hasV6Ops())
869 setTargetDAGCombine(ISD::SRL);
871 setStackPointerRegisterToSaveRestore(ARM::SP);
873 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
874 !Subtarget->hasVFP2())
875 setSchedulingPreference(Sched::RegPressure);
877 setSchedulingPreference(Sched::Hybrid);
879 //// temporary - rewrite interface to use type
880 MaxStoresPerMemset = 8;
881 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
882 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
883 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
884 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
885 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
887 // On ARM arguments smaller than 4 bytes are extended, so all arguments
888 // are at least 4 bytes aligned.
889 setMinStackArgumentAlignment(4);
891 // Prefer likely predicted branches to selects on out-of-order cores.
892 PredictableSelectIsExpensive = Subtarget->isLikeA9();
894 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
897 // FIXME: It might make sense to define the representative register class as the
898 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
899 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
900 // SPR's representative would be DPR_VFP2. This should work well if register
901 // pressure tracking were modified such that a register use would increment the
902 // pressure of the register class's representative and all of it's super
903 // classes' representatives transitively. We have not implemented this because
904 // of the difficulty prior to coalescing of modeling operand register classes
905 // due to the common occurrence of cross class copies and subregister insertions
907 std::pair<const TargetRegisterClass*, uint8_t>
908 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
909 const TargetRegisterClass *RRC = nullptr;
911 switch (VT.SimpleTy) {
913 return TargetLowering::findRepresentativeClass(VT);
914 // Use DPR as representative register class for all floating point
915 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
916 // the cost is 1 for both f32 and f64.
917 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
918 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
919 RRC = &ARM::DPRRegClass;
920 // When NEON is used for SP, only half of the register file is available
921 // because operations that define both SP and DP results will be constrained
922 // to the VFP2 class (D0-D15). We currently model this constraint prior to
923 // coalescing by double-counting the SP regs. See the FIXME above.
924 if (Subtarget->useNEONForSinglePrecisionFP())
927 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
928 case MVT::v4f32: case MVT::v2f64:
929 RRC = &ARM::DPRRegClass;
933 RRC = &ARM::DPRRegClass;
937 RRC = &ARM::DPRRegClass;
941 return std::make_pair(RRC, Cost);
944 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
946 default: return nullptr;
947 case ARMISD::Wrapper: return "ARMISD::Wrapper";
948 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
949 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
950 case ARMISD::CALL: return "ARMISD::CALL";
951 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
952 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
953 case ARMISD::tCALL: return "ARMISD::tCALL";
954 case ARMISD::BRCOND: return "ARMISD::BRCOND";
955 case ARMISD::BR_JT: return "ARMISD::BR_JT";
956 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
957 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
958 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
959 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
960 case ARMISD::CMP: return "ARMISD::CMP";
961 case ARMISD::CMN: return "ARMISD::CMN";
962 case ARMISD::CMPZ: return "ARMISD::CMPZ";
963 case ARMISD::CMPFP: return "ARMISD::CMPFP";
964 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
965 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
966 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
968 case ARMISD::CMOV: return "ARMISD::CMOV";
970 case ARMISD::RBIT: return "ARMISD::RBIT";
972 case ARMISD::FTOSI: return "ARMISD::FTOSI";
973 case ARMISD::FTOUI: return "ARMISD::FTOUI";
974 case ARMISD::SITOF: return "ARMISD::SITOF";
975 case ARMISD::UITOF: return "ARMISD::UITOF";
977 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
978 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
979 case ARMISD::RRX: return "ARMISD::RRX";
981 case ARMISD::ADDC: return "ARMISD::ADDC";
982 case ARMISD::ADDE: return "ARMISD::ADDE";
983 case ARMISD::SUBC: return "ARMISD::SUBC";
984 case ARMISD::SUBE: return "ARMISD::SUBE";
986 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
987 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
989 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
990 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
992 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
994 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
996 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
998 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1000 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1002 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1004 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1005 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1006 case ARMISD::VCGE: return "ARMISD::VCGE";
1007 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1008 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1009 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1010 case ARMISD::VCGT: return "ARMISD::VCGT";
1011 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1012 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1013 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1014 case ARMISD::VTST: return "ARMISD::VTST";
1016 case ARMISD::VSHL: return "ARMISD::VSHL";
1017 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1018 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1019 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1020 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1021 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1022 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1023 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1024 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1025 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1026 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1027 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1028 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1029 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1030 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1031 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1032 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1033 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1034 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1035 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1036 case ARMISD::VDUP: return "ARMISD::VDUP";
1037 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1038 case ARMISD::VEXT: return "ARMISD::VEXT";
1039 case ARMISD::VREV64: return "ARMISD::VREV64";
1040 case ARMISD::VREV32: return "ARMISD::VREV32";
1041 case ARMISD::VREV16: return "ARMISD::VREV16";
1042 case ARMISD::VZIP: return "ARMISD::VZIP";
1043 case ARMISD::VUZP: return "ARMISD::VUZP";
1044 case ARMISD::VTRN: return "ARMISD::VTRN";
1045 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1046 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1047 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1048 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1049 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1050 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1051 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1052 case ARMISD::FMAX: return "ARMISD::FMAX";
1053 case ARMISD::FMIN: return "ARMISD::FMIN";
1054 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1055 case ARMISD::VMINNM: return "ARMISD::VMIN";
1056 case ARMISD::BFI: return "ARMISD::BFI";
1057 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1058 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1059 case ARMISD::VBSL: return "ARMISD::VBSL";
1060 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1061 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1062 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1063 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1064 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1065 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1066 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1067 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1068 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1069 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1070 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1071 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1072 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1073 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1074 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1075 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1076 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1077 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1078 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1079 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1083 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1084 if (!VT.isVector()) return getPointerTy();
1085 return VT.changeVectorElementTypeToInteger();
1088 /// getRegClassFor - Return the register class that should be used for the
1089 /// specified value type.
1090 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1091 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1092 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1093 // load / store 4 to 8 consecutive D registers.
1094 if (Subtarget->hasNEON()) {
1095 if (VT == MVT::v4i64)
1096 return &ARM::QQPRRegClass;
1097 if (VT == MVT::v8i64)
1098 return &ARM::QQQQPRRegClass;
1100 return TargetLowering::getRegClassFor(VT);
1103 // Create a fast isel object.
1105 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1106 const TargetLibraryInfo *libInfo) const {
1107 return ARM::createFastISel(funcInfo, libInfo);
1110 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1111 /// be used for loads / stores from the global.
1112 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1113 return (Subtarget->isThumb1Only() ? 127 : 4095);
1116 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1117 unsigned NumVals = N->getNumValues();
1119 return Sched::RegPressure;
1121 for (unsigned i = 0; i != NumVals; ++i) {
1122 EVT VT = N->getValueType(i);
1123 if (VT == MVT::Glue || VT == MVT::Other)
1125 if (VT.isFloatingPoint() || VT.isVector())
1129 if (!N->isMachineOpcode())
1130 return Sched::RegPressure;
1132 // Load are scheduled for latency even if there instruction itinerary
1133 // is not available.
1134 const TargetInstrInfo *TII =
1135 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1136 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1138 if (MCID.getNumDefs() == 0)
1139 return Sched::RegPressure;
1140 if (!Itins->isEmpty() &&
1141 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1144 return Sched::RegPressure;
1147 //===----------------------------------------------------------------------===//
1149 //===----------------------------------------------------------------------===//
1151 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1152 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1154 default: llvm_unreachable("Unknown condition code!");
1155 case ISD::SETNE: return ARMCC::NE;
1156 case ISD::SETEQ: return ARMCC::EQ;
1157 case ISD::SETGT: return ARMCC::GT;
1158 case ISD::SETGE: return ARMCC::GE;
1159 case ISD::SETLT: return ARMCC::LT;
1160 case ISD::SETLE: return ARMCC::LE;
1161 case ISD::SETUGT: return ARMCC::HI;
1162 case ISD::SETUGE: return ARMCC::HS;
1163 case ISD::SETULT: return ARMCC::LO;
1164 case ISD::SETULE: return ARMCC::LS;
1168 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1169 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1170 ARMCC::CondCodes &CondCode2) {
1171 CondCode2 = ARMCC::AL;
1173 default: llvm_unreachable("Unknown FP condition!");
1175 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1177 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1179 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1180 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1181 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1182 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1183 case ISD::SETO: CondCode = ARMCC::VC; break;
1184 case ISD::SETUO: CondCode = ARMCC::VS; break;
1185 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1186 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1187 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1189 case ISD::SETULT: CondCode = ARMCC::LT; break;
1191 case ISD::SETULE: CondCode = ARMCC::LE; break;
1193 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1197 //===----------------------------------------------------------------------===//
1198 // Calling Convention Implementation
1199 //===----------------------------------------------------------------------===//
1201 #include "ARMGenCallingConv.inc"
1203 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1204 /// account presence of floating point hardware and calling convention
1205 /// limitations, such as support for variadic functions.
1207 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1208 bool isVarArg) const {
1211 llvm_unreachable("Unsupported calling convention");
1212 case CallingConv::ARM_AAPCS:
1213 case CallingConv::ARM_APCS:
1214 case CallingConv::GHC:
1216 case CallingConv::ARM_AAPCS_VFP:
1217 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1218 case CallingConv::C:
1219 if (!Subtarget->isAAPCS_ABI())
1220 return CallingConv::ARM_APCS;
1221 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1222 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1224 return CallingConv::ARM_AAPCS_VFP;
1226 return CallingConv::ARM_AAPCS;
1227 case CallingConv::Fast:
1228 if (!Subtarget->isAAPCS_ABI()) {
1229 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1230 return CallingConv::Fast;
1231 return CallingConv::ARM_APCS;
1232 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1233 return CallingConv::ARM_AAPCS_VFP;
1235 return CallingConv::ARM_AAPCS;
1239 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1240 /// CallingConvention.
1241 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1243 bool isVarArg) const {
1244 switch (getEffectiveCallingConv(CC, isVarArg)) {
1246 llvm_unreachable("Unsupported calling convention");
1247 case CallingConv::ARM_APCS:
1248 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1249 case CallingConv::ARM_AAPCS:
1250 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1251 case CallingConv::ARM_AAPCS_VFP:
1252 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1253 case CallingConv::Fast:
1254 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1255 case CallingConv::GHC:
1256 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1260 /// LowerCallResult - Lower the result values of a call into the
1261 /// appropriate copies out of appropriate physical registers.
1263 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1264 CallingConv::ID CallConv, bool isVarArg,
1265 const SmallVectorImpl<ISD::InputArg> &Ins,
1266 SDLoc dl, SelectionDAG &DAG,
1267 SmallVectorImpl<SDValue> &InVals,
1268 bool isThisReturn, SDValue ThisVal) const {
1270 // Assign locations to each value returned by this call.
1271 SmallVector<CCValAssign, 16> RVLocs;
1272 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1273 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1274 CCInfo.AnalyzeCallResult(Ins,
1275 CCAssignFnForNode(CallConv, /* Return*/ true,
1278 // Copy all of the result registers out of their specified physreg.
1279 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1280 CCValAssign VA = RVLocs[i];
1282 // Pass 'this' value directly from the argument to return value, to avoid
1283 // reg unit interference
1284 if (i == 0 && isThisReturn) {
1285 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1286 "unexpected return calling convention register assignment");
1287 InVals.push_back(ThisVal);
1292 if (VA.needsCustom()) {
1293 // Handle f64 or half of a v2f64.
1294 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1296 Chain = Lo.getValue(1);
1297 InFlag = Lo.getValue(2);
1298 VA = RVLocs[++i]; // skip ahead to next loc
1299 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1301 Chain = Hi.getValue(1);
1302 InFlag = Hi.getValue(2);
1303 if (!Subtarget->isLittle())
1305 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1307 if (VA.getLocVT() == MVT::v2f64) {
1308 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1309 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1310 DAG.getConstant(0, MVT::i32));
1312 VA = RVLocs[++i]; // skip ahead to next loc
1313 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1314 Chain = Lo.getValue(1);
1315 InFlag = Lo.getValue(2);
1316 VA = RVLocs[++i]; // skip ahead to next loc
1317 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1318 Chain = Hi.getValue(1);
1319 InFlag = Hi.getValue(2);
1320 if (!Subtarget->isLittle())
1322 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1323 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1324 DAG.getConstant(1, MVT::i32));
1327 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1329 Chain = Val.getValue(1);
1330 InFlag = Val.getValue(2);
1333 switch (VA.getLocInfo()) {
1334 default: llvm_unreachable("Unknown loc info!");
1335 case CCValAssign::Full: break;
1336 case CCValAssign::BCvt:
1337 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1341 InVals.push_back(Val);
1347 /// LowerMemOpCallTo - Store the argument to the stack.
1349 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1350 SDValue StackPtr, SDValue Arg,
1351 SDLoc dl, SelectionDAG &DAG,
1352 const CCValAssign &VA,
1353 ISD::ArgFlagsTy Flags) const {
1354 unsigned LocMemOffset = VA.getLocMemOffset();
1355 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1356 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1357 return DAG.getStore(Chain, dl, Arg, PtrOff,
1358 MachinePointerInfo::getStack(LocMemOffset),
1362 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1363 SDValue Chain, SDValue &Arg,
1364 RegsToPassVector &RegsToPass,
1365 CCValAssign &VA, CCValAssign &NextVA,
1367 SmallVectorImpl<SDValue> &MemOpChains,
1368 ISD::ArgFlagsTy Flags) const {
1370 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1371 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1372 unsigned id = Subtarget->isLittle() ? 0 : 1;
1373 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1375 if (NextVA.isRegLoc())
1376 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1378 assert(NextVA.isMemLoc());
1379 if (!StackPtr.getNode())
1380 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1382 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1388 /// LowerCall - Lowering a call into a callseq_start <-
1389 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1392 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1393 SmallVectorImpl<SDValue> &InVals) const {
1394 SelectionDAG &DAG = CLI.DAG;
1396 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1397 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1398 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1399 SDValue Chain = CLI.Chain;
1400 SDValue Callee = CLI.Callee;
1401 bool &isTailCall = CLI.IsTailCall;
1402 CallingConv::ID CallConv = CLI.CallConv;
1403 bool doesNotRet = CLI.DoesNotReturn;
1404 bool isVarArg = CLI.IsVarArg;
1406 MachineFunction &MF = DAG.getMachineFunction();
1407 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1408 bool isThisReturn = false;
1409 bool isSibCall = false;
1411 // Disable tail calls if they're not supported.
1412 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1416 // Check if it's really possible to do a tail call.
1417 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1418 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1419 Outs, OutVals, Ins, DAG);
1420 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1421 report_fatal_error("failed to perform tail call elimination on a call "
1422 "site marked musttail");
1423 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1424 // detected sibcalls.
1431 // Analyze operands of the call, assigning locations to each operand.
1432 SmallVector<CCValAssign, 16> ArgLocs;
1433 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1434 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1435 CCInfo.AnalyzeCallOperands(Outs,
1436 CCAssignFnForNode(CallConv, /* Return*/ false,
1439 // Get a count of how many bytes are to be pushed on the stack.
1440 unsigned NumBytes = CCInfo.getNextStackOffset();
1442 // For tail calls, memory operands are available in our caller's stack.
1446 // Adjust the stack pointer for the new arguments...
1447 // These operations are automatically eliminated by the prolog/epilog pass
1449 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1452 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1454 RegsToPassVector RegsToPass;
1455 SmallVector<SDValue, 8> MemOpChains;
1457 // Walk the register/memloc assignments, inserting copies/loads. In the case
1458 // of tail call optimization, arguments are handled later.
1459 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1461 ++i, ++realArgIdx) {
1462 CCValAssign &VA = ArgLocs[i];
1463 SDValue Arg = OutVals[realArgIdx];
1464 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1465 bool isByVal = Flags.isByVal();
1467 // Promote the value if needed.
1468 switch (VA.getLocInfo()) {
1469 default: llvm_unreachable("Unknown loc info!");
1470 case CCValAssign::Full: break;
1471 case CCValAssign::SExt:
1472 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1474 case CCValAssign::ZExt:
1475 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1477 case CCValAssign::AExt:
1478 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1480 case CCValAssign::BCvt:
1481 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1485 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1486 if (VA.needsCustom()) {
1487 if (VA.getLocVT() == MVT::v2f64) {
1488 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1489 DAG.getConstant(0, MVT::i32));
1490 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1491 DAG.getConstant(1, MVT::i32));
1493 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1494 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1496 VA = ArgLocs[++i]; // skip ahead to next loc
1497 if (VA.isRegLoc()) {
1498 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1499 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1501 assert(VA.isMemLoc());
1503 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1504 dl, DAG, VA, Flags));
1507 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1508 StackPtr, MemOpChains, Flags);
1510 } else if (VA.isRegLoc()) {
1511 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1512 assert(VA.getLocVT() == MVT::i32 &&
1513 "unexpected calling convention register assignment");
1514 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1515 "unexpected use of 'returned'");
1516 isThisReturn = true;
1518 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1519 } else if (isByVal) {
1520 assert(VA.isMemLoc());
1521 unsigned offset = 0;
1523 // True if this byval aggregate will be split between registers
1525 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1526 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1528 if (CurByValIdx < ByValArgsCount) {
1530 unsigned RegBegin, RegEnd;
1531 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1533 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1535 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1536 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1537 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1538 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1539 MachinePointerInfo(),
1540 false, false, false,
1541 DAG.InferPtrAlignment(AddArg));
1542 MemOpChains.push_back(Load.getValue(1));
1543 RegsToPass.push_back(std::make_pair(j, Load));
1546 // If parameter size outsides register area, "offset" value
1547 // helps us to calculate stack slot for remained part properly.
1548 offset = RegEnd - RegBegin;
1550 CCInfo.nextInRegsParam();
1553 if (Flags.getByValSize() > 4*offset) {
1554 unsigned LocMemOffset = VA.getLocMemOffset();
1555 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1556 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1558 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1559 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1560 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1562 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1564 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1565 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1566 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1569 } else if (!isSibCall) {
1570 assert(VA.isMemLoc());
1572 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1573 dl, DAG, VA, Flags));
1577 if (!MemOpChains.empty())
1578 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1580 // Build a sequence of copy-to-reg nodes chained together with token chain
1581 // and flag operands which copy the outgoing args into the appropriate regs.
1583 // Tail call byval lowering might overwrite argument registers so in case of
1584 // tail call optimization the copies to registers are lowered later.
1586 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1587 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1588 RegsToPass[i].second, InFlag);
1589 InFlag = Chain.getValue(1);
1592 // For tail calls lower the arguments to the 'real' stack slot.
1594 // Force all the incoming stack arguments to be loaded from the stack
1595 // before any new outgoing arguments are stored to the stack, because the
1596 // outgoing stack slots may alias the incoming argument stack slots, and
1597 // the alias isn't otherwise explicit. This is slightly more conservative
1598 // than necessary, because it means that each store effectively depends
1599 // on every argument instead of just those arguments it would clobber.
1601 // Do not flag preceding copytoreg stuff together with the following stuff.
1603 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1604 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1605 RegsToPass[i].second, InFlag);
1606 InFlag = Chain.getValue(1);
1611 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1612 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1613 // node so that legalize doesn't hack it.
1614 bool isDirect = false;
1615 bool isARMFunc = false;
1616 bool isLocalARMFunc = false;
1617 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1619 if (EnableARMLongCalls) {
1620 assert((Subtarget->isTargetWindows() ||
1621 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1622 "long-calls with non-static relocation model!");
1623 // Handle a global address or an external symbol. If it's not one of
1624 // those, the target's already in a register, so we don't need to do
1626 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1627 const GlobalValue *GV = G->getGlobal();
1628 // Create a constant pool entry for the callee address
1629 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1630 ARMConstantPoolValue *CPV =
1631 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1633 // Get the address of the callee into a register
1634 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1635 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1636 Callee = DAG.getLoad(getPointerTy(), dl,
1637 DAG.getEntryNode(), CPAddr,
1638 MachinePointerInfo::getConstantPool(),
1639 false, false, false, 0);
1640 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1641 const char *Sym = S->getSymbol();
1643 // Create a constant pool entry for the callee address
1644 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1645 ARMConstantPoolValue *CPV =
1646 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1647 ARMPCLabelIndex, 0);
1648 // Get the address of the callee into a register
1649 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1650 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1651 Callee = DAG.getLoad(getPointerTy(), dl,
1652 DAG.getEntryNode(), CPAddr,
1653 MachinePointerInfo::getConstantPool(),
1654 false, false, false, 0);
1656 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1657 const GlobalValue *GV = G->getGlobal();
1659 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1660 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1661 getTargetMachine().getRelocationModel() != Reloc::Static;
1662 isARMFunc = !Subtarget->isThumb() || isStub;
1663 // ARM call to a local ARM function is predicable.
1664 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1665 // tBX takes a register source operand.
1666 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1668 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1669 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1670 } else if (Subtarget->isTargetCOFF()) {
1671 assert(Subtarget->isTargetWindows() &&
1672 "Windows is the only supported COFF target");
1673 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1674 ? ARMII::MO_DLLIMPORT
1675 : ARMII::MO_NO_FLAG;
1676 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1678 if (GV->hasDLLImportStorageClass())
1679 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1680 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1681 Callee), MachinePointerInfo::getGOT(),
1682 false, false, false, 0);
1684 // On ELF targets for PIC code, direct calls should go through the PLT
1685 unsigned OpFlags = 0;
1686 if (Subtarget->isTargetELF() &&
1687 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1688 OpFlags = ARMII::MO_PLT;
1689 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1691 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1693 bool isStub = Subtarget->isTargetMachO() &&
1694 getTargetMachine().getRelocationModel() != Reloc::Static;
1695 isARMFunc = !Subtarget->isThumb() || isStub;
1696 // tBX takes a register source operand.
1697 const char *Sym = S->getSymbol();
1698 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1699 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1700 ARMConstantPoolValue *CPV =
1701 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1702 ARMPCLabelIndex, 4);
1703 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1704 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1705 Callee = DAG.getLoad(getPointerTy(), dl,
1706 DAG.getEntryNode(), CPAddr,
1707 MachinePointerInfo::getConstantPool(),
1708 false, false, false, 0);
1709 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1710 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1711 getPointerTy(), Callee, PICLabel);
1713 unsigned OpFlags = 0;
1714 // On ELF targets for PIC code, direct calls should go through the PLT
1715 if (Subtarget->isTargetELF() &&
1716 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1717 OpFlags = ARMII::MO_PLT;
1718 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1722 // FIXME: handle tail calls differently.
1724 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1725 AttributeSet::FunctionIndex, Attribute::MinSize);
1726 if (Subtarget->isThumb()) {
1727 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1728 CallOpc = ARMISD::CALL_NOLINK;
1730 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1732 if (!isDirect && !Subtarget->hasV5TOps())
1733 CallOpc = ARMISD::CALL_NOLINK;
1734 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1735 // Emit regular call when code size is the priority
1737 // "mov lr, pc; b _foo" to avoid confusing the RSP
1738 CallOpc = ARMISD::CALL_NOLINK;
1740 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1743 std::vector<SDValue> Ops;
1744 Ops.push_back(Chain);
1745 Ops.push_back(Callee);
1747 // Add argument registers to the end of the list so that they are known live
1749 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1750 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1751 RegsToPass[i].second.getValueType()));
1753 // Add a register mask operand representing the call-preserved registers.
1755 const uint32_t *Mask;
1756 const TargetRegisterInfo *TRI =
1757 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1758 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1760 // For 'this' returns, use the R0-preserving mask if applicable
1761 Mask = ARI->getThisReturnPreservedMask(CallConv);
1763 // Set isThisReturn to false if the calling convention is not one that
1764 // allows 'returned' to be modeled in this way, so LowerCallResult does
1765 // not try to pass 'this' straight through
1766 isThisReturn = false;
1767 Mask = ARI->getCallPreservedMask(CallConv);
1770 Mask = ARI->getCallPreservedMask(CallConv);
1772 assert(Mask && "Missing call preserved mask for calling convention");
1773 Ops.push_back(DAG.getRegisterMask(Mask));
1776 if (InFlag.getNode())
1777 Ops.push_back(InFlag);
1779 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1781 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1783 // Returns a chain and a flag for retval copy to use.
1784 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1785 InFlag = Chain.getValue(1);
1787 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1788 DAG.getIntPtrConstant(0, true), InFlag, dl);
1790 InFlag = Chain.getValue(1);
1792 // Handle result values, copying them out of physregs into vregs that we
1794 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1795 InVals, isThisReturn,
1796 isThisReturn ? OutVals[0] : SDValue());
1799 /// HandleByVal - Every parameter *after* a byval parameter is passed
1800 /// on the stack. Remember the next parameter register to allocate,
1801 /// and then confiscate the rest of the parameter registers to insure
1804 ARMTargetLowering::HandleByVal(
1805 CCState *State, unsigned &size, unsigned Align) const {
1806 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1807 assert((State->getCallOrPrologue() == Prologue ||
1808 State->getCallOrPrologue() == Call) &&
1809 "unhandled ParmContext");
1811 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1812 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1813 unsigned AlignInRegs = Align / 4;
1814 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1815 for (unsigned i = 0; i < Waste; ++i)
1816 reg = State->AllocateReg(GPRArgRegs, 4);
1819 unsigned excess = 4 * (ARM::R4 - reg);
1821 // Special case when NSAA != SP and parameter size greater than size of
1822 // all remained GPR regs. In that case we can't split parameter, we must
1823 // send it to stack. We also must set NCRN to R4, so waste all
1824 // remained registers.
1825 const unsigned NSAAOffset = State->getNextStackOffset();
1826 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1827 while (State->AllocateReg(GPRArgRegs, 4))
1832 // First register for byval parameter is the first register that wasn't
1833 // allocated before this method call, so it would be "reg".
1834 // If parameter is small enough to be saved in range [reg, r4), then
1835 // the end (first after last) register would be reg + param-size-in-regs,
1836 // else parameter would be splitted between registers and stack,
1837 // end register would be r4 in this case.
1838 unsigned ByValRegBegin = reg;
1839 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1840 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1841 // Note, first register is allocated in the beginning of function already,
1842 // allocate remained amount of registers we need.
1843 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1844 State->AllocateReg(GPRArgRegs, 4);
1845 // A byval parameter that is split between registers and memory needs its
1846 // size truncated here.
1847 // In the case where the entire structure fits in registers, we set the
1848 // size in memory to zero.
1857 /// MatchingStackOffset - Return true if the given stack call argument is
1858 /// already available in the same position (relatively) of the caller's
1859 /// incoming argument stack.
1861 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1862 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1863 const TargetInstrInfo *TII) {
1864 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1866 if (Arg.getOpcode() == ISD::CopyFromReg) {
1867 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1868 if (!TargetRegisterInfo::isVirtualRegister(VR))
1870 MachineInstr *Def = MRI->getVRegDef(VR);
1873 if (!Flags.isByVal()) {
1874 if (!TII->isLoadFromStackSlot(Def, FI))
1879 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1880 if (Flags.isByVal())
1881 // ByVal argument is passed in as a pointer but it's now being
1882 // dereferenced. e.g.
1883 // define @foo(%struct.X* %A) {
1884 // tail call @bar(%struct.X* byval %A)
1887 SDValue Ptr = Ld->getBasePtr();
1888 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1891 FI = FINode->getIndex();
1895 assert(FI != INT_MAX);
1896 if (!MFI->isFixedObjectIndex(FI))
1898 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1901 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1902 /// for tail call optimization. Targets which want to do tail call
1903 /// optimization should implement this function.
1905 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1906 CallingConv::ID CalleeCC,
1908 bool isCalleeStructRet,
1909 bool isCallerStructRet,
1910 const SmallVectorImpl<ISD::OutputArg> &Outs,
1911 const SmallVectorImpl<SDValue> &OutVals,
1912 const SmallVectorImpl<ISD::InputArg> &Ins,
1913 SelectionDAG& DAG) const {
1914 const Function *CallerF = DAG.getMachineFunction().getFunction();
1915 CallingConv::ID CallerCC = CallerF->getCallingConv();
1916 bool CCMatch = CallerCC == CalleeCC;
1918 // Look for obvious safe cases to perform tail call optimization that do not
1919 // require ABI changes. This is what gcc calls sibcall.
1921 // Do not sibcall optimize vararg calls unless the call site is not passing
1923 if (isVarArg && !Outs.empty())
1926 // Exception-handling functions need a special set of instructions to indicate
1927 // a return to the hardware. Tail-calling another function would probably
1929 if (CallerF->hasFnAttribute("interrupt"))
1932 // Also avoid sibcall optimization if either caller or callee uses struct
1933 // return semantics.
1934 if (isCalleeStructRet || isCallerStructRet)
1937 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1938 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1939 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1940 // support in the assembler and linker to be used. This would need to be
1941 // fixed to fully support tail calls in Thumb1.
1943 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1944 // LR. This means if we need to reload LR, it takes an extra instructions,
1945 // which outweighs the value of the tail call; but here we don't know yet
1946 // whether LR is going to be used. Probably the right approach is to
1947 // generate the tail call here and turn it back into CALL/RET in
1948 // emitEpilogue if LR is used.
1950 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1951 // but we need to make sure there are enough registers; the only valid
1952 // registers are the 4 used for parameters. We don't currently do this
1954 if (Subtarget->isThumb1Only())
1957 // If the calling conventions do not match, then we'd better make sure the
1958 // results are returned in the same way as what the caller expects.
1960 SmallVector<CCValAssign, 16> RVLocs1;
1961 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1962 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1963 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1965 SmallVector<CCValAssign, 16> RVLocs2;
1966 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1967 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1968 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1970 if (RVLocs1.size() != RVLocs2.size())
1972 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1973 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1975 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1977 if (RVLocs1[i].isRegLoc()) {
1978 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1981 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1987 // If Caller's vararg or byval argument has been split between registers and
1988 // stack, do not perform tail call, since part of the argument is in caller's
1990 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1991 getInfo<ARMFunctionInfo>();
1992 if (AFI_Caller->getArgRegsSaveSize())
1995 // If the callee takes no arguments then go on to check the results of the
1997 if (!Outs.empty()) {
1998 // Check if stack adjustment is needed. For now, do not do this if any
1999 // argument is passed on the stack.
2000 SmallVector<CCValAssign, 16> ArgLocs;
2001 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2002 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2003 CCInfo.AnalyzeCallOperands(Outs,
2004 CCAssignFnForNode(CalleeCC, false, isVarArg));
2005 if (CCInfo.getNextStackOffset()) {
2006 MachineFunction &MF = DAG.getMachineFunction();
2008 // Check if the arguments are already laid out in the right way as
2009 // the caller's fixed stack objects.
2010 MachineFrameInfo *MFI = MF.getFrameInfo();
2011 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2012 const TargetInstrInfo *TII =
2013 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2014 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2016 ++i, ++realArgIdx) {
2017 CCValAssign &VA = ArgLocs[i];
2018 EVT RegVT = VA.getLocVT();
2019 SDValue Arg = OutVals[realArgIdx];
2020 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2021 if (VA.getLocInfo() == CCValAssign::Indirect)
2023 if (VA.needsCustom()) {
2024 // f64 and vector types are split into multiple registers or
2025 // register/stack-slot combinations. The types will not match
2026 // the registers; give up on memory f64 refs until we figure
2027 // out what to do about this.
2030 if (!ArgLocs[++i].isRegLoc())
2032 if (RegVT == MVT::v2f64) {
2033 if (!ArgLocs[++i].isRegLoc())
2035 if (!ArgLocs[++i].isRegLoc())
2038 } else if (!VA.isRegLoc()) {
2039 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2051 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2052 MachineFunction &MF, bool isVarArg,
2053 const SmallVectorImpl<ISD::OutputArg> &Outs,
2054 LLVMContext &Context) const {
2055 SmallVector<CCValAssign, 16> RVLocs;
2056 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2057 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2061 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2062 SDLoc DL, SelectionDAG &DAG) {
2063 const MachineFunction &MF = DAG.getMachineFunction();
2064 const Function *F = MF.getFunction();
2066 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2068 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2069 // version of the "preferred return address". These offsets affect the return
2070 // instruction if this is a return from PL1 without hypervisor extensions.
2071 // IRQ/FIQ: +4 "subs pc, lr, #4"
2072 // SWI: 0 "subs pc, lr, #0"
2073 // ABORT: +4 "subs pc, lr, #4"
2074 // UNDEF: +4/+2 "subs pc, lr, #0"
2075 // UNDEF varies depending on where the exception came from ARM or Thumb
2076 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2079 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2082 else if (IntKind == "SWI" || IntKind == "UNDEF")
2085 report_fatal_error("Unsupported interrupt attribute. If present, value "
2086 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2088 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2090 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2094 ARMTargetLowering::LowerReturn(SDValue Chain,
2095 CallingConv::ID CallConv, bool isVarArg,
2096 const SmallVectorImpl<ISD::OutputArg> &Outs,
2097 const SmallVectorImpl<SDValue> &OutVals,
2098 SDLoc dl, SelectionDAG &DAG) const {
2100 // CCValAssign - represent the assignment of the return value to a location.
2101 SmallVector<CCValAssign, 16> RVLocs;
2103 // CCState - Info about the registers and stack slots.
2104 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2105 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2107 // Analyze outgoing return values.
2108 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2112 SmallVector<SDValue, 4> RetOps;
2113 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2114 bool isLittleEndian = Subtarget->isLittle();
2116 // Copy the result values into the output registers.
2117 for (unsigned i = 0, realRVLocIdx = 0;
2119 ++i, ++realRVLocIdx) {
2120 CCValAssign &VA = RVLocs[i];
2121 assert(VA.isRegLoc() && "Can only return in registers!");
2123 SDValue Arg = OutVals[realRVLocIdx];
2125 switch (VA.getLocInfo()) {
2126 default: llvm_unreachable("Unknown loc info!");
2127 case CCValAssign::Full: break;
2128 case CCValAssign::BCvt:
2129 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2133 if (VA.needsCustom()) {
2134 if (VA.getLocVT() == MVT::v2f64) {
2135 // Extract the first half and return it in two registers.
2136 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2137 DAG.getConstant(0, MVT::i32));
2138 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2139 DAG.getVTList(MVT::i32, MVT::i32), Half);
2141 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2142 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2144 Flag = Chain.getValue(1);
2145 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2146 VA = RVLocs[++i]; // skip ahead to next loc
2147 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2148 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2150 Flag = Chain.getValue(1);
2151 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2152 VA = RVLocs[++i]; // skip ahead to next loc
2154 // Extract the 2nd half and fall through to handle it as an f64 value.
2155 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2156 DAG.getConstant(1, MVT::i32));
2158 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2160 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2161 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2162 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2163 fmrrd.getValue(isLittleEndian ? 0 : 1),
2165 Flag = Chain.getValue(1);
2166 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2167 VA = RVLocs[++i]; // skip ahead to next loc
2168 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2169 fmrrd.getValue(isLittleEndian ? 1 : 0),
2172 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2174 // Guarantee that all emitted copies are
2175 // stuck together, avoiding something bad.
2176 Flag = Chain.getValue(1);
2177 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2180 // Update chain and glue.
2183 RetOps.push_back(Flag);
2185 // CPUs which aren't M-class use a special sequence to return from
2186 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2187 // though we use "subs pc, lr, #N").
2189 // M-class CPUs actually use a normal return sequence with a special
2190 // (hardware-provided) value in LR, so the normal code path works.
2191 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2192 !Subtarget->isMClass()) {
2193 if (Subtarget->isThumb1Only())
2194 report_fatal_error("interrupt attribute is not supported in Thumb1");
2195 return LowerInterruptReturn(RetOps, dl, DAG);
2198 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2201 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2202 if (N->getNumValues() != 1)
2204 if (!N->hasNUsesOfValue(1, 0))
2207 SDValue TCChain = Chain;
2208 SDNode *Copy = *N->use_begin();
2209 if (Copy->getOpcode() == ISD::CopyToReg) {
2210 // If the copy has a glue operand, we conservatively assume it isn't safe to
2211 // perform a tail call.
2212 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2214 TCChain = Copy->getOperand(0);
2215 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2216 SDNode *VMov = Copy;
2217 // f64 returned in a pair of GPRs.
2218 SmallPtrSet<SDNode*, 2> Copies;
2219 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2221 if (UI->getOpcode() != ISD::CopyToReg)
2225 if (Copies.size() > 2)
2228 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2230 SDValue UseChain = UI->getOperand(0);
2231 if (Copies.count(UseChain.getNode()))
2238 } else if (Copy->getOpcode() == ISD::BITCAST) {
2239 // f32 returned in a single GPR.
2240 if (!Copy->hasOneUse())
2242 Copy = *Copy->use_begin();
2243 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2245 TCChain = Copy->getOperand(0);
2250 bool HasRet = false;
2251 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2253 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2254 UI->getOpcode() != ARMISD::INTRET_FLAG)
2266 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2267 if (!Subtarget->supportsTailCall())
2270 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2273 return !Subtarget->isThumb1Only();
2276 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2277 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2278 // one of the above mentioned nodes. It has to be wrapped because otherwise
2279 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2280 // be used to form addressing mode. These wrapped nodes will be selected
2282 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2283 EVT PtrVT = Op.getValueType();
2284 // FIXME there is no actual debug info here
2286 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2288 if (CP->isMachineConstantPoolEntry())
2289 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2290 CP->getAlignment());
2292 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2293 CP->getAlignment());
2294 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2297 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2298 return MachineJumpTableInfo::EK_Inline;
2301 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2302 SelectionDAG &DAG) const {
2303 MachineFunction &MF = DAG.getMachineFunction();
2304 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305 unsigned ARMPCLabelIndex = 0;
2307 EVT PtrVT = getPointerTy();
2308 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2309 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2311 if (RelocM == Reloc::Static) {
2312 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2314 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2315 ARMPCLabelIndex = AFI->createPICLabelUId();
2316 ARMConstantPoolValue *CPV =
2317 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2318 ARMCP::CPBlockAddress, PCAdj);
2319 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2321 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2322 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2323 MachinePointerInfo::getConstantPool(),
2324 false, false, false, 0);
2325 if (RelocM == Reloc::Static)
2327 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2328 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2331 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2333 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2334 SelectionDAG &DAG) const {
2336 EVT PtrVT = getPointerTy();
2337 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2338 MachineFunction &MF = DAG.getMachineFunction();
2339 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2340 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2341 ARMConstantPoolValue *CPV =
2342 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2343 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2344 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2345 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2346 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2347 MachinePointerInfo::getConstantPool(),
2348 false, false, false, 0);
2349 SDValue Chain = Argument.getValue(1);
2351 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2352 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2354 // call __tls_get_addr.
2357 Entry.Node = Argument;
2358 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2359 Args.push_back(Entry);
2361 // FIXME: is there useful debug info available here?
2362 TargetLowering::CallLoweringInfo CLI(DAG);
2363 CLI.setDebugLoc(dl).setChain(Chain)
2364 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2365 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2368 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2369 return CallResult.first;
2372 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2373 // "local exec" model.
2375 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2377 TLSModel::Model model) const {
2378 const GlobalValue *GV = GA->getGlobal();
2381 SDValue Chain = DAG.getEntryNode();
2382 EVT PtrVT = getPointerTy();
2383 // Get the Thread Pointer
2384 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2386 if (model == TLSModel::InitialExec) {
2387 MachineFunction &MF = DAG.getMachineFunction();
2388 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2389 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2390 // Initial exec model.
2391 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2392 ARMConstantPoolValue *CPV =
2393 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2394 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2396 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2397 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2398 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2399 MachinePointerInfo::getConstantPool(),
2400 false, false, false, 0);
2401 Chain = Offset.getValue(1);
2403 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2404 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2406 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2407 MachinePointerInfo::getConstantPool(),
2408 false, false, false, 0);
2411 assert(model == TLSModel::LocalExec);
2412 ARMConstantPoolValue *CPV =
2413 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2414 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2416 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2417 MachinePointerInfo::getConstantPool(),
2418 false, false, false, 0);
2421 // The address of the thread local variable is the add of the thread
2422 // pointer with the offset of the variable.
2423 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2427 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2428 // TODO: implement the "local dynamic" model
2429 assert(Subtarget->isTargetELF() &&
2430 "TLS not implemented for non-ELF targets");
2431 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2433 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2436 case TLSModel::GeneralDynamic:
2437 case TLSModel::LocalDynamic:
2438 return LowerToTLSGeneralDynamicModel(GA, DAG);
2439 case TLSModel::InitialExec:
2440 case TLSModel::LocalExec:
2441 return LowerToTLSExecModels(GA, DAG, model);
2443 llvm_unreachable("bogus TLS model");
2446 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2447 SelectionDAG &DAG) const {
2448 EVT PtrVT = getPointerTy();
2450 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2451 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2452 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2453 ARMConstantPoolValue *CPV =
2454 ARMConstantPoolConstant::Create(GV,
2455 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2456 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2457 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2458 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2460 MachinePointerInfo::getConstantPool(),
2461 false, false, false, 0);
2462 SDValue Chain = Result.getValue(1);
2463 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2464 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2466 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2467 MachinePointerInfo::getGOT(),
2468 false, false, false, 0);
2472 // If we have T2 ops, we can materialize the address directly via movt/movw
2473 // pair. This is always cheaper.
2474 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2476 // FIXME: Once remat is capable of dealing with instructions with register
2477 // operands, expand this into two nodes.
2478 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2479 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2481 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2482 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2483 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2484 MachinePointerInfo::getConstantPool(),
2485 false, false, false, 0);
2489 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2490 SelectionDAG &DAG) const {
2491 EVT PtrVT = getPointerTy();
2493 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2494 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2496 if (Subtarget->useMovt(DAG.getMachineFunction()))
2499 // FIXME: Once remat is capable of dealing with instructions with register
2500 // operands, expand this into multiple nodes
2502 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2504 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2505 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2507 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2508 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2509 MachinePointerInfo::getGOT(), false, false, false, 0);
2513 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2514 SelectionDAG &DAG) const {
2515 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2516 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2517 "Windows on ARM expects to use movw/movt");
2519 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2520 const ARMII::TOF TargetFlags =
2521 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2522 EVT PtrVT = getPointerTy();
2528 // FIXME: Once remat is capable of dealing with instructions with register
2529 // operands, expand this into two nodes.
2530 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2531 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2533 if (GV->hasDLLImportStorageClass())
2534 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2535 MachinePointerInfo::getGOT(), false, false, false, 0);
2539 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2540 SelectionDAG &DAG) const {
2541 assert(Subtarget->isTargetELF() &&
2542 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2543 MachineFunction &MF = DAG.getMachineFunction();
2544 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2545 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2546 EVT PtrVT = getPointerTy();
2548 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2549 ARMConstantPoolValue *CPV =
2550 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2551 ARMPCLabelIndex, PCAdj);
2552 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2553 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2554 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2555 MachinePointerInfo::getConstantPool(),
2556 false, false, false, 0);
2557 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2558 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2562 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2564 SDValue Val = DAG.getConstant(0, MVT::i32);
2565 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2566 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2567 Op.getOperand(1), Val);
2571 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2573 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2574 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2578 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2579 const ARMSubtarget *Subtarget) const {
2580 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2583 default: return SDValue(); // Don't custom lower most intrinsics.
2584 case Intrinsic::arm_rbit: {
2585 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2586 "RBIT intrinsic must have i32 type!");
2587 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2589 case Intrinsic::arm_thread_pointer: {
2590 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2591 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2593 case Intrinsic::eh_sjlj_lsda: {
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2596 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2597 EVT PtrVT = getPointerTy();
2598 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2600 unsigned PCAdj = (RelocM != Reloc::PIC_)
2601 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2602 ARMConstantPoolValue *CPV =
2603 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2604 ARMCP::CPLSDA, PCAdj);
2605 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2606 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2608 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2609 MachinePointerInfo::getConstantPool(),
2610 false, false, false, 0);
2612 if (RelocM == Reloc::PIC_) {
2613 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2614 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2618 case Intrinsic::arm_neon_vmulls:
2619 case Intrinsic::arm_neon_vmullu: {
2620 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2621 ? ARMISD::VMULLs : ARMISD::VMULLu;
2622 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2623 Op.getOperand(1), Op.getOperand(2));
2628 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2629 const ARMSubtarget *Subtarget) {
2630 // FIXME: handle "fence singlethread" more efficiently.
2632 if (!Subtarget->hasDataBarrier()) {
2633 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2634 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2636 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2637 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2638 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2639 DAG.getConstant(0, MVT::i32));
2642 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2643 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2644 unsigned Domain = ARM_MB::ISH;
2645 if (Subtarget->isMClass()) {
2646 // Only a full system barrier exists in the M-class architectures.
2647 Domain = ARM_MB::SY;
2648 } else if (Subtarget->isSwift() && Ord == Release) {
2649 // Swift happens to implement ISHST barriers in a way that's compatible with
2650 // Release semantics but weaker than ISH so we'd be fools not to use
2651 // it. Beware: other processors probably don't!
2652 Domain = ARM_MB::ISHST;
2655 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2656 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2657 DAG.getConstant(Domain, MVT::i32));
2660 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2661 const ARMSubtarget *Subtarget) {
2662 // ARM pre v5TE and Thumb1 does not have preload instructions.
2663 if (!(Subtarget->isThumb2() ||
2664 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2665 // Just preserve the chain.
2666 return Op.getOperand(0);
2669 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2671 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2672 // ARMv7 with MP extension has PLDW.
2673 return Op.getOperand(0);
2675 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2676 if (Subtarget->isThumb()) {
2678 isRead = ~isRead & 1;
2679 isData = ~isData & 1;
2682 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2683 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2684 DAG.getConstant(isData, MVT::i32));
2687 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2688 MachineFunction &MF = DAG.getMachineFunction();
2689 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2691 // vastart just stores the address of the VarArgsFrameIndex slot into the
2692 // memory location argument.
2694 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2695 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2696 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2697 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2698 MachinePointerInfo(SV), false, false, 0);
2702 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2703 SDValue &Root, SelectionDAG &DAG,
2705 MachineFunction &MF = DAG.getMachineFunction();
2706 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2708 const TargetRegisterClass *RC;
2709 if (AFI->isThumb1OnlyFunction())
2710 RC = &ARM::tGPRRegClass;
2712 RC = &ARM::GPRRegClass;
2714 // Transform the arguments stored in physical registers into virtual ones.
2715 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2716 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2719 if (NextVA.isMemLoc()) {
2720 MachineFrameInfo *MFI = MF.getFrameInfo();
2721 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2723 // Create load node to retrieve arguments from the stack.
2724 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2725 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2726 MachinePointerInfo::getFixedStack(FI),
2727 false, false, false, 0);
2729 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2730 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2732 if (!Subtarget->isLittle())
2733 std::swap (ArgValue, ArgValue2);
2734 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2738 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2739 unsigned InRegsParamRecordIdx,
2741 unsigned &ArgRegsSize,
2742 unsigned &ArgRegsSaveSize)
2745 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2746 unsigned RBegin, REnd;
2747 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2748 NumGPRs = REnd - RBegin;
2750 unsigned int firstUnalloced;
2751 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2752 sizeof(GPRArgRegs) /
2753 sizeof(GPRArgRegs[0]));
2754 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2757 unsigned Align = MF.getTarget()
2759 ->getFrameLowering()
2760 ->getStackAlignment();
2761 ArgRegsSize = NumGPRs * 4;
2763 // If parameter is split between stack and GPRs...
2764 if (NumGPRs && Align > 4 &&
2765 (ArgRegsSize < ArgSize ||
2766 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2767 // Add padding for part of param recovered from GPRs. For example,
2768 // if Align == 8, its last byte must be at address K*8 - 1.
2769 // We need to do it, since remained (stack) part of parameter has
2770 // stack alignment, and we need to "attach" "GPRs head" without gaps
2773 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2774 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2776 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2778 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2779 ArgRegsSaveSize = ArgRegsSize + Padding;
2781 // We don't need to extend regs save size for byval parameters if they
2782 // are passed via GPRs only.
2783 ArgRegsSaveSize = ArgRegsSize;
2786 // The remaining GPRs hold either the beginning of variable-argument
2787 // data, or the beginning of an aggregate passed by value (usually
2788 // byval). Either way, we allocate stack slots adjacent to the data
2789 // provided by our caller, and store the unallocated registers there.
2790 // If this is a variadic function, the va_list pointer will begin with
2791 // these values; otherwise, this reassembles a (byval) structure that
2792 // was split between registers and memory.
2793 // Return: The frame index registers were stored into.
2795 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2796 SDLoc dl, SDValue &Chain,
2797 const Value *OrigArg,
2798 unsigned InRegsParamRecordIdx,
2799 unsigned OffsetFromOrigArg,
2803 unsigned ByValStoreOffset,
2804 unsigned TotalArgRegsSaveSize) const {
2806 // Currently, two use-cases possible:
2807 // Case #1. Non-var-args function, and we meet first byval parameter.
2808 // Setup first unallocated register as first byval register;
2809 // eat all remained registers
2810 // (these two actions are performed by HandleByVal method).
2811 // Then, here, we initialize stack frame with
2812 // "store-reg" instructions.
2813 // Case #2. Var-args function, that doesn't contain byval parameters.
2814 // The same: eat all remained unallocated registers,
2815 // initialize stack frame.
2817 MachineFunction &MF = DAG.getMachineFunction();
2818 MachineFrameInfo *MFI = MF.getFrameInfo();
2819 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2820 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2821 unsigned RBegin, REnd;
2822 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2823 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2824 firstRegToSaveIndex = RBegin - ARM::R0;
2825 lastRegToSaveIndex = REnd - ARM::R0;
2827 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2828 (GPRArgRegs, array_lengthof(GPRArgRegs));
2829 lastRegToSaveIndex = 4;
2832 unsigned ArgRegsSize, ArgRegsSaveSize;
2833 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2834 ArgRegsSize, ArgRegsSaveSize);
2836 // Store any by-val regs to their spots on the stack so that they may be
2837 // loaded by deferencing the result of formal parameter pointer or va_next.
2838 // Note: once stack area for byval/varargs registers
2839 // was initialized, it can't be initialized again.
2840 if (ArgRegsSaveSize) {
2841 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2844 assert(AFI->getStoredByValParamsPadding() == 0 &&
2845 "The only parameter may be padded.");
2846 AFI->setStoredByValParamsPadding(Padding);
2849 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2852 (int64_t)TotalArgRegsSaveSize,
2854 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2856 MFI->CreateFixedObject(Padding,
2857 ArgOffset + ByValStoreOffset -
2858 (int64_t)ArgRegsSaveSize,
2862 SmallVector<SDValue, 4> MemOps;
2863 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2864 ++firstRegToSaveIndex, ++i) {
2865 const TargetRegisterClass *RC;
2866 if (AFI->isThumb1OnlyFunction())
2867 RC = &ARM::tGPRRegClass;
2869 RC = &ARM::GPRRegClass;
2871 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2872 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2874 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2875 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2877 MemOps.push_back(Store);
2878 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2879 DAG.getConstant(4, getPointerTy()));
2882 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2884 if (!MemOps.empty())
2885 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2889 // We cannot allocate a zero-byte object for the first variadic argument,
2890 // so just make up a size.
2893 // This will point to the next argument passed via stack.
2894 return MFI->CreateFixedObject(
2895 ArgSize, ArgOffset, !ForceMutable);
2899 // Setup stack frame, the va_list pointer will start from.
2901 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2902 SDLoc dl, SDValue &Chain,
2904 unsigned TotalArgRegsSaveSize,
2905 bool ForceMutable) const {
2906 MachineFunction &MF = DAG.getMachineFunction();
2907 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2909 // Try to store any remaining integer argument regs
2910 // to their spots on the stack so that they may be loaded by deferencing
2911 // the result of va_next.
2912 // If there is no regs to be stored, just point address after last
2913 // argument passed via stack.
2915 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2916 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2917 0, TotalArgRegsSaveSize);
2919 AFI->setVarArgsFrameIndex(FrameIndex);
2923 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2924 CallingConv::ID CallConv, bool isVarArg,
2925 const SmallVectorImpl<ISD::InputArg>
2927 SDLoc dl, SelectionDAG &DAG,
2928 SmallVectorImpl<SDValue> &InVals)
2930 MachineFunction &MF = DAG.getMachineFunction();
2931 MachineFrameInfo *MFI = MF.getFrameInfo();
2933 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2935 // Assign locations to all of the incoming arguments.
2936 SmallVector<CCValAssign, 16> ArgLocs;
2937 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2938 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2939 CCInfo.AnalyzeFormalArguments(Ins,
2940 CCAssignFnForNode(CallConv, /* Return*/ false,
2943 SmallVector<SDValue, 16> ArgValues;
2944 int lastInsIndex = -1;
2946 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2947 unsigned CurArgIdx = 0;
2949 // Initially ArgRegsSaveSize is zero.
2950 // Then we increase this value each time we meet byval parameter.
2951 // We also increase this value in case of varargs function.
2952 AFI->setArgRegsSaveSize(0);
2954 unsigned ByValStoreOffset = 0;
2955 unsigned TotalArgRegsSaveSize = 0;
2956 unsigned ArgRegsSaveSizeMaxAlign = 4;
2958 // Calculate the amount of stack space that we need to allocate to store
2959 // byval and variadic arguments that are passed in registers.
2960 // We need to know this before we allocate the first byval or variadic
2961 // argument, as they will be allocated a stack slot below the CFA (Canonical
2962 // Frame Address, the stack pointer at entry to the function).
2963 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2964 CCValAssign &VA = ArgLocs[i];
2965 if (VA.isMemLoc()) {
2966 int index = VA.getValNo();
2967 if (index != lastInsIndex) {
2968 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2969 if (Flags.isByVal()) {
2970 unsigned ExtraArgRegsSize;
2971 unsigned ExtraArgRegsSaveSize;
2972 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2973 Flags.getByValSize(),
2974 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2976 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2977 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2978 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2979 CCInfo.nextInRegsParam();
2981 lastInsIndex = index;
2985 CCInfo.rewindByValRegsInfo();
2988 unsigned ExtraArgRegsSize;
2989 unsigned ExtraArgRegsSaveSize;
2990 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2991 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2992 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2994 // If the arg regs save area contains N-byte aligned values, the
2995 // bottom of it must be at least N-byte aligned.
2996 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2997 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2999 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3000 CCValAssign &VA = ArgLocs[i];
3001 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3002 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3003 // Arguments stored in registers.
3004 if (VA.isRegLoc()) {
3005 EVT RegVT = VA.getLocVT();
3007 if (VA.needsCustom()) {
3008 // f64 and vector types are split up into multiple registers or
3009 // combinations of registers and stack slots.
3010 if (VA.getLocVT() == MVT::v2f64) {
3011 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3013 VA = ArgLocs[++i]; // skip ahead to next loc
3015 if (VA.isMemLoc()) {
3016 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3017 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3018 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3019 MachinePointerInfo::getFixedStack(FI),
3020 false, false, false, 0);
3022 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3025 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3026 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3027 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3028 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3029 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3031 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3034 const TargetRegisterClass *RC;
3036 if (RegVT == MVT::f32)
3037 RC = &ARM::SPRRegClass;
3038 else if (RegVT == MVT::f64)
3039 RC = &ARM::DPRRegClass;
3040 else if (RegVT == MVT::v2f64)
3041 RC = &ARM::QPRRegClass;
3042 else if (RegVT == MVT::i32)
3043 RC = AFI->isThumb1OnlyFunction() ?
3044 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3045 (const TargetRegisterClass*)&ARM::GPRRegClass;
3047 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3049 // Transform the arguments in physical registers into virtual ones.
3050 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3051 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3054 // If this is an 8 or 16-bit value, it is really passed promoted
3055 // to 32 bits. Insert an assert[sz]ext to capture this, then
3056 // truncate to the right size.
3057 switch (VA.getLocInfo()) {
3058 default: llvm_unreachable("Unknown loc info!");
3059 case CCValAssign::Full: break;
3060 case CCValAssign::BCvt:
3061 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3063 case CCValAssign::SExt:
3064 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3065 DAG.getValueType(VA.getValVT()));
3066 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3068 case CCValAssign::ZExt:
3069 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3070 DAG.getValueType(VA.getValVT()));
3071 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3075 InVals.push_back(ArgValue);
3077 } else { // VA.isRegLoc()
3080 assert(VA.isMemLoc());
3081 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3083 int index = ArgLocs[i].getValNo();
3085 // Some Ins[] entries become multiple ArgLoc[] entries.
3086 // Process them only once.
3087 if (index != lastInsIndex)
3089 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3090 // FIXME: For now, all byval parameter objects are marked mutable.
3091 // This can be changed with more analysis.
3092 // In case of tail call optimization mark all arguments mutable.
3093 // Since they could be overwritten by lowering of arguments in case of
3095 if (Flags.isByVal()) {
3096 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3098 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3099 int FrameIndex = StoreByValRegs(
3100 CCInfo, DAG, dl, Chain, CurOrigArg,
3102 Ins[VA.getValNo()].PartOffset,
3103 VA.getLocMemOffset(),
3104 Flags.getByValSize(),
3105 true /*force mutable frames*/,
3107 TotalArgRegsSaveSize);
3108 ByValStoreOffset += Flags.getByValSize();
3109 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3110 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3111 CCInfo.nextInRegsParam();
3113 unsigned FIOffset = VA.getLocMemOffset();
3114 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3117 // Create load nodes to retrieve arguments from the stack.
3118 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3119 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3120 MachinePointerInfo::getFixedStack(FI),
3121 false, false, false, 0));
3123 lastInsIndex = index;
3130 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3131 CCInfo.getNextStackOffset(),
3132 TotalArgRegsSaveSize);
3134 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3139 /// isFloatingPointZero - Return true if this is +0.0.
3140 static bool isFloatingPointZero(SDValue Op) {
3141 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3142 return CFP->getValueAPF().isPosZero();
3143 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3144 // Maybe this has already been legalized into the constant pool?
3145 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3146 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3147 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3148 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3149 return CFP->getValueAPF().isPosZero();
3155 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3156 /// the given operands.
3158 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3159 SDValue &ARMcc, SelectionDAG &DAG,
3161 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3162 unsigned C = RHSC->getZExtValue();
3163 if (!isLegalICmpImmediate(C)) {
3164 // Constant does not fit, try adjusting it by one?
3169 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3170 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3171 RHS = DAG.getConstant(C-1, MVT::i32);
3176 if (C != 0 && isLegalICmpImmediate(C-1)) {
3177 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3178 RHS = DAG.getConstant(C-1, MVT::i32);
3183 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3184 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3185 RHS = DAG.getConstant(C+1, MVT::i32);
3190 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3191 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3192 RHS = DAG.getConstant(C+1, MVT::i32);
3199 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3200 ARMISD::NodeType CompareType;
3203 CompareType = ARMISD::CMP;
3208 CompareType = ARMISD::CMPZ;
3211 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3212 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3215 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3217 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3220 if (!isFloatingPointZero(RHS))
3221 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3223 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3224 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3227 /// duplicateCmp - Glue values can have only one use, so this function
3228 /// duplicates a comparison node.
3230 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3231 unsigned Opc = Cmp.getOpcode();
3233 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3234 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3236 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3237 Cmp = Cmp.getOperand(0);
3238 Opc = Cmp.getOpcode();
3239 if (Opc == ARMISD::CMPFP)
3240 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3242 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3243 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3245 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3248 std::pair<SDValue, SDValue>
3249 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3250 SDValue &ARMcc) const {
3251 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3253 SDValue Value, OverflowCmp;
3254 SDValue LHS = Op.getOperand(0);
3255 SDValue RHS = Op.getOperand(1);
3258 // FIXME: We are currently always generating CMPs because we don't support
3259 // generating CMN through the backend. This is not as good as the natural
3260 // CMP case because it causes a register dependency and cannot be folded
3263 switch (Op.getOpcode()) {
3265 llvm_unreachable("Unknown overflow instruction!");
3267 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3268 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3269 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3272 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3273 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3277 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3278 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3279 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3282 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3283 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3284 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3288 return std::make_pair(Value, OverflowCmp);
3293 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3294 // Let legalize expand this if it isn't a legal type yet.
3295 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3298 SDValue Value, OverflowCmp;
3300 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3301 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3302 // We use 0 and 1 as false and true values.
3303 SDValue TVal = DAG.getConstant(1, MVT::i32);
3304 SDValue FVal = DAG.getConstant(0, MVT::i32);
3305 EVT VT = Op.getValueType();
3307 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3308 ARMcc, CCR, OverflowCmp);
3310 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3311 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3315 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3316 SDValue Cond = Op.getOperand(0);
3317 SDValue SelectTrue = Op.getOperand(1);
3318 SDValue SelectFalse = Op.getOperand(2);
3320 unsigned Opc = Cond.getOpcode();
3322 if (Cond.getResNo() == 1 &&
3323 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3324 Opc == ISD::USUBO)) {
3325 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3328 SDValue Value, OverflowCmp;
3330 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3331 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3332 EVT VT = Op.getValueType();
3334 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3335 ARMcc, CCR, OverflowCmp);
3341 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3342 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3344 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3345 const ConstantSDNode *CMOVTrue =
3346 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3347 const ConstantSDNode *CMOVFalse =
3348 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3350 if (CMOVTrue && CMOVFalse) {
3351 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3352 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3356 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3358 False = SelectFalse;
3359 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3364 if (True.getNode() && False.getNode()) {
3365 EVT VT = Op.getValueType();
3366 SDValue ARMcc = Cond.getOperand(2);
3367 SDValue CCR = Cond.getOperand(3);
3368 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3369 assert(True.getValueType() == VT);
3370 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3375 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3376 // undefined bits before doing a full-word comparison with zero.
3377 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3378 DAG.getConstant(1, Cond.getValueType()));
3380 return DAG.getSelectCC(dl, Cond,
3381 DAG.getConstant(0, Cond.getValueType()),
3382 SelectTrue, SelectFalse, ISD::SETNE);
3385 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3386 if (CC == ISD::SETNE)
3388 return ISD::getSetCCInverse(CC, true);
3391 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3392 bool &swpCmpOps, bool &swpVselOps) {
3393 // Start by selecting the GE condition code for opcodes that return true for
3395 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3397 CondCode = ARMCC::GE;
3399 // and GT for opcodes that return false for 'equality'.
3400 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3402 CondCode = ARMCC::GT;
3404 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3405 // to swap the compare operands.
3406 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3410 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3411 // If we have an unordered opcode, we need to swap the operands to the VSEL
3412 // instruction (effectively negating the condition).
3414 // This also has the effect of swapping which one of 'less' or 'greater'
3415 // returns true, so we also swap the compare operands. It also switches
3416 // whether we return true for 'equality', so we compensate by picking the
3417 // opposite condition code to our original choice.
3418 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3419 CC == ISD::SETUGT) {
3420 swpCmpOps = !swpCmpOps;
3421 swpVselOps = !swpVselOps;
3422 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3425 // 'ordered' is 'anything but unordered', so use the VS condition code and
3426 // swap the VSEL operands.
3427 if (CC == ISD::SETO) {
3428 CondCode = ARMCC::VS;
3432 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3433 // code and swap the VSEL operands.
3434 if (CC == ISD::SETUNE) {
3435 CondCode = ARMCC::EQ;
3440 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3441 EVT VT = Op.getValueType();
3442 SDValue LHS = Op.getOperand(0);
3443 SDValue RHS = Op.getOperand(1);
3444 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3445 SDValue TrueVal = Op.getOperand(2);
3446 SDValue FalseVal = Op.getOperand(3);
3449 if (LHS.getValueType() == MVT::i32) {
3450 // Try to generate VSEL on ARMv8.
3451 // The VSEL instruction can't use all the usual ARM condition
3452 // codes: it only has two bits to select the condition code, so it's
3453 // constrained to use only GE, GT, VS and EQ.
3455 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3456 // swap the operands of the previous compare instruction (effectively
3457 // inverting the compare condition, swapping 'less' and 'greater') and
3458 // sometimes need to swap the operands to the VSEL (which inverts the
3459 // condition in the sense of firing whenever the previous condition didn't)
3460 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3461 TrueVal.getValueType() == MVT::f64)) {
3462 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3463 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3464 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3465 CC = getInverseCCForVSEL(CC);
3466 std::swap(TrueVal, FalseVal);
3471 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3472 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3473 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3477 ARMCC::CondCodes CondCode, CondCode2;
3478 FPCCToARMCC(CC, CondCode, CondCode2);
3480 // Try to generate VSEL on ARMv8.
3481 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3482 TrueVal.getValueType() == MVT::f64)) {
3483 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3484 // same operands, as follows:
3485 // c = fcmp [ogt, olt, ugt, ult] a, b
3487 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3488 // handled differently than the original code sequence.
3489 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3491 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3492 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3493 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3494 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3497 bool swpCmpOps = false;
3498 bool swpVselOps = false;
3499 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3501 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3502 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3504 std::swap(LHS, RHS);
3506 std::swap(TrueVal, FalseVal);
3510 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3511 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3512 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3513 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3515 if (CondCode2 != ARMCC::AL) {
3516 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3517 // FIXME: Needs another CMP because flag can have but one use.
3518 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3519 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3520 Result, TrueVal, ARMcc2, CCR, Cmp2);
3525 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3526 /// to morph to an integer compare sequence.
3527 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3528 const ARMSubtarget *Subtarget) {
3529 SDNode *N = Op.getNode();
3530 if (!N->hasOneUse())
3531 // Otherwise it requires moving the value from fp to integer registers.
3533 if (!N->getNumValues())
3535 EVT VT = Op.getValueType();
3536 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3537 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3538 // vmrs are very slow, e.g. cortex-a8.
3541 if (isFloatingPointZero(Op)) {
3545 return ISD::isNormalLoad(N);
3548 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3549 if (isFloatingPointZero(Op))
3550 return DAG.getConstant(0, MVT::i32);
3552 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3553 return DAG.getLoad(MVT::i32, SDLoc(Op),
3554 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3555 Ld->isVolatile(), Ld->isNonTemporal(),
3556 Ld->isInvariant(), Ld->getAlignment());
3558 llvm_unreachable("Unknown VFP cmp argument!");
3561 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3562 SDValue &RetVal1, SDValue &RetVal2) {
3563 if (isFloatingPointZero(Op)) {
3564 RetVal1 = DAG.getConstant(0, MVT::i32);
3565 RetVal2 = DAG.getConstant(0, MVT::i32);
3569 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3570 SDValue Ptr = Ld->getBasePtr();
3571 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3572 Ld->getChain(), Ptr,
3573 Ld->getPointerInfo(),
3574 Ld->isVolatile(), Ld->isNonTemporal(),
3575 Ld->isInvariant(), Ld->getAlignment());
3577 EVT PtrType = Ptr.getValueType();
3578 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3579 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3580 PtrType, Ptr, DAG.getConstant(4, PtrType));
3581 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3582 Ld->getChain(), NewPtr,
3583 Ld->getPointerInfo().getWithOffset(4),
3584 Ld->isVolatile(), Ld->isNonTemporal(),
3585 Ld->isInvariant(), NewAlign);
3589 llvm_unreachable("Unknown VFP cmp argument!");
3592 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3593 /// f32 and even f64 comparisons to integer ones.
3595 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3596 SDValue Chain = Op.getOperand(0);
3597 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3598 SDValue LHS = Op.getOperand(2);
3599 SDValue RHS = Op.getOperand(3);
3600 SDValue Dest = Op.getOperand(4);
3603 bool LHSSeenZero = false;
3604 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3605 bool RHSSeenZero = false;
3606 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3607 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3608 // If unsafe fp math optimization is enabled and there are no other uses of
3609 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3610 // to an integer comparison.
3611 if (CC == ISD::SETOEQ)
3613 else if (CC == ISD::SETUNE)
3616 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3618 if (LHS.getValueType() == MVT::f32) {
3619 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3620 bitcastf32Toi32(LHS, DAG), Mask);
3621 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3622 bitcastf32Toi32(RHS, DAG), Mask);
3623 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3624 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3625 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3626 Chain, Dest, ARMcc, CCR, Cmp);
3631 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3632 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3633 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3634 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3635 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3636 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3637 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3638 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3639 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3645 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3646 SDValue Chain = Op.getOperand(0);
3647 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3648 SDValue LHS = Op.getOperand(2);
3649 SDValue RHS = Op.getOperand(3);
3650 SDValue Dest = Op.getOperand(4);
3653 if (LHS.getValueType() == MVT::i32) {
3655 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3656 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3657 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3658 Chain, Dest, ARMcc, CCR, Cmp);
3661 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3663 if (getTargetMachine().Options.UnsafeFPMath &&
3664 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3665 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3666 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3667 if (Result.getNode())
3671 ARMCC::CondCodes CondCode, CondCode2;
3672 FPCCToARMCC(CC, CondCode, CondCode2);
3674 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3675 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3676 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3677 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3678 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3679 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3680 if (CondCode2 != ARMCC::AL) {
3681 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3682 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3683 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3688 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3689 SDValue Chain = Op.getOperand(0);
3690 SDValue Table = Op.getOperand(1);
3691 SDValue Index = Op.getOperand(2);
3694 EVT PTy = getPointerTy();
3695 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3696 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3697 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3698 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3699 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3700 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3701 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3702 if (Subtarget->isThumb2()) {
3703 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3704 // which does another jump to the destination. This also makes it easier
3705 // to translate it to TBB / TBH later.
3706 // FIXME: This might not work if the function is extremely large.
3707 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3708 Addr, Op.getOperand(2), JTI, UId);
3710 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3711 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3712 MachinePointerInfo::getJumpTable(),
3713 false, false, false, 0);
3714 Chain = Addr.getValue(1);
3715 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3716 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3718 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3719 MachinePointerInfo::getJumpTable(),
3720 false, false, false, 0);
3721 Chain = Addr.getValue(1);
3722 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3726 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3727 EVT VT = Op.getValueType();
3730 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3731 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3733 return DAG.UnrollVectorOp(Op.getNode());
3736 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3737 "Invalid type for custom lowering!");
3738 if (VT != MVT::v4i16)
3739 return DAG.UnrollVectorOp(Op.getNode());
3741 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3742 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3745 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3746 EVT VT = Op.getValueType();
3748 return LowerVectorFP_TO_INT(Op, DAG);
3753 switch (Op.getOpcode()) {
3754 default: llvm_unreachable("Invalid opcode!");
3755 case ISD::FP_TO_SINT:
3756 Opc = ARMISD::FTOSI;
3758 case ISD::FP_TO_UINT:
3759 Opc = ARMISD::FTOUI;
3762 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3763 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3766 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3767 EVT VT = Op.getValueType();
3770 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3771 if (VT.getVectorElementType() == MVT::f32)
3773 return DAG.UnrollVectorOp(Op.getNode());
3776 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3777 "Invalid type for custom lowering!");
3778 if (VT != MVT::v4f32)
3779 return DAG.UnrollVectorOp(Op.getNode());
3783 switch (Op.getOpcode()) {
3784 default: llvm_unreachable("Invalid opcode!");
3785 case ISD::SINT_TO_FP:
3786 CastOpc = ISD::SIGN_EXTEND;
3787 Opc = ISD::SINT_TO_FP;
3789 case ISD::UINT_TO_FP:
3790 CastOpc = ISD::ZERO_EXTEND;
3791 Opc = ISD::UINT_TO_FP;
3795 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3796 return DAG.getNode(Opc, dl, VT, Op);
3799 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3800 EVT VT = Op.getValueType();
3802 return LowerVectorINT_TO_FP(Op, DAG);
3807 switch (Op.getOpcode()) {
3808 default: llvm_unreachable("Invalid opcode!");
3809 case ISD::SINT_TO_FP:
3810 Opc = ARMISD::SITOF;
3812 case ISD::UINT_TO_FP:
3813 Opc = ARMISD::UITOF;
3817 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3818 return DAG.getNode(Opc, dl, VT, Op);
3821 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3822 // Implement fcopysign with a fabs and a conditional fneg.
3823 SDValue Tmp0 = Op.getOperand(0);
3824 SDValue Tmp1 = Op.getOperand(1);
3826 EVT VT = Op.getValueType();
3827 EVT SrcVT = Tmp1.getValueType();
3828 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3829 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3830 bool UseNEON = !InGPR && Subtarget->hasNEON();
3833 // Use VBSL to copy the sign bit.
3834 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3835 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3836 DAG.getTargetConstant(EncodedVal, MVT::i32));
3837 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3839 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3840 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3841 DAG.getConstant(32, MVT::i32));
3842 else /*if (VT == MVT::f32)*/
3843 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3844 if (SrcVT == MVT::f32) {
3845 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3847 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3848 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3849 DAG.getConstant(32, MVT::i32));
3850 } else if (VT == MVT::f32)
3851 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3852 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3853 DAG.getConstant(32, MVT::i32));
3854 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3855 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3857 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3859 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3860 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3861 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3863 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3864 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3865 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3866 if (VT == MVT::f32) {
3867 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3868 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3869 DAG.getConstant(0, MVT::i32));
3871 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3877 // Bitcast operand 1 to i32.
3878 if (SrcVT == MVT::f64)
3879 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3881 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3883 // Or in the signbit with integer operations.
3884 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3885 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3886 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3887 if (VT == MVT::f32) {
3888 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3889 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3890 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3891 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3894 // f64: Or the high part with signbit and then combine two parts.
3895 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3897 SDValue Lo = Tmp0.getValue(0);
3898 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3899 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3900 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3903 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3904 MachineFunction &MF = DAG.getMachineFunction();
3905 MachineFrameInfo *MFI = MF.getFrameInfo();
3906 MFI->setReturnAddressIsTaken(true);
3908 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3911 EVT VT = Op.getValueType();
3913 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3915 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3916 SDValue Offset = DAG.getConstant(4, MVT::i32);
3917 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3918 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3919 MachinePointerInfo(), false, false, false, 0);
3922 // Return LR, which contains the return address. Mark it an implicit live-in.
3923 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3924 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3927 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3928 const ARMBaseRegisterInfo &ARI =
3929 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3930 MachineFunction &MF = DAG.getMachineFunction();
3931 MachineFrameInfo *MFI = MF.getFrameInfo();
3932 MFI->setFrameAddressIsTaken(true);
3934 EVT VT = Op.getValueType();
3935 SDLoc dl(Op); // FIXME probably not meaningful
3936 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3937 unsigned FrameReg = ARI.getFrameRegister(MF);
3938 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3940 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3941 MachinePointerInfo(),
3942 false, false, false, 0);
3946 // FIXME? Maybe this could be a TableGen attribute on some registers and
3947 // this table could be generated automatically from RegInfo.
3948 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3950 unsigned Reg = StringSwitch<unsigned>(RegName)
3951 .Case("sp", ARM::SP)
3955 report_fatal_error("Invalid register name global variable");
3958 /// ExpandBITCAST - If the target supports VFP, this function is called to
3959 /// expand a bit convert where either the source or destination type is i64 to
3960 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3961 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3962 /// vectors), since the legalizer won't know what to do with that.
3963 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3964 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3966 SDValue Op = N->getOperand(0);
3968 // This function is only supposed to be called for i64 types, either as the
3969 // source or destination of the bit convert.
3970 EVT SrcVT = Op.getValueType();
3971 EVT DstVT = N->getValueType(0);
3972 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3973 "ExpandBITCAST called for non-i64 type");
3975 // Turn i64->f64 into VMOVDRR.
3976 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3977 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3978 DAG.getConstant(0, MVT::i32));
3979 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3980 DAG.getConstant(1, MVT::i32));
3981 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3982 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3985 // Turn f64->i64 into VMOVRRD.
3986 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3988 if (TLI.isBigEndian() && SrcVT.isVector() &&
3989 SrcVT.getVectorNumElements() > 1)
3990 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3991 DAG.getVTList(MVT::i32, MVT::i32),
3992 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3994 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3995 DAG.getVTList(MVT::i32, MVT::i32), Op);
3996 // Merge the pieces into a single i64 value.
3997 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4003 /// getZeroVector - Returns a vector of specified type with all zero elements.
4004 /// Zero vectors are used to represent vector negation and in those cases
4005 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4006 /// not support i64 elements, so sometimes the zero vectors will need to be
4007 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4009 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4010 assert(VT.isVector() && "Expected a vector type");
4011 // The canonical modified immediate encoding of a zero vector is....0!
4012 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4013 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4014 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4015 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4018 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4019 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4020 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4021 SelectionDAG &DAG) const {
4022 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4023 EVT VT = Op.getValueType();
4024 unsigned VTBits = VT.getSizeInBits();
4026 SDValue ShOpLo = Op.getOperand(0);
4027 SDValue ShOpHi = Op.getOperand(1);
4028 SDValue ShAmt = Op.getOperand(2);
4030 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4032 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4034 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4035 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4036 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4037 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4038 DAG.getConstant(VTBits, MVT::i32));
4039 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4040 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4041 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4043 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4044 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4046 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4047 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4050 SDValue Ops[2] = { Lo, Hi };
4051 return DAG.getMergeValues(Ops, dl);
4054 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4055 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4056 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4057 SelectionDAG &DAG) const {
4058 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4059 EVT VT = Op.getValueType();
4060 unsigned VTBits = VT.getSizeInBits();
4062 SDValue ShOpLo = Op.getOperand(0);
4063 SDValue ShOpHi = Op.getOperand(1);
4064 SDValue ShAmt = Op.getOperand(2);
4067 assert(Op.getOpcode() == ISD::SHL_PARTS);
4068 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4069 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4070 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4071 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4072 DAG.getConstant(VTBits, MVT::i32));
4073 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4074 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4076 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4077 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4078 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4080 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4081 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4084 SDValue Ops[2] = { Lo, Hi };
4085 return DAG.getMergeValues(Ops, dl);
4088 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4089 SelectionDAG &DAG) const {
4090 // The rounding mode is in bits 23:22 of the FPSCR.
4091 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4092 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4093 // so that the shift + and get folded into a bitfield extract.
4095 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4096 DAG.getConstant(Intrinsic::arm_get_fpscr,
4098 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4099 DAG.getConstant(1U << 22, MVT::i32));
4100 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4101 DAG.getConstant(22, MVT::i32));
4102 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4103 DAG.getConstant(3, MVT::i32));
4106 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4107 const ARMSubtarget *ST) {
4108 EVT VT = N->getValueType(0);
4111 if (!ST->hasV6T2Ops())
4114 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4115 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4118 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4119 /// for each 16-bit element from operand, repeated. The basic idea is to
4120 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4122 /// Trace for v4i16:
4123 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4124 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4125 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4126 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4127 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4128 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4129 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4130 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4131 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4132 EVT VT = N->getValueType(0);
4135 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4136 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4137 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4138 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4139 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4140 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4143 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4144 /// bit-count for each 16-bit element from the operand. We need slightly
4145 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4146 /// 64/128-bit registers.
4148 /// Trace for v4i16:
4149 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4150 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4151 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4152 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4153 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4154 EVT VT = N->getValueType(0);
4157 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4158 if (VT.is64BitVector()) {
4159 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4160 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4161 DAG.getIntPtrConstant(0));
4163 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4164 BitCounts, DAG.getIntPtrConstant(0));
4165 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4169 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4170 /// bit-count for each 32-bit element from the operand. The idea here is
4171 /// to split the vector into 16-bit elements, leverage the 16-bit count
4172 /// routine, and then combine the results.
4174 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4175 /// input = [v0 v1 ] (vi: 32-bit elements)
4176 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4177 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4178 /// vrev: N0 = [k1 k0 k3 k2 ]
4180 /// N1 =+[k1 k0 k3 k2 ]
4182 /// N2 =+[k1 k3 k0 k2 ]
4184 /// Extended =+[k1 k3 k0 k2 ]
4186 /// Extracted=+[k1 k3 ]
4188 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4189 EVT VT = N->getValueType(0);
4192 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4194 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4195 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4196 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4197 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4198 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4200 if (VT.is64BitVector()) {
4201 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4202 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4203 DAG.getIntPtrConstant(0));
4205 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4206 DAG.getIntPtrConstant(0));
4207 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4211 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4212 const ARMSubtarget *ST) {
4213 EVT VT = N->getValueType(0);
4215 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4216 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4217 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4218 "Unexpected type for custom ctpop lowering");
4220 if (VT.getVectorElementType() == MVT::i32)
4221 return lowerCTPOP32BitElements(N, DAG);
4223 return lowerCTPOP16BitElements(N, DAG);
4226 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4227 const ARMSubtarget *ST) {
4228 EVT VT = N->getValueType(0);
4234 // Lower vector shifts on NEON to use VSHL.
4235 assert(ST->hasNEON() && "unexpected vector shift");
4237 // Left shifts translate directly to the vshiftu intrinsic.
4238 if (N->getOpcode() == ISD::SHL)
4239 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4240 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4241 N->getOperand(0), N->getOperand(1));
4243 assert((N->getOpcode() == ISD::SRA ||
4244 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4246 // NEON uses the same intrinsics for both left and right shifts. For
4247 // right shifts, the shift amounts are negative, so negate the vector of
4249 EVT ShiftVT = N->getOperand(1).getValueType();
4250 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4251 getZeroVector(ShiftVT, DAG, dl),
4253 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4254 Intrinsic::arm_neon_vshifts :
4255 Intrinsic::arm_neon_vshiftu);
4256 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4257 DAG.getConstant(vshiftInt, MVT::i32),
4258 N->getOperand(0), NegatedCount);
4261 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4262 const ARMSubtarget *ST) {
4263 EVT VT = N->getValueType(0);
4266 // We can get here for a node like i32 = ISD::SHL i32, i64
4270 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4271 "Unknown shift to lower!");
4273 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4274 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4275 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4278 // If we are in thumb mode, we don't have RRX.
4279 if (ST->isThumb1Only()) return SDValue();
4281 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4282 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4283 DAG.getConstant(0, MVT::i32));
4284 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4285 DAG.getConstant(1, MVT::i32));
4287 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4288 // captures the result into a carry flag.
4289 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4290 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4292 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4293 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4295 // Merge the pieces into a single i64 value.
4296 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4299 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4300 SDValue TmpOp0, TmpOp1;
4301 bool Invert = false;
4305 SDValue Op0 = Op.getOperand(0);
4306 SDValue Op1 = Op.getOperand(1);
4307 SDValue CC = Op.getOperand(2);
4308 EVT VT = Op.getValueType();
4309 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4312 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4313 switch (SetCCOpcode) {
4314 default: llvm_unreachable("Illegal FP comparison");
4316 case ISD::SETNE: Invert = true; // Fallthrough
4318 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4320 case ISD::SETLT: Swap = true; // Fallthrough
4322 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4324 case ISD::SETLE: Swap = true; // Fallthrough
4326 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4327 case ISD::SETUGE: Swap = true; // Fallthrough
4328 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4329 case ISD::SETUGT: Swap = true; // Fallthrough
4330 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4331 case ISD::SETUEQ: Invert = true; // Fallthrough
4333 // Expand this to (OLT | OGT).
4337 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4338 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4340 case ISD::SETUO: Invert = true; // Fallthrough
4342 // Expand this to (OLT | OGE).
4346 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4347 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4351 // Integer comparisons.
4352 switch (SetCCOpcode) {
4353 default: llvm_unreachable("Illegal integer comparison");
4354 case ISD::SETNE: Invert = true;
4355 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4356 case ISD::SETLT: Swap = true;
4357 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4358 case ISD::SETLE: Swap = true;
4359 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4360 case ISD::SETULT: Swap = true;
4361 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4362 case ISD::SETULE: Swap = true;
4363 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4366 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4367 if (Opc == ARMISD::VCEQ) {
4370 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4372 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4375 // Ignore bitconvert.
4376 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4377 AndOp = AndOp.getOperand(0);
4379 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4381 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4382 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4389 std::swap(Op0, Op1);
4391 // If one of the operands is a constant vector zero, attempt to fold the
4392 // comparison to a specialized compare-against-zero form.
4394 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4396 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4397 if (Opc == ARMISD::VCGE)
4398 Opc = ARMISD::VCLEZ;
4399 else if (Opc == ARMISD::VCGT)
4400 Opc = ARMISD::VCLTZ;
4405 if (SingleOp.getNode()) {
4408 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4410 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4412 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4414 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4416 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4418 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4421 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4425 Result = DAG.getNOT(dl, Result, VT);
4430 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4431 /// valid vector constant for a NEON instruction with a "modified immediate"
4432 /// operand (e.g., VMOV). If so, return the encoded value.
4433 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4434 unsigned SplatBitSize, SelectionDAG &DAG,
4435 EVT &VT, bool is128Bits, NEONModImmType type) {
4436 unsigned OpCmode, Imm;
4438 // SplatBitSize is set to the smallest size that splats the vector, so a
4439 // zero vector will always have SplatBitSize == 8. However, NEON modified
4440 // immediate instructions others than VMOV do not support the 8-bit encoding
4441 // of a zero vector, and the default encoding of zero is supposed to be the
4446 switch (SplatBitSize) {
4448 if (type != VMOVModImm)
4450 // Any 1-byte value is OK. Op=0, Cmode=1110.
4451 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4454 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4458 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4459 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4460 if ((SplatBits & ~0xff) == 0) {
4461 // Value = 0x00nn: Op=x, Cmode=100x.
4466 if ((SplatBits & ~0xff00) == 0) {
4467 // Value = 0xnn00: Op=x, Cmode=101x.
4469 Imm = SplatBits >> 8;
4475 // NEON's 32-bit VMOV supports splat values where:
4476 // * only one byte is nonzero, or
4477 // * the least significant byte is 0xff and the second byte is nonzero, or
4478 // * the least significant 2 bytes are 0xff and the third is nonzero.
4479 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4480 if ((SplatBits & ~0xff) == 0) {
4481 // Value = 0x000000nn: Op=x, Cmode=000x.
4486 if ((SplatBits & ~0xff00) == 0) {
4487 // Value = 0x0000nn00: Op=x, Cmode=001x.
4489 Imm = SplatBits >> 8;
4492 if ((SplatBits & ~0xff0000) == 0) {
4493 // Value = 0x00nn0000: Op=x, Cmode=010x.
4495 Imm = SplatBits >> 16;
4498 if ((SplatBits & ~0xff000000) == 0) {
4499 // Value = 0xnn000000: Op=x, Cmode=011x.
4501 Imm = SplatBits >> 24;
4505 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4506 if (type == OtherModImm) return SDValue();
4508 if ((SplatBits & ~0xffff) == 0 &&
4509 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4510 // Value = 0x0000nnff: Op=x, Cmode=1100.
4512 Imm = SplatBits >> 8;
4516 if ((SplatBits & ~0xffffff) == 0 &&
4517 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4518 // Value = 0x00nnffff: Op=x, Cmode=1101.
4520 Imm = SplatBits >> 16;
4524 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4525 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4526 // VMOV.I32. A (very) minor optimization would be to replicate the value
4527 // and fall through here to test for a valid 64-bit splat. But, then the
4528 // caller would also need to check and handle the change in size.
4532 if (type != VMOVModImm)
4534 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4535 uint64_t BitMask = 0xff;
4537 unsigned ImmMask = 1;
4539 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4540 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4543 } else if ((SplatBits & BitMask) != 0) {
4550 if (DAG.getTargetLoweringInfo().isBigEndian())
4551 // swap higher and lower 32 bit word
4552 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4554 // Op=1, Cmode=1110.
4556 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4561 llvm_unreachable("unexpected size for isNEONModifiedImm");
4564 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4565 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4568 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4569 const ARMSubtarget *ST) const {
4573 bool IsDouble = Op.getValueType() == MVT::f64;
4574 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4576 // Try splatting with a VMOV.f32...
4577 APFloat FPVal = CFP->getValueAPF();
4578 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4581 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4582 // We have code in place to select a valid ConstantFP already, no need to
4587 // It's a float and we are trying to use NEON operations where
4588 // possible. Lower it to a splat followed by an extract.
4590 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4591 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4593 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4594 DAG.getConstant(0, MVT::i32));
4597 // The rest of our options are NEON only, make sure that's allowed before
4599 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4603 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4605 // It wouldn't really be worth bothering for doubles except for one very
4606 // important value, which does happen to match: 0.0. So make sure we don't do
4608 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4611 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4612 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4614 if (NewVal != SDValue()) {
4616 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4619 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4621 // It's a float: cast and extract a vector element.
4622 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4624 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4625 DAG.getConstant(0, MVT::i32));
4628 // Finally, try a VMVN.i32
4629 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4631 if (NewVal != SDValue()) {
4633 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4636 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4638 // It's a float: cast and extract a vector element.
4639 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4641 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4642 DAG.getConstant(0, MVT::i32));
4648 // check if an VEXT instruction can handle the shuffle mask when the
4649 // vector sources of the shuffle are the same.
4650 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4651 unsigned NumElts = VT.getVectorNumElements();
4653 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4659 // If this is a VEXT shuffle, the immediate value is the index of the first
4660 // element. The other shuffle indices must be the successive elements after
4662 unsigned ExpectedElt = Imm;
4663 for (unsigned i = 1; i < NumElts; ++i) {
4664 // Increment the expected index. If it wraps around, just follow it
4665 // back to index zero and keep going.
4667 if (ExpectedElt == NumElts)
4670 if (M[i] < 0) continue; // ignore UNDEF indices
4671 if (ExpectedElt != static_cast<unsigned>(M[i]))
4679 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4680 bool &ReverseVEXT, unsigned &Imm) {
4681 unsigned NumElts = VT.getVectorNumElements();
4682 ReverseVEXT = false;
4684 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4690 // If this is a VEXT shuffle, the immediate value is the index of the first
4691 // element. The other shuffle indices must be the successive elements after
4693 unsigned ExpectedElt = Imm;
4694 for (unsigned i = 1; i < NumElts; ++i) {
4695 // Increment the expected index. If it wraps around, it may still be
4696 // a VEXT but the source vectors must be swapped.
4698 if (ExpectedElt == NumElts * 2) {
4703 if (M[i] < 0) continue; // ignore UNDEF indices
4704 if (ExpectedElt != static_cast<unsigned>(M[i]))
4708 // Adjust the index value if the source operands will be swapped.
4715 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4716 /// instruction with the specified blocksize. (The order of the elements
4717 /// within each block of the vector is reversed.)
4718 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4719 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4720 "Only possible block sizes for VREV are: 16, 32, 64");
4722 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4726 unsigned NumElts = VT.getVectorNumElements();
4727 unsigned BlockElts = M[0] + 1;
4728 // If the first shuffle index is UNDEF, be optimistic.
4730 BlockElts = BlockSize / EltSz;
4732 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4735 for (unsigned i = 0; i < NumElts; ++i) {
4736 if (M[i] < 0) continue; // ignore UNDEF indices
4737 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4744 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4745 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4746 // range, then 0 is placed into the resulting vector. So pretty much any mask
4747 // of 8 elements can work here.
4748 return VT == MVT::v8i8 && M.size() == 8;
4751 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4752 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4756 unsigned NumElts = VT.getVectorNumElements();
4757 WhichResult = (M[0] == 0 ? 0 : 1);
4758 for (unsigned i = 0; i < NumElts; i += 2) {
4759 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4760 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4766 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4767 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4768 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4769 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4770 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4774 unsigned NumElts = VT.getVectorNumElements();
4775 WhichResult = (M[0] == 0 ? 0 : 1);
4776 for (unsigned i = 0; i < NumElts; i += 2) {
4777 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4778 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4784 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4785 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4789 unsigned NumElts = VT.getVectorNumElements();
4790 WhichResult = (M[0] == 0 ? 0 : 1);
4791 for (unsigned i = 0; i != NumElts; ++i) {
4792 if (M[i] < 0) continue; // ignore UNDEF indices
4793 if ((unsigned) M[i] != 2 * i + WhichResult)
4797 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4798 if (VT.is64BitVector() && EltSz == 32)
4804 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4805 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4806 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4807 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4808 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4812 unsigned Half = VT.getVectorNumElements() / 2;
4813 WhichResult = (M[0] == 0 ? 0 : 1);
4814 for (unsigned j = 0; j != 2; ++j) {
4815 unsigned Idx = WhichResult;
4816 for (unsigned i = 0; i != Half; ++i) {
4817 int MIdx = M[i + j * Half];
4818 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4824 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4825 if (VT.is64BitVector() && EltSz == 32)
4831 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4832 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4836 unsigned NumElts = VT.getVectorNumElements();
4837 WhichResult = (M[0] == 0 ? 0 : 1);
4838 unsigned Idx = WhichResult * NumElts / 2;
4839 for (unsigned i = 0; i != NumElts; i += 2) {
4840 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4841 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4846 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4847 if (VT.is64BitVector() && EltSz == 32)
4853 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4854 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4855 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4856 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4857 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4861 unsigned NumElts = VT.getVectorNumElements();
4862 WhichResult = (M[0] == 0 ? 0 : 1);
4863 unsigned Idx = WhichResult * NumElts / 2;
4864 for (unsigned i = 0; i != NumElts; i += 2) {
4865 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4866 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4871 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4872 if (VT.is64BitVector() && EltSz == 32)
4878 /// \return true if this is a reverse operation on an vector.
4879 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4880 unsigned NumElts = VT.getVectorNumElements();
4881 // Make sure the mask has the right size.
4882 if (NumElts != M.size())
4885 // Look for <15, ..., 3, -1, 1, 0>.
4886 for (unsigned i = 0; i != NumElts; ++i)
4887 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4893 // If N is an integer constant that can be moved into a register in one
4894 // instruction, return an SDValue of such a constant (will become a MOV
4895 // instruction). Otherwise return null.
4896 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4897 const ARMSubtarget *ST, SDLoc dl) {
4899 if (!isa<ConstantSDNode>(N))
4901 Val = cast<ConstantSDNode>(N)->getZExtValue();
4903 if (ST->isThumb1Only()) {
4904 if (Val <= 255 || ~Val <= 255)
4905 return DAG.getConstant(Val, MVT::i32);
4907 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4908 return DAG.getConstant(Val, MVT::i32);
4913 // If this is a case we can't handle, return null and let the default
4914 // expansion code take care of it.
4915 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4916 const ARMSubtarget *ST) const {
4917 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4919 EVT VT = Op.getValueType();
4921 APInt SplatBits, SplatUndef;
4922 unsigned SplatBitSize;
4924 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4925 if (SplatBitSize <= 64) {
4926 // Check if an immediate VMOV works.
4928 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4929 SplatUndef.getZExtValue(), SplatBitSize,
4930 DAG, VmovVT, VT.is128BitVector(),
4932 if (Val.getNode()) {
4933 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4934 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4937 // Try an immediate VMVN.
4938 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4939 Val = isNEONModifiedImm(NegatedImm,
4940 SplatUndef.getZExtValue(), SplatBitSize,
4941 DAG, VmovVT, VT.is128BitVector(),
4943 if (Val.getNode()) {
4944 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4945 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4948 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4949 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4950 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4952 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4953 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4959 // Scan through the operands to see if only one value is used.
4961 // As an optimisation, even if more than one value is used it may be more
4962 // profitable to splat with one value then change some lanes.
4964 // Heuristically we decide to do this if the vector has a "dominant" value,
4965 // defined as splatted to more than half of the lanes.
4966 unsigned NumElts = VT.getVectorNumElements();
4967 bool isOnlyLowElement = true;
4968 bool usesOnlyOneValue = true;
4969 bool hasDominantValue = false;
4970 bool isConstant = true;
4972 // Map of the number of times a particular SDValue appears in the
4974 DenseMap<SDValue, unsigned> ValueCounts;
4976 for (unsigned i = 0; i < NumElts; ++i) {
4977 SDValue V = Op.getOperand(i);
4978 if (V.getOpcode() == ISD::UNDEF)
4981 isOnlyLowElement = false;
4982 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4985 ValueCounts.insert(std::make_pair(V, 0));
4986 unsigned &Count = ValueCounts[V];
4988 // Is this value dominant? (takes up more than half of the lanes)
4989 if (++Count > (NumElts / 2)) {
4990 hasDominantValue = true;
4994 if (ValueCounts.size() != 1)
4995 usesOnlyOneValue = false;
4996 if (!Value.getNode() && ValueCounts.size() > 0)
4997 Value = ValueCounts.begin()->first;
4999 if (ValueCounts.size() == 0)
5000 return DAG.getUNDEF(VT);
5002 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5003 // Keep going if we are hitting this case.
5004 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5005 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5007 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5009 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5010 // i32 and try again.
5011 if (hasDominantValue && EltSize <= 32) {
5015 // If we are VDUPing a value that comes directly from a vector, that will
5016 // cause an unnecessary move to and from a GPR, where instead we could
5017 // just use VDUPLANE. We can only do this if the lane being extracted
5018 // is at a constant index, as the VDUP from lane instructions only have
5019 // constant-index forms.
5020 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5021 isa<ConstantSDNode>(Value->getOperand(1))) {
5022 // We need to create a new undef vector to use for the VDUPLANE if the
5023 // size of the vector from which we get the value is different than the
5024 // size of the vector that we need to create. We will insert the element
5025 // such that the register coalescer will remove unnecessary copies.
5026 if (VT != Value->getOperand(0).getValueType()) {
5027 ConstantSDNode *constIndex;
5028 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5029 assert(constIndex && "The index is not a constant!");
5030 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5031 VT.getVectorNumElements();
5032 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5033 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5034 Value, DAG.getConstant(index, MVT::i32)),
5035 DAG.getConstant(index, MVT::i32));
5037 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5038 Value->getOperand(0), Value->getOperand(1));
5040 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5042 if (!usesOnlyOneValue) {
5043 // The dominant value was splatted as 'N', but we now have to insert
5044 // all differing elements.
5045 for (unsigned I = 0; I < NumElts; ++I) {
5046 if (Op.getOperand(I) == Value)
5048 SmallVector<SDValue, 3> Ops;
5050 Ops.push_back(Op.getOperand(I));
5051 Ops.push_back(DAG.getConstant(I, MVT::i32));
5052 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5057 if (VT.getVectorElementType().isFloatingPoint()) {
5058 SmallVector<SDValue, 8> Ops;
5059 for (unsigned i = 0; i < NumElts; ++i)
5060 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5062 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5063 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5064 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5066 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5068 if (usesOnlyOneValue) {
5069 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5070 if (isConstant && Val.getNode())
5071 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5075 // If all elements are constants and the case above didn't get hit, fall back
5076 // to the default expansion, which will generate a load from the constant
5081 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5083 SDValue shuffle = ReconstructShuffle(Op, DAG);
5084 if (shuffle != SDValue())
5088 // Vectors with 32- or 64-bit elements can be built by directly assigning
5089 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5090 // will be legalized.
5091 if (EltSize >= 32) {
5092 // Do the expansion with floating-point types, since that is what the VFP
5093 // registers are defined to use, and since i64 is not legal.
5094 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5095 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5096 SmallVector<SDValue, 8> Ops;
5097 for (unsigned i = 0; i < NumElts; ++i)
5098 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5099 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5100 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5103 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5104 // know the default expansion would otherwise fall back on something even
5105 // worse. For a vector with one or two non-undef values, that's
5106 // scalar_to_vector for the elements followed by a shuffle (provided the
5107 // shuffle is valid for the target) and materialization element by element
5108 // on the stack followed by a load for everything else.
5109 if (!isConstant && !usesOnlyOneValue) {
5110 SDValue Vec = DAG.getUNDEF(VT);
5111 for (unsigned i = 0 ; i < NumElts; ++i) {
5112 SDValue V = Op.getOperand(i);
5113 if (V.getOpcode() == ISD::UNDEF)
5115 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5116 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5124 // Gather data to see if the operation can be modelled as a
5125 // shuffle in combination with VEXTs.
5126 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5127 SelectionDAG &DAG) const {
5129 EVT VT = Op.getValueType();
5130 unsigned NumElts = VT.getVectorNumElements();
5132 SmallVector<SDValue, 2> SourceVecs;
5133 SmallVector<unsigned, 2> MinElts;
5134 SmallVector<unsigned, 2> MaxElts;
5136 for (unsigned i = 0; i < NumElts; ++i) {
5137 SDValue V = Op.getOperand(i);
5138 if (V.getOpcode() == ISD::UNDEF)
5140 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5141 // A shuffle can only come from building a vector from various
5142 // elements of other vectors.
5144 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5145 VT.getVectorElementType()) {
5146 // This code doesn't know how to handle shuffles where the vector
5147 // element types do not match (this happens because type legalization
5148 // promotes the return type of EXTRACT_VECTOR_ELT).
5149 // FIXME: It might be appropriate to extend this code to handle
5150 // mismatched types.
5154 // Record this extraction against the appropriate vector if possible...
5155 SDValue SourceVec = V.getOperand(0);
5156 // If the element number isn't a constant, we can't effectively
5157 // analyze what's going on.
5158 if (!isa<ConstantSDNode>(V.getOperand(1)))
5160 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5161 bool FoundSource = false;
5162 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5163 if (SourceVecs[j] == SourceVec) {
5164 if (MinElts[j] > EltNo)
5166 if (MaxElts[j] < EltNo)
5173 // Or record a new source if not...
5175 SourceVecs.push_back(SourceVec);
5176 MinElts.push_back(EltNo);
5177 MaxElts.push_back(EltNo);
5181 // Currently only do something sane when at most two source vectors
5183 if (SourceVecs.size() > 2)
5186 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5187 int VEXTOffsets[2] = {0, 0};
5189 // This loop extracts the usage patterns of the source vectors
5190 // and prepares appropriate SDValues for a shuffle if possible.
5191 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5192 if (SourceVecs[i].getValueType() == VT) {
5193 // No VEXT necessary
5194 ShuffleSrcs[i] = SourceVecs[i];
5197 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5198 // It probably isn't worth padding out a smaller vector just to
5199 // break it down again in a shuffle.
5203 // Since only 64-bit and 128-bit vectors are legal on ARM and
5204 // we've eliminated the other cases...
5205 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5206 "unexpected vector sizes in ReconstructShuffle");
5208 if (MaxElts[i] - MinElts[i] >= NumElts) {
5209 // Span too large for a VEXT to cope
5213 if (MinElts[i] >= NumElts) {
5214 // The extraction can just take the second half
5215 VEXTOffsets[i] = NumElts;
5216 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5218 DAG.getIntPtrConstant(NumElts));
5219 } else if (MaxElts[i] < NumElts) {
5220 // The extraction can just take the first half
5222 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5224 DAG.getIntPtrConstant(0));
5226 // An actual VEXT is needed
5227 VEXTOffsets[i] = MinElts[i];
5228 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5230 DAG.getIntPtrConstant(0));
5231 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5233 DAG.getIntPtrConstant(NumElts));
5234 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5235 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5239 SmallVector<int, 8> Mask;
5241 for (unsigned i = 0; i < NumElts; ++i) {
5242 SDValue Entry = Op.getOperand(i);
5243 if (Entry.getOpcode() == ISD::UNDEF) {
5248 SDValue ExtractVec = Entry.getOperand(0);
5249 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5250 .getOperand(1))->getSExtValue();
5251 if (ExtractVec == SourceVecs[0]) {
5252 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5254 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5258 // Final check before we try to produce nonsense...
5259 if (isShuffleMaskLegal(Mask, VT))
5260 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5266 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5267 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5268 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5269 /// are assumed to be legal.
5271 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5273 if (VT.getVectorNumElements() == 4 &&
5274 (VT.is128BitVector() || VT.is64BitVector())) {
5275 unsigned PFIndexes[4];
5276 for (unsigned i = 0; i != 4; ++i) {
5280 PFIndexes[i] = M[i];
5283 // Compute the index in the perfect shuffle table.
5284 unsigned PFTableIndex =
5285 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5286 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5287 unsigned Cost = (PFEntry >> 30);
5294 unsigned Imm, WhichResult;
5296 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5297 return (EltSize >= 32 ||
5298 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5299 isVREVMask(M, VT, 64) ||
5300 isVREVMask(M, VT, 32) ||
5301 isVREVMask(M, VT, 16) ||
5302 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5303 isVTBLMask(M, VT) ||
5304 isVTRNMask(M, VT, WhichResult) ||
5305 isVUZPMask(M, VT, WhichResult) ||
5306 isVZIPMask(M, VT, WhichResult) ||
5307 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5308 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5309 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5310 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5313 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5314 /// the specified operations to build the shuffle.
5315 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5316 SDValue RHS, SelectionDAG &DAG,
5318 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5319 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5320 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5323 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5332 OP_VUZPL, // VUZP, left result
5333 OP_VUZPR, // VUZP, right result
5334 OP_VZIPL, // VZIP, left result
5335 OP_VZIPR, // VZIP, right result
5336 OP_VTRNL, // VTRN, left result
5337 OP_VTRNR // VTRN, right result
5340 if (OpNum == OP_COPY) {
5341 if (LHSID == (1*9+2)*9+3) return LHS;
5342 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5346 SDValue OpLHS, OpRHS;
5347 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5348 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5349 EVT VT = OpLHS.getValueType();
5352 default: llvm_unreachable("Unknown shuffle opcode!");
5354 // VREV divides the vector in half and swaps within the half.
5355 if (VT.getVectorElementType() == MVT::i32 ||
5356 VT.getVectorElementType() == MVT::f32)
5357 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5358 // vrev <4 x i16> -> VREV32
5359 if (VT.getVectorElementType() == MVT::i16)
5360 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5361 // vrev <4 x i8> -> VREV16
5362 assert(VT.getVectorElementType() == MVT::i8);
5363 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5368 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5369 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5373 return DAG.getNode(ARMISD::VEXT, dl, VT,
5375 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5378 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5379 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5382 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5383 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5386 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5387 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5391 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5392 ArrayRef<int> ShuffleMask,
5393 SelectionDAG &DAG) {
5394 // Check to see if we can use the VTBL instruction.
5395 SDValue V1 = Op.getOperand(0);
5396 SDValue V2 = Op.getOperand(1);
5399 SmallVector<SDValue, 8> VTBLMask;
5400 for (ArrayRef<int>::iterator
5401 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5402 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5404 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5405 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5406 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5408 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5409 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5412 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5413 SelectionDAG &DAG) {
5415 SDValue OpLHS = Op.getOperand(0);
5416 EVT VT = OpLHS.getValueType();
5418 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5419 "Expect an v8i16/v16i8 type");
5420 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5421 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5422 // extract the first 8 bytes into the top double word and the last 8 bytes
5423 // into the bottom double word. The v8i16 case is similar.
5424 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5425 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5426 DAG.getConstant(ExtractNum, MVT::i32));
5429 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5430 SDValue V1 = Op.getOperand(0);
5431 SDValue V2 = Op.getOperand(1);
5433 EVT VT = Op.getValueType();
5434 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5436 // Convert shuffles that are directly supported on NEON to target-specific
5437 // DAG nodes, instead of keeping them as shuffles and matching them again
5438 // during code selection. This is more efficient and avoids the possibility
5439 // of inconsistencies between legalization and selection.
5440 // FIXME: floating-point vectors should be canonicalized to integer vectors
5441 // of the same time so that they get CSEd properly.
5442 ArrayRef<int> ShuffleMask = SVN->getMask();
5444 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5445 if (EltSize <= 32) {
5446 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5447 int Lane = SVN->getSplatIndex();
5448 // If this is undef splat, generate it via "just" vdup, if possible.
5449 if (Lane == -1) Lane = 0;
5451 // Test if V1 is a SCALAR_TO_VECTOR.
5452 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5453 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5455 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5456 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5458 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5459 !isa<ConstantSDNode>(V1.getOperand(0))) {
5460 bool IsScalarToVector = true;
5461 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5462 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5463 IsScalarToVector = false;
5466 if (IsScalarToVector)
5467 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5469 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5470 DAG.getConstant(Lane, MVT::i32));
5475 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5478 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5479 DAG.getConstant(Imm, MVT::i32));
5482 if (isVREVMask(ShuffleMask, VT, 64))
5483 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5484 if (isVREVMask(ShuffleMask, VT, 32))
5485 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5486 if (isVREVMask(ShuffleMask, VT, 16))
5487 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5489 if (V2->getOpcode() == ISD::UNDEF &&
5490 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5491 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5492 DAG.getConstant(Imm, MVT::i32));
5495 // Check for Neon shuffles that modify both input vectors in place.
5496 // If both results are used, i.e., if there are two shuffles with the same
5497 // source operands and with masks corresponding to both results of one of
5498 // these operations, DAG memoization will ensure that a single node is
5499 // used for both shuffles.
5500 unsigned WhichResult;
5501 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5502 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5503 V1, V2).getValue(WhichResult);
5504 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5505 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5506 V1, V2).getValue(WhichResult);
5507 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5508 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5509 V1, V2).getValue(WhichResult);
5511 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5512 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5513 V1, V1).getValue(WhichResult);
5514 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5515 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5516 V1, V1).getValue(WhichResult);
5517 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5518 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5519 V1, V1).getValue(WhichResult);
5522 // If the shuffle is not directly supported and it has 4 elements, use
5523 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5524 unsigned NumElts = VT.getVectorNumElements();
5526 unsigned PFIndexes[4];
5527 for (unsigned i = 0; i != 4; ++i) {
5528 if (ShuffleMask[i] < 0)
5531 PFIndexes[i] = ShuffleMask[i];
5534 // Compute the index in the perfect shuffle table.
5535 unsigned PFTableIndex =
5536 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5537 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5538 unsigned Cost = (PFEntry >> 30);
5541 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5544 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5545 if (EltSize >= 32) {
5546 // Do the expansion with floating-point types, since that is what the VFP
5547 // registers are defined to use, and since i64 is not legal.
5548 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5549 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5550 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5551 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5552 SmallVector<SDValue, 8> Ops;
5553 for (unsigned i = 0; i < NumElts; ++i) {
5554 if (ShuffleMask[i] < 0)
5555 Ops.push_back(DAG.getUNDEF(EltVT));
5557 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5558 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5559 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5562 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5563 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5566 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5567 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5569 if (VT == MVT::v8i8) {
5570 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5571 if (NewOp.getNode())
5578 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5579 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5580 SDValue Lane = Op.getOperand(2);
5581 if (!isa<ConstantSDNode>(Lane))
5587 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5588 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5589 SDValue Lane = Op.getOperand(1);
5590 if (!isa<ConstantSDNode>(Lane))
5593 SDValue Vec = Op.getOperand(0);
5594 if (Op.getValueType() == MVT::i32 &&
5595 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5597 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5603 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5604 // The only time a CONCAT_VECTORS operation can have legal types is when
5605 // two 64-bit vectors are concatenated to a 128-bit vector.
5606 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5607 "unexpected CONCAT_VECTORS");
5609 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5610 SDValue Op0 = Op.getOperand(0);
5611 SDValue Op1 = Op.getOperand(1);
5612 if (Op0.getOpcode() != ISD::UNDEF)
5613 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5614 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5615 DAG.getIntPtrConstant(0));
5616 if (Op1.getOpcode() != ISD::UNDEF)
5617 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5618 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5619 DAG.getIntPtrConstant(1));
5620 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5623 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5624 /// element has been zero/sign-extended, depending on the isSigned parameter,
5625 /// from an integer type half its size.
5626 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5628 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5629 EVT VT = N->getValueType(0);
5630 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5631 SDNode *BVN = N->getOperand(0).getNode();
5632 if (BVN->getValueType(0) != MVT::v4i32 ||
5633 BVN->getOpcode() != ISD::BUILD_VECTOR)
5635 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5636 unsigned HiElt = 1 - LoElt;
5637 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5638 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5639 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5640 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5641 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5644 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5645 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5648 if (Hi0->isNullValue() && Hi1->isNullValue())
5654 if (N->getOpcode() != ISD::BUILD_VECTOR)
5657 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5658 SDNode *Elt = N->getOperand(i).getNode();
5659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5660 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5661 unsigned HalfSize = EltSize / 2;
5663 if (!isIntN(HalfSize, C->getSExtValue()))
5666 if (!isUIntN(HalfSize, C->getZExtValue()))
5677 /// isSignExtended - Check if a node is a vector value that is sign-extended
5678 /// or a constant BUILD_VECTOR with sign-extended elements.
5679 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5680 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5682 if (isExtendedBUILD_VECTOR(N, DAG, true))
5687 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5688 /// or a constant BUILD_VECTOR with zero-extended elements.
5689 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5690 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5692 if (isExtendedBUILD_VECTOR(N, DAG, false))
5697 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5698 if (OrigVT.getSizeInBits() >= 64)
5701 assert(OrigVT.isSimple() && "Expecting a simple value type");
5703 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5704 switch (OrigSimpleTy) {
5705 default: llvm_unreachable("Unexpected Vector Type");
5714 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5715 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5716 /// We insert the required extension here to get the vector to fill a D register.
5717 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5720 unsigned ExtOpcode) {
5721 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5722 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5723 // 64-bits we need to insert a new extension so that it will be 64-bits.
5724 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5725 if (OrigTy.getSizeInBits() >= 64)
5728 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5729 EVT NewVT = getExtensionTo64Bits(OrigTy);
5731 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5734 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5735 /// does not do any sign/zero extension. If the original vector is less
5736 /// than 64 bits, an appropriate extension will be added after the load to
5737 /// reach a total size of 64 bits. We have to add the extension separately
5738 /// because ARM does not have a sign/zero extending load for vectors.
5739 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5740 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5742 // The load already has the right type.
5743 if (ExtendedTy == LD->getMemoryVT())
5744 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5745 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5746 LD->isNonTemporal(), LD->isInvariant(),
5747 LD->getAlignment());
5749 // We need to create a zextload/sextload. We cannot just create a load
5750 // followed by a zext/zext node because LowerMUL is also run during normal
5751 // operation legalization where we can't create illegal types.
5752 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5753 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5754 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5755 LD->isNonTemporal(), LD->getAlignment());
5758 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5759 /// extending load, or BUILD_VECTOR with extended elements, return the
5760 /// unextended value. The unextended vector should be 64 bits so that it can
5761 /// be used as an operand to a VMULL instruction. If the original vector size
5762 /// before extension is less than 64 bits we add a an extension to resize
5763 /// the vector to 64 bits.
5764 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5765 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5766 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5767 N->getOperand(0)->getValueType(0),
5771 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5772 return SkipLoadExtensionForVMULL(LD, DAG);
5774 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5775 // have been legalized as a BITCAST from v4i32.
5776 if (N->getOpcode() == ISD::BITCAST) {
5777 SDNode *BVN = N->getOperand(0).getNode();
5778 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5779 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5780 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5781 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5782 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5784 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5785 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5786 EVT VT = N->getValueType(0);
5787 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5788 unsigned NumElts = VT.getVectorNumElements();
5789 MVT TruncVT = MVT::getIntegerVT(EltSize);
5790 SmallVector<SDValue, 8> Ops;
5791 for (unsigned i = 0; i != NumElts; ++i) {
5792 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5793 const APInt &CInt = C->getAPIntValue();
5794 // Element types smaller than 32 bits are not legal, so use i32 elements.
5795 // The values are implicitly truncated so sext vs. zext doesn't matter.
5796 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5798 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5799 MVT::getVectorVT(TruncVT, NumElts), Ops);
5802 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5803 unsigned Opcode = N->getOpcode();
5804 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5805 SDNode *N0 = N->getOperand(0).getNode();
5806 SDNode *N1 = N->getOperand(1).getNode();
5807 return N0->hasOneUse() && N1->hasOneUse() &&
5808 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5813 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5814 unsigned Opcode = N->getOpcode();
5815 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5816 SDNode *N0 = N->getOperand(0).getNode();
5817 SDNode *N1 = N->getOperand(1).getNode();
5818 return N0->hasOneUse() && N1->hasOneUse() &&
5819 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5824 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5825 // Multiplications are only custom-lowered for 128-bit vectors so that
5826 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5827 EVT VT = Op.getValueType();
5828 assert(VT.is128BitVector() && VT.isInteger() &&
5829 "unexpected type for custom-lowering ISD::MUL");
5830 SDNode *N0 = Op.getOperand(0).getNode();
5831 SDNode *N1 = Op.getOperand(1).getNode();
5832 unsigned NewOpc = 0;
5834 bool isN0SExt = isSignExtended(N0, DAG);
5835 bool isN1SExt = isSignExtended(N1, DAG);
5836 if (isN0SExt && isN1SExt)
5837 NewOpc = ARMISD::VMULLs;
5839 bool isN0ZExt = isZeroExtended(N0, DAG);
5840 bool isN1ZExt = isZeroExtended(N1, DAG);
5841 if (isN0ZExt && isN1ZExt)
5842 NewOpc = ARMISD::VMULLu;
5843 else if (isN1SExt || isN1ZExt) {
5844 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5845 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5846 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5847 NewOpc = ARMISD::VMULLs;
5849 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5850 NewOpc = ARMISD::VMULLu;
5852 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5854 NewOpc = ARMISD::VMULLu;
5860 if (VT == MVT::v2i64)
5861 // Fall through to expand this. It is not legal.
5864 // Other vector multiplications are legal.
5869 // Legalize to a VMULL instruction.
5872 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5874 Op0 = SkipExtensionForVMULL(N0, DAG);
5875 assert(Op0.getValueType().is64BitVector() &&
5876 Op1.getValueType().is64BitVector() &&
5877 "unexpected types for extended operands to VMULL");
5878 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5881 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5882 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5889 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5890 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5891 EVT Op1VT = Op1.getValueType();
5892 return DAG.getNode(N0->getOpcode(), DL, VT,
5893 DAG.getNode(NewOpc, DL, VT,
5894 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5895 DAG.getNode(NewOpc, DL, VT,
5896 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5900 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5902 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5903 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5904 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5905 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5906 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5907 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5908 // Get reciprocal estimate.
5909 // float4 recip = vrecpeq_f32(yf);
5910 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5911 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5912 // Because char has a smaller range than uchar, we can actually get away
5913 // without any newton steps. This requires that we use a weird bias
5914 // of 0xb000, however (again, this has been exhaustively tested).
5915 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5916 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5917 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5918 Y = DAG.getConstant(0xb000, MVT::i32);
5919 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5920 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5921 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5922 // Convert back to short.
5923 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5924 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5929 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5931 // Convert to float.
5932 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5933 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5934 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5935 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5936 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5937 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5939 // Use reciprocal estimate and one refinement step.
5940 // float4 recip = vrecpeq_f32(yf);
5941 // recip *= vrecpsq_f32(yf, recip);
5942 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5944 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5945 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5947 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5948 // Because short has a smaller range than ushort, we can actually get away
5949 // with only a single newton step. This requires that we use a weird bias
5950 // of 89, however (again, this has been exhaustively tested).
5951 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5952 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5953 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5954 N1 = DAG.getConstant(0x89, MVT::i32);
5955 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5956 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5957 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5958 // Convert back to integer and return.
5959 // return vmovn_s32(vcvt_s32_f32(result));
5960 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5961 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5965 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5966 EVT VT = Op.getValueType();
5967 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5968 "unexpected type for custom-lowering ISD::SDIV");
5971 SDValue N0 = Op.getOperand(0);
5972 SDValue N1 = Op.getOperand(1);
5975 if (VT == MVT::v8i8) {
5976 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5977 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5979 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5980 DAG.getIntPtrConstant(4));
5981 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5982 DAG.getIntPtrConstant(4));
5983 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5984 DAG.getIntPtrConstant(0));
5985 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5986 DAG.getIntPtrConstant(0));
5988 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5989 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5991 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5992 N0 = LowerCONCAT_VECTORS(N0, DAG);
5994 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5997 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6000 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6001 EVT VT = Op.getValueType();
6002 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6003 "unexpected type for custom-lowering ISD::UDIV");
6006 SDValue N0 = Op.getOperand(0);
6007 SDValue N1 = Op.getOperand(1);
6010 if (VT == MVT::v8i8) {
6011 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6012 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6014 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6015 DAG.getIntPtrConstant(4));
6016 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6017 DAG.getIntPtrConstant(4));
6018 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6019 DAG.getIntPtrConstant(0));
6020 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6021 DAG.getIntPtrConstant(0));
6023 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6024 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6026 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6027 N0 = LowerCONCAT_VECTORS(N0, DAG);
6029 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6030 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6035 // v4i16 sdiv ... Convert to float.
6036 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6037 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6038 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6039 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6040 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6041 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6043 // Use reciprocal estimate and two refinement steps.
6044 // float4 recip = vrecpeq_f32(yf);
6045 // recip *= vrecpsq_f32(yf, recip);
6046 // recip *= vrecpsq_f32(yf, recip);
6047 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6048 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6049 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6050 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6052 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6053 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6054 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6056 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6057 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6058 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6059 // and that it will never cause us to return an answer too large).
6060 // float4 result = as_float4(as_int4(xf*recip) + 2);
6061 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6062 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6063 N1 = DAG.getConstant(2, MVT::i32);
6064 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6065 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6066 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6067 // Convert back to integer and return.
6068 // return vmovn_u32(vcvt_s32_f32(result));
6069 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6070 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6074 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6075 EVT VT = Op.getNode()->getValueType(0);
6076 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6079 bool ExtraOp = false;
6080 switch (Op.getOpcode()) {
6081 default: llvm_unreachable("Invalid code");
6082 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6083 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6084 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6085 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6089 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6091 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6092 Op.getOperand(1), Op.getOperand(2));
6095 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6096 assert(Subtarget->isTargetDarwin());
6098 // For iOS, we want to call an alternative entry point: __sincos_stret,
6099 // return values are passed via sret.
6101 SDValue Arg = Op.getOperand(0);
6102 EVT ArgVT = Arg.getValueType();
6103 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6105 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6108 // Pair of floats / doubles used to pass the result.
6109 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6111 // Create stack object for sret.
6112 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6113 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6114 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6115 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6121 Entry.Ty = RetTy->getPointerTo();
6122 Entry.isSExt = false;
6123 Entry.isZExt = false;
6124 Entry.isSRet = true;
6125 Args.push_back(Entry);
6129 Entry.isSExt = false;
6130 Entry.isZExt = false;
6131 Args.push_back(Entry);
6133 const char *LibcallName = (ArgVT == MVT::f64)
6134 ? "__sincos_stret" : "__sincosf_stret";
6135 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6137 TargetLowering::CallLoweringInfo CLI(DAG);
6138 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6139 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6141 .setDiscardResult();
6143 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6145 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6146 MachinePointerInfo(), false, false, false, 0);
6148 // Address of cos field.
6149 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6150 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6151 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6152 MachinePointerInfo(), false, false, false, 0);
6154 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6155 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6156 LoadSin.getValue(0), LoadCos.getValue(0));
6159 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6160 // Monotonic load/store is legal for all targets
6161 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6164 // Acquire/Release load/store is not legal for targets without a
6165 // dmb or equivalent available.
6169 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6170 SmallVectorImpl<SDValue> &Results,
6172 const ARMSubtarget *Subtarget) {
6174 SDValue Cycles32, OutChain;
6176 if (Subtarget->hasPerfMon()) {
6177 // Under Power Management extensions, the cycle-count is:
6178 // mrc p15, #0, <Rt>, c9, c13, #0
6179 SDValue Ops[] = { N->getOperand(0), // Chain
6180 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6181 DAG.getConstant(15, MVT::i32),
6182 DAG.getConstant(0, MVT::i32),
6183 DAG.getConstant(9, MVT::i32),
6184 DAG.getConstant(13, MVT::i32),
6185 DAG.getConstant(0, MVT::i32)
6188 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6189 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6190 OutChain = Cycles32.getValue(1);
6192 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6193 // there are older ARM CPUs that have implementation-specific ways of
6194 // obtaining this information (FIXME!).
6195 Cycles32 = DAG.getConstant(0, MVT::i32);
6196 OutChain = DAG.getEntryNode();
6200 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6201 Cycles32, DAG.getConstant(0, MVT::i32));
6202 Results.push_back(Cycles64);
6203 Results.push_back(OutChain);
6206 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6207 switch (Op.getOpcode()) {
6208 default: llvm_unreachable("Don't know how to custom lower this!");
6209 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6210 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6211 case ISD::GlobalAddress:
6212 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6213 default: llvm_unreachable("unknown object format");
6215 return LowerGlobalAddressWindows(Op, DAG);
6217 return LowerGlobalAddressELF(Op, DAG);
6219 return LowerGlobalAddressDarwin(Op, DAG);
6221 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6222 case ISD::SELECT: return LowerSELECT(Op, DAG);
6223 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6224 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6225 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6226 case ISD::VASTART: return LowerVASTART(Op, DAG);
6227 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6228 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6229 case ISD::SINT_TO_FP:
6230 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6231 case ISD::FP_TO_SINT:
6232 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6233 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6234 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6235 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6236 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6237 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6238 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6239 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6241 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6244 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6245 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6246 case ISD::SRL_PARTS:
6247 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6248 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6249 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6250 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6251 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6252 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6253 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6254 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6255 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6256 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6257 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6258 case ISD::MUL: return LowerMUL(Op, DAG);
6259 case ISD::SDIV: return LowerSDIV(Op, DAG);
6260 case ISD::UDIV: return LowerUDIV(Op, DAG);
6264 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6269 return LowerXALUO(Op, DAG);
6270 case ISD::ATOMIC_LOAD:
6271 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6272 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6274 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6275 case ISD::DYNAMIC_STACKALLOC:
6276 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6277 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6278 llvm_unreachable("Don't know how to custom lower this!");
6282 /// ReplaceNodeResults - Replace the results of node with an illegal result
6283 /// type with new values built out of custom code.
6284 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6285 SmallVectorImpl<SDValue>&Results,
6286 SelectionDAG &DAG) const {
6288 switch (N->getOpcode()) {
6290 llvm_unreachable("Don't know how to custom expand this!");
6292 Res = ExpandBITCAST(N, DAG);
6296 Res = Expand64BitShift(N, DAG, Subtarget);
6298 case ISD::READCYCLECOUNTER:
6299 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6303 Results.push_back(Res);
6306 //===----------------------------------------------------------------------===//
6307 // ARM Scheduler Hooks
6308 //===----------------------------------------------------------------------===//
6310 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6311 /// registers the function context.
6312 void ARMTargetLowering::
6313 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6314 MachineBasicBlock *DispatchBB, int FI) const {
6315 const TargetInstrInfo *TII =
6316 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6317 DebugLoc dl = MI->getDebugLoc();
6318 MachineFunction *MF = MBB->getParent();
6319 MachineRegisterInfo *MRI = &MF->getRegInfo();
6320 MachineConstantPool *MCP = MF->getConstantPool();
6321 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6322 const Function *F = MF->getFunction();
6324 bool isThumb = Subtarget->isThumb();
6325 bool isThumb2 = Subtarget->isThumb2();
6327 unsigned PCLabelId = AFI->createPICLabelUId();
6328 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6329 ARMConstantPoolValue *CPV =
6330 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6331 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6333 const TargetRegisterClass *TRC = isThumb ?
6334 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6335 (const TargetRegisterClass*)&ARM::GPRRegClass;
6337 // Grab constant pool and fixed stack memory operands.
6338 MachineMemOperand *CPMMO =
6339 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6340 MachineMemOperand::MOLoad, 4, 4);
6342 MachineMemOperand *FIMMOSt =
6343 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6344 MachineMemOperand::MOStore, 4, 4);
6346 // Load the address of the dispatch MBB into the jump buffer.
6348 // Incoming value: jbuf
6349 // ldr.n r5, LCPI1_1
6352 // str r5, [$jbuf, #+4] ; &jbuf[1]
6353 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6354 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6355 .addConstantPoolIndex(CPI)
6356 .addMemOperand(CPMMO));
6357 // Set the low bit because of thumb mode.
6358 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6360 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6361 .addReg(NewVReg1, RegState::Kill)
6363 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6364 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6365 .addReg(NewVReg2, RegState::Kill)
6367 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6368 .addReg(NewVReg3, RegState::Kill)
6370 .addImm(36) // &jbuf[1] :: pc
6371 .addMemOperand(FIMMOSt));
6372 } else if (isThumb) {
6373 // Incoming value: jbuf
6374 // ldr.n r1, LCPI1_4
6378 // add r2, $jbuf, #+4 ; &jbuf[1]
6380 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6381 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6382 .addConstantPoolIndex(CPI)
6383 .addMemOperand(CPMMO));
6384 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6385 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6386 .addReg(NewVReg1, RegState::Kill)
6388 // Set the low bit because of thumb mode.
6389 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6390 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6391 .addReg(ARM::CPSR, RegState::Define)
6393 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6394 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6395 .addReg(ARM::CPSR, RegState::Define)
6396 .addReg(NewVReg2, RegState::Kill)
6397 .addReg(NewVReg3, RegState::Kill));
6398 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6399 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6401 .addImm(36)); // &jbuf[1] :: pc
6402 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6403 .addReg(NewVReg4, RegState::Kill)
6404 .addReg(NewVReg5, RegState::Kill)
6406 .addMemOperand(FIMMOSt));
6408 // Incoming value: jbuf
6411 // str r1, [$jbuf, #+4] ; &jbuf[1]
6412 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6413 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6414 .addConstantPoolIndex(CPI)
6416 .addMemOperand(CPMMO));
6417 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6418 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6419 .addReg(NewVReg1, RegState::Kill)
6420 .addImm(PCLabelId));
6421 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6422 .addReg(NewVReg2, RegState::Kill)
6424 .addImm(36) // &jbuf[1] :: pc
6425 .addMemOperand(FIMMOSt));
6429 MachineBasicBlock *ARMTargetLowering::
6430 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6431 const TargetInstrInfo *TII =
6432 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6433 DebugLoc dl = MI->getDebugLoc();
6434 MachineFunction *MF = MBB->getParent();
6435 MachineRegisterInfo *MRI = &MF->getRegInfo();
6436 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6437 MachineFrameInfo *MFI = MF->getFrameInfo();
6438 int FI = MFI->getFunctionContextIndex();
6440 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6441 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6442 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6444 // Get a mapping of the call site numbers to all of the landing pads they're
6446 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6447 unsigned MaxCSNum = 0;
6448 MachineModuleInfo &MMI = MF->getMMI();
6449 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6451 if (!BB->isLandingPad()) continue;
6453 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6455 for (MachineBasicBlock::iterator
6456 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6457 if (!II->isEHLabel()) continue;
6459 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6460 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6462 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6463 for (SmallVectorImpl<unsigned>::iterator
6464 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6465 CSI != CSE; ++CSI) {
6466 CallSiteNumToLPad[*CSI].push_back(BB);
6467 MaxCSNum = std::max(MaxCSNum, *CSI);
6473 // Get an ordered list of the machine basic blocks for the jump table.
6474 std::vector<MachineBasicBlock*> LPadList;
6475 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6476 LPadList.reserve(CallSiteNumToLPad.size());
6477 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6478 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6479 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6480 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6481 LPadList.push_back(*II);
6482 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6486 assert(!LPadList.empty() &&
6487 "No landing pad destinations for the dispatch jump table!");
6489 // Create the jump table and associated information.
6490 MachineJumpTableInfo *JTI =
6491 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6492 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6493 unsigned UId = AFI->createJumpTableUId();
6494 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6496 // Create the MBBs for the dispatch code.
6498 // Shove the dispatch's address into the return slot in the function context.
6499 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6500 DispatchBB->setIsLandingPad();
6502 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6503 unsigned trap_opcode;
6504 if (Subtarget->isThumb())
6505 trap_opcode = ARM::tTRAP;
6507 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6509 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6510 DispatchBB->addSuccessor(TrapBB);
6512 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6513 DispatchBB->addSuccessor(DispContBB);
6516 MF->insert(MF->end(), DispatchBB);
6517 MF->insert(MF->end(), DispContBB);
6518 MF->insert(MF->end(), TrapBB);
6520 // Insert code into the entry block that creates and registers the function
6522 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6524 MachineMemOperand *FIMMOLd =
6525 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6526 MachineMemOperand::MOLoad |
6527 MachineMemOperand::MOVolatile, 4, 4);
6529 MachineInstrBuilder MIB;
6530 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6532 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6533 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6535 // Add a register mask with no preserved registers. This results in all
6536 // registers being marked as clobbered.
6537 MIB.addRegMask(RI.getNoPreservedMask());
6539 unsigned NumLPads = LPadList.size();
6540 if (Subtarget->isThumb2()) {
6541 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6542 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6545 .addMemOperand(FIMMOLd));
6547 if (NumLPads < 256) {
6548 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6550 .addImm(LPadList.size()));
6552 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6553 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6554 .addImm(NumLPads & 0xFFFF));
6556 unsigned VReg2 = VReg1;
6557 if ((NumLPads & 0xFFFF0000) != 0) {
6558 VReg2 = MRI->createVirtualRegister(TRC);
6559 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6561 .addImm(NumLPads >> 16));
6564 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6569 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6574 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6575 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6576 .addJumpTableIndex(MJTI)
6579 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6582 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6583 .addReg(NewVReg3, RegState::Kill)
6585 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6587 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6588 .addReg(NewVReg4, RegState::Kill)
6590 .addJumpTableIndex(MJTI)
6592 } else if (Subtarget->isThumb()) {
6593 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6594 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6597 .addMemOperand(FIMMOLd));
6599 if (NumLPads < 256) {
6600 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6604 MachineConstantPool *ConstantPool = MF->getConstantPool();
6605 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6606 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6608 // MachineConstantPool wants an explicit alignment.
6609 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6611 Align = getDataLayout()->getTypeAllocSize(C->getType());
6612 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6614 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6615 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6616 .addReg(VReg1, RegState::Define)
6617 .addConstantPoolIndex(Idx));
6618 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6623 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6628 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6629 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6630 .addReg(ARM::CPSR, RegState::Define)
6634 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6635 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6636 .addJumpTableIndex(MJTI)
6639 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6640 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6641 .addReg(ARM::CPSR, RegState::Define)
6642 .addReg(NewVReg2, RegState::Kill)
6645 MachineMemOperand *JTMMOLd =
6646 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6647 MachineMemOperand::MOLoad, 4, 4);
6649 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6650 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6651 .addReg(NewVReg4, RegState::Kill)
6653 .addMemOperand(JTMMOLd));
6655 unsigned NewVReg6 = NewVReg5;
6656 if (RelocM == Reloc::PIC_) {
6657 NewVReg6 = MRI->createVirtualRegister(TRC);
6658 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6659 .addReg(ARM::CPSR, RegState::Define)
6660 .addReg(NewVReg5, RegState::Kill)
6664 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6665 .addReg(NewVReg6, RegState::Kill)
6666 .addJumpTableIndex(MJTI)
6669 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6670 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6673 .addMemOperand(FIMMOLd));
6675 if (NumLPads < 256) {
6676 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6679 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6680 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6681 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6682 .addImm(NumLPads & 0xFFFF));
6684 unsigned VReg2 = VReg1;
6685 if ((NumLPads & 0xFFFF0000) != 0) {
6686 VReg2 = MRI->createVirtualRegister(TRC);
6687 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6689 .addImm(NumLPads >> 16));
6692 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6696 MachineConstantPool *ConstantPool = MF->getConstantPool();
6697 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6698 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6700 // MachineConstantPool wants an explicit alignment.
6701 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6703 Align = getDataLayout()->getTypeAllocSize(C->getType());
6704 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6706 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6707 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6708 .addReg(VReg1, RegState::Define)
6709 .addConstantPoolIndex(Idx)
6711 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6713 .addReg(VReg1, RegState::Kill));
6716 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6721 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6723 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6725 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6726 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6727 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6728 .addJumpTableIndex(MJTI)
6731 MachineMemOperand *JTMMOLd =
6732 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6733 MachineMemOperand::MOLoad, 4, 4);
6734 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6736 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6737 .addReg(NewVReg3, RegState::Kill)
6740 .addMemOperand(JTMMOLd));
6742 if (RelocM == Reloc::PIC_) {
6743 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6744 .addReg(NewVReg5, RegState::Kill)
6746 .addJumpTableIndex(MJTI)
6749 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6750 .addReg(NewVReg5, RegState::Kill)
6751 .addJumpTableIndex(MJTI)
6756 // Add the jump table entries as successors to the MBB.
6757 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6758 for (std::vector<MachineBasicBlock*>::iterator
6759 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6760 MachineBasicBlock *CurMBB = *I;
6761 if (SeenMBBs.insert(CurMBB))
6762 DispContBB->addSuccessor(CurMBB);
6765 // N.B. the order the invoke BBs are processed in doesn't matter here.
6766 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6767 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6768 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6769 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6770 MachineBasicBlock *BB = *I;
6772 // Remove the landing pad successor from the invoke block and replace it
6773 // with the new dispatch block.
6774 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6776 while (!Successors.empty()) {
6777 MachineBasicBlock *SMBB = Successors.pop_back_val();
6778 if (SMBB->isLandingPad()) {
6779 BB->removeSuccessor(SMBB);
6780 MBBLPads.push_back(SMBB);
6784 BB->addSuccessor(DispatchBB);
6786 // Find the invoke call and mark all of the callee-saved registers as
6787 // 'implicit defined' so that they're spilled. This prevents code from
6788 // moving instructions to before the EH block, where they will never be
6790 for (MachineBasicBlock::reverse_iterator
6791 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6792 if (!II->isCall()) continue;
6794 DenseMap<unsigned, bool> DefRegs;
6795 for (MachineInstr::mop_iterator
6796 OI = II->operands_begin(), OE = II->operands_end();
6798 if (!OI->isReg()) continue;
6799 DefRegs[OI->getReg()] = true;
6802 MachineInstrBuilder MIB(*MF, &*II);
6804 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6805 unsigned Reg = SavedRegs[i];
6806 if (Subtarget->isThumb2() &&
6807 !ARM::tGPRRegClass.contains(Reg) &&
6808 !ARM::hGPRRegClass.contains(Reg))
6810 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6812 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6815 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6822 // Mark all former landing pads as non-landing pads. The dispatch is the only
6824 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6825 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6826 (*I)->setIsLandingPad(false);
6828 // The instruction is gone now.
6829 MI->eraseFromParent();
6835 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6836 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6837 E = MBB->succ_end(); I != E; ++I)
6840 llvm_unreachable("Expecting a BB with two successors!");
6843 /// Return the load opcode for a given load size. If load size >= 8,
6844 /// neon opcode will be returned.
6845 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6847 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6848 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6850 return LdSize == 4 ? ARM::tLDRi
6851 : LdSize == 2 ? ARM::tLDRHi
6852 : LdSize == 1 ? ARM::tLDRBi : 0;
6854 return LdSize == 4 ? ARM::t2LDR_POST
6855 : LdSize == 2 ? ARM::t2LDRH_POST
6856 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6857 return LdSize == 4 ? ARM::LDR_POST_IMM
6858 : LdSize == 2 ? ARM::LDRH_POST
6859 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6862 /// Return the store opcode for a given store size. If store size >= 8,
6863 /// neon opcode will be returned.
6864 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6866 return StSize == 16 ? ARM::VST1q32wb_fixed
6867 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6869 return StSize == 4 ? ARM::tSTRi
6870 : StSize == 2 ? ARM::tSTRHi
6871 : StSize == 1 ? ARM::tSTRBi : 0;
6873 return StSize == 4 ? ARM::t2STR_POST
6874 : StSize == 2 ? ARM::t2STRH_POST
6875 : StSize == 1 ? ARM::t2STRB_POST : 0;
6876 return StSize == 4 ? ARM::STR_POST_IMM
6877 : StSize == 2 ? ARM::STRH_POST
6878 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6881 /// Emit a post-increment load operation with given size. The instructions
6882 /// will be added to BB at Pos.
6883 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6884 const TargetInstrInfo *TII, DebugLoc dl,
6885 unsigned LdSize, unsigned Data, unsigned AddrIn,
6886 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6887 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6888 assert(LdOpc != 0 && "Should have a load opcode");
6890 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6891 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6893 } else if (IsThumb1) {
6894 // load + update AddrIn
6895 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6896 .addReg(AddrIn).addImm(0));
6897 MachineInstrBuilder MIB =
6898 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6899 MIB = AddDefaultT1CC(MIB);
6900 MIB.addReg(AddrIn).addImm(LdSize);
6901 AddDefaultPred(MIB);
6902 } else if (IsThumb2) {
6903 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6904 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6907 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6908 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6909 .addReg(0).addImm(LdSize));
6913 /// Emit a post-increment store operation with given size. The instructions
6914 /// will be added to BB at Pos.
6915 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6916 const TargetInstrInfo *TII, DebugLoc dl,
6917 unsigned StSize, unsigned Data, unsigned AddrIn,
6918 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6919 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6920 assert(StOpc != 0 && "Should have a store opcode");
6922 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6923 .addReg(AddrIn).addImm(0).addReg(Data));
6924 } else if (IsThumb1) {
6925 // store + update AddrIn
6926 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6927 .addReg(AddrIn).addImm(0));
6928 MachineInstrBuilder MIB =
6929 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6930 MIB = AddDefaultT1CC(MIB);
6931 MIB.addReg(AddrIn).addImm(StSize);
6932 AddDefaultPred(MIB);
6933 } else if (IsThumb2) {
6934 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6935 .addReg(Data).addReg(AddrIn).addImm(StSize));
6937 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6938 .addReg(Data).addReg(AddrIn).addReg(0)
6944 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6945 MachineBasicBlock *BB) const {
6946 // This pseudo instruction has 3 operands: dst, src, size
6947 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6948 // Otherwise, we will generate unrolled scalar copies.
6949 const TargetInstrInfo *TII =
6950 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6951 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6952 MachineFunction::iterator It = BB;
6955 unsigned dest = MI->getOperand(0).getReg();
6956 unsigned src = MI->getOperand(1).getReg();
6957 unsigned SizeVal = MI->getOperand(2).getImm();
6958 unsigned Align = MI->getOperand(3).getImm();
6959 DebugLoc dl = MI->getDebugLoc();
6961 MachineFunction *MF = BB->getParent();
6962 MachineRegisterInfo &MRI = MF->getRegInfo();
6963 unsigned UnitSize = 0;
6964 const TargetRegisterClass *TRC = nullptr;
6965 const TargetRegisterClass *VecTRC = nullptr;
6967 bool IsThumb1 = Subtarget->isThumb1Only();
6968 bool IsThumb2 = Subtarget->isThumb2();
6972 } else if (Align & 2) {
6975 // Check whether we can use NEON instructions.
6976 if (!MF->getFunction()->getAttributes().
6977 hasAttribute(AttributeSet::FunctionIndex,
6978 Attribute::NoImplicitFloat) &&
6979 Subtarget->hasNEON()) {
6980 if ((Align % 16 == 0) && SizeVal >= 16)
6982 else if ((Align % 8 == 0) && SizeVal >= 8)
6985 // Can't use NEON instructions.
6990 // Select the correct opcode and register class for unit size load/store
6991 bool IsNeon = UnitSize >= 8;
6992 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6993 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6995 VecTRC = UnitSize == 16
6996 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6998 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7001 unsigned BytesLeft = SizeVal % UnitSize;
7002 unsigned LoopSize = SizeVal - BytesLeft;
7004 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7005 // Use LDR and STR to copy.
7006 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7007 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7008 unsigned srcIn = src;
7009 unsigned destIn = dest;
7010 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7011 unsigned srcOut = MRI.createVirtualRegister(TRC);
7012 unsigned destOut = MRI.createVirtualRegister(TRC);
7013 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7014 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7015 IsThumb1, IsThumb2);
7016 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7017 IsThumb1, IsThumb2);
7022 // Handle the leftover bytes with LDRB and STRB.
7023 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7024 // [destOut] = STRB_POST(scratch, destIn, 1)
7025 for (unsigned i = 0; i < BytesLeft; i++) {
7026 unsigned srcOut = MRI.createVirtualRegister(TRC);
7027 unsigned destOut = MRI.createVirtualRegister(TRC);
7028 unsigned scratch = MRI.createVirtualRegister(TRC);
7029 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7030 IsThumb1, IsThumb2);
7031 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7032 IsThumb1, IsThumb2);
7036 MI->eraseFromParent(); // The instruction is gone now.
7040 // Expand the pseudo op to a loop.
7043 // movw varEnd, # --> with thumb2
7045 // ldrcp varEnd, idx --> without thumb2
7046 // fallthrough --> loopMBB
7048 // PHI varPhi, varEnd, varLoop
7049 // PHI srcPhi, src, srcLoop
7050 // PHI destPhi, dst, destLoop
7051 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7052 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7053 // subs varLoop, varPhi, #UnitSize
7055 // fallthrough --> exitMBB
7057 // epilogue to handle left-over bytes
7058 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7059 // [destOut] = STRB_POST(scratch, destLoop, 1)
7060 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7061 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7062 MF->insert(It, loopMBB);
7063 MF->insert(It, exitMBB);
7065 // Transfer the remainder of BB and its successor edges to exitMBB.
7066 exitMBB->splice(exitMBB->begin(), BB,
7067 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7068 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7070 // Load an immediate to varEnd.
7071 unsigned varEnd = MRI.createVirtualRegister(TRC);
7073 unsigned Vtmp = varEnd;
7074 if ((LoopSize & 0xFFFF0000) != 0)
7075 Vtmp = MRI.createVirtualRegister(TRC);
7076 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7077 .addImm(LoopSize & 0xFFFF));
7079 if ((LoopSize & 0xFFFF0000) != 0)
7080 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7081 .addReg(Vtmp).addImm(LoopSize >> 16));
7083 MachineConstantPool *ConstantPool = MF->getConstantPool();
7084 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7085 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7087 // MachineConstantPool wants an explicit alignment.
7088 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7090 Align = getDataLayout()->getTypeAllocSize(C->getType());
7091 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7094 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7095 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7097 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7098 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7100 BB->addSuccessor(loopMBB);
7102 // Generate the loop body:
7103 // varPhi = PHI(varLoop, varEnd)
7104 // srcPhi = PHI(srcLoop, src)
7105 // destPhi = PHI(destLoop, dst)
7106 MachineBasicBlock *entryBB = BB;
7108 unsigned varLoop = MRI.createVirtualRegister(TRC);
7109 unsigned varPhi = MRI.createVirtualRegister(TRC);
7110 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7111 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7112 unsigned destLoop = MRI.createVirtualRegister(TRC);
7113 unsigned destPhi = MRI.createVirtualRegister(TRC);
7115 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7116 .addReg(varLoop).addMBB(loopMBB)
7117 .addReg(varEnd).addMBB(entryBB);
7118 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7119 .addReg(srcLoop).addMBB(loopMBB)
7120 .addReg(src).addMBB(entryBB);
7121 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7122 .addReg(destLoop).addMBB(loopMBB)
7123 .addReg(dest).addMBB(entryBB);
7125 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7126 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7127 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7128 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7129 IsThumb1, IsThumb2);
7130 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7131 IsThumb1, IsThumb2);
7133 // Decrement loop variable by UnitSize.
7135 MachineInstrBuilder MIB =
7136 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7137 MIB = AddDefaultT1CC(MIB);
7138 MIB.addReg(varPhi).addImm(UnitSize);
7139 AddDefaultPred(MIB);
7141 MachineInstrBuilder MIB =
7142 BuildMI(*BB, BB->end(), dl,
7143 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7144 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7145 MIB->getOperand(5).setReg(ARM::CPSR);
7146 MIB->getOperand(5).setIsDef(true);
7148 BuildMI(*BB, BB->end(), dl,
7149 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7150 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7152 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7153 BB->addSuccessor(loopMBB);
7154 BB->addSuccessor(exitMBB);
7156 // Add epilogue to handle BytesLeft.
7158 MachineInstr *StartOfExit = exitMBB->begin();
7160 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7161 // [destOut] = STRB_POST(scratch, destLoop, 1)
7162 unsigned srcIn = srcLoop;
7163 unsigned destIn = destLoop;
7164 for (unsigned i = 0; i < BytesLeft; i++) {
7165 unsigned srcOut = MRI.createVirtualRegister(TRC);
7166 unsigned destOut = MRI.createVirtualRegister(TRC);
7167 unsigned scratch = MRI.createVirtualRegister(TRC);
7168 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7169 IsThumb1, IsThumb2);
7170 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7171 IsThumb1, IsThumb2);
7176 MI->eraseFromParent(); // The instruction is gone now.
7181 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7182 MachineBasicBlock *MBB) const {
7183 const TargetMachine &TM = getTargetMachine();
7184 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7185 DebugLoc DL = MI->getDebugLoc();
7187 assert(Subtarget->isTargetWindows() &&
7188 "__chkstk is only supported on Windows");
7189 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7191 // __chkstk takes the number of words to allocate on the stack in R4, and
7192 // returns the stack adjustment in number of bytes in R4. This will not
7193 // clober any other registers (other than the obvious lr).
7195 // Although, technically, IP should be considered a register which may be
7196 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7197 // thumb-2 environment, so there is no interworking required. As a result, we
7198 // do not expect a veneer to be emitted by the linker, clobbering IP.
7200 // Each module receives its own copy of __chkstk, so no import thunk is
7201 // required, again, ensuring that IP is not clobbered.
7203 // Finally, although some linkers may theoretically provide a trampoline for
7204 // out of range calls (which is quite common due to a 32M range limitation of
7205 // branches for Thumb), we can generate the long-call version via
7206 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7209 switch (TM.getCodeModel()) {
7210 case CodeModel::Small:
7211 case CodeModel::Medium:
7212 case CodeModel::Default:
7213 case CodeModel::Kernel:
7214 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7215 .addImm((unsigned)ARMCC::AL).addReg(0)
7216 .addExternalSymbol("__chkstk")
7217 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7218 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7219 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7221 case CodeModel::Large:
7222 case CodeModel::JITDefault: {
7223 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7224 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7226 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7227 .addExternalSymbol("__chkstk");
7228 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7229 .addImm((unsigned)ARMCC::AL).addReg(0)
7230 .addReg(Reg, RegState::Kill)
7231 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7232 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7233 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7238 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7240 .addReg(ARM::SP).addReg(ARM::R4)));
7242 MI->eraseFromParent();
7247 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7248 MachineBasicBlock *BB) const {
7249 const TargetInstrInfo *TII =
7250 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7251 DebugLoc dl = MI->getDebugLoc();
7252 bool isThumb2 = Subtarget->isThumb2();
7253 switch (MI->getOpcode()) {
7256 llvm_unreachable("Unexpected instr type to insert");
7258 // The Thumb2 pre-indexed stores have the same MI operands, they just
7259 // define them differently in the .td files from the isel patterns, so
7260 // they need pseudos.
7261 case ARM::t2STR_preidx:
7262 MI->setDesc(TII->get(ARM::t2STR_PRE));
7264 case ARM::t2STRB_preidx:
7265 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7267 case ARM::t2STRH_preidx:
7268 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7271 case ARM::STRi_preidx:
7272 case ARM::STRBi_preidx: {
7273 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7274 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7275 // Decode the offset.
7276 unsigned Offset = MI->getOperand(4).getImm();
7277 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7278 Offset = ARM_AM::getAM2Offset(Offset);
7282 MachineMemOperand *MMO = *MI->memoperands_begin();
7283 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7284 .addOperand(MI->getOperand(0)) // Rn_wb
7285 .addOperand(MI->getOperand(1)) // Rt
7286 .addOperand(MI->getOperand(2)) // Rn
7287 .addImm(Offset) // offset (skip GPR==zero_reg)
7288 .addOperand(MI->getOperand(5)) // pred
7289 .addOperand(MI->getOperand(6))
7290 .addMemOperand(MMO);
7291 MI->eraseFromParent();
7294 case ARM::STRr_preidx:
7295 case ARM::STRBr_preidx:
7296 case ARM::STRH_preidx: {
7298 switch (MI->getOpcode()) {
7299 default: llvm_unreachable("unexpected opcode!");
7300 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7301 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7302 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7304 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7305 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7306 MIB.addOperand(MI->getOperand(i));
7307 MI->eraseFromParent();
7311 case ARM::tMOVCCr_pseudo: {
7312 // To "insert" a SELECT_CC instruction, we actually have to insert the
7313 // diamond control-flow pattern. The incoming instruction knows the
7314 // destination vreg to set, the condition code register to branch on, the
7315 // true/false values to select between, and a branch opcode to use.
7316 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7317 MachineFunction::iterator It = BB;
7323 // cmpTY ccX, r1, r2
7325 // fallthrough --> copy0MBB
7326 MachineBasicBlock *thisMBB = BB;
7327 MachineFunction *F = BB->getParent();
7328 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7329 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7330 F->insert(It, copy0MBB);
7331 F->insert(It, sinkMBB);
7333 // Transfer the remainder of BB and its successor edges to sinkMBB.
7334 sinkMBB->splice(sinkMBB->begin(), BB,
7335 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7336 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7338 BB->addSuccessor(copy0MBB);
7339 BB->addSuccessor(sinkMBB);
7341 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7342 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7345 // %FalseValue = ...
7346 // # fallthrough to sinkMBB
7349 // Update machine-CFG edges
7350 BB->addSuccessor(sinkMBB);
7353 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7356 BuildMI(*BB, BB->begin(), dl,
7357 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7358 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7359 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7361 MI->eraseFromParent(); // The pseudo instruction is gone now.
7366 case ARM::BCCZi64: {
7367 // If there is an unconditional branch to the other successor, remove it.
7368 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7370 // Compare both parts that make up the double comparison separately for
7372 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7374 unsigned LHS1 = MI->getOperand(1).getReg();
7375 unsigned LHS2 = MI->getOperand(2).getReg();
7377 AddDefaultPred(BuildMI(BB, dl,
7378 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7379 .addReg(LHS1).addImm(0));
7380 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7381 .addReg(LHS2).addImm(0)
7382 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7384 unsigned RHS1 = MI->getOperand(3).getReg();
7385 unsigned RHS2 = MI->getOperand(4).getReg();
7386 AddDefaultPred(BuildMI(BB, dl,
7387 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7388 .addReg(LHS1).addReg(RHS1));
7389 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7390 .addReg(LHS2).addReg(RHS2)
7391 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7394 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7395 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7396 if (MI->getOperand(0).getImm() == ARMCC::NE)
7397 std::swap(destMBB, exitMBB);
7399 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7400 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7402 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7404 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7406 MI->eraseFromParent(); // The pseudo instruction is gone now.
7410 case ARM::Int_eh_sjlj_setjmp:
7411 case ARM::Int_eh_sjlj_setjmp_nofp:
7412 case ARM::tInt_eh_sjlj_setjmp:
7413 case ARM::t2Int_eh_sjlj_setjmp:
7414 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7415 EmitSjLjDispatchBlock(MI, BB);
7420 // To insert an ABS instruction, we have to insert the
7421 // diamond control-flow pattern. The incoming instruction knows the
7422 // source vreg to test against 0, the destination vreg to set,
7423 // the condition code register to branch on, the
7424 // true/false values to select between, and a branch opcode to use.
7429 // BCC (branch to SinkBB if V0 >= 0)
7430 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7431 // SinkBB: V1 = PHI(V2, V3)
7432 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7433 MachineFunction::iterator BBI = BB;
7435 MachineFunction *Fn = BB->getParent();
7436 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7437 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7438 Fn->insert(BBI, RSBBB);
7439 Fn->insert(BBI, SinkBB);
7441 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7442 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7443 bool isThumb2 = Subtarget->isThumb2();
7444 MachineRegisterInfo &MRI = Fn->getRegInfo();
7445 // In Thumb mode S must not be specified if source register is the SP or
7446 // PC and if destination register is the SP, so restrict register class
7447 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7448 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7449 (const TargetRegisterClass*)&ARM::GPRRegClass);
7451 // Transfer the remainder of BB and its successor edges to sinkMBB.
7452 SinkBB->splice(SinkBB->begin(), BB,
7453 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7454 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7456 BB->addSuccessor(RSBBB);
7457 BB->addSuccessor(SinkBB);
7459 // fall through to SinkMBB
7460 RSBBB->addSuccessor(SinkBB);
7462 // insert a cmp at the end of BB
7463 AddDefaultPred(BuildMI(BB, dl,
7464 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7465 .addReg(ABSSrcReg).addImm(0));
7467 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7469 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7470 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7472 // insert rsbri in RSBBB
7473 // Note: BCC and rsbri will be converted into predicated rsbmi
7474 // by if-conversion pass
7475 BuildMI(*RSBBB, RSBBB->begin(), dl,
7476 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7477 .addReg(ABSSrcReg, RegState::Kill)
7478 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7480 // insert PHI in SinkBB,
7481 // reuse ABSDstReg to not change uses of ABS instruction
7482 BuildMI(*SinkBB, SinkBB->begin(), dl,
7483 TII->get(ARM::PHI), ABSDstReg)
7484 .addReg(NewRsbDstReg).addMBB(RSBBB)
7485 .addReg(ABSSrcReg).addMBB(BB);
7487 // remove ABS instruction
7488 MI->eraseFromParent();
7490 // return last added BB
7493 case ARM::COPY_STRUCT_BYVAL_I32:
7495 return EmitStructByval(MI, BB);
7496 case ARM::WIN__CHKSTK:
7497 return EmitLowered__chkstk(MI, BB);
7501 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7502 SDNode *Node) const {
7503 if (!MI->hasPostISelHook()) {
7504 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7505 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7509 const MCInstrDesc *MCID = &MI->getDesc();
7510 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7511 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7512 // operand is still set to noreg. If needed, set the optional operand's
7513 // register to CPSR, and remove the redundant implicit def.
7515 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7517 // Rename pseudo opcodes.
7518 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7520 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7521 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7522 MCID = &TII->get(NewOpc);
7524 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7525 "converted opcode should be the same except for cc_out");
7529 // Add the optional cc_out operand
7530 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7532 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7534 // Any ARM instruction that sets the 's' bit should specify an optional
7535 // "cc_out" operand in the last operand position.
7536 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7537 assert(!NewOpc && "Optional cc_out operand required");
7540 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7541 // since we already have an optional CPSR def.
7542 bool definesCPSR = false;
7543 bool deadCPSR = false;
7544 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7546 const MachineOperand &MO = MI->getOperand(i);
7547 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7551 MI->RemoveOperand(i);
7556 assert(!NewOpc && "Optional cc_out operand required");
7559 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7561 assert(!MI->getOperand(ccOutIdx).getReg() &&
7562 "expect uninitialized optional cc_out operand");
7566 // If this instruction was defined with an optional CPSR def and its dag node
7567 // had a live implicit CPSR def, then activate the optional CPSR def.
7568 MachineOperand &MO = MI->getOperand(ccOutIdx);
7569 MO.setReg(ARM::CPSR);
7573 //===----------------------------------------------------------------------===//
7574 // ARM Optimization Hooks
7575 //===----------------------------------------------------------------------===//
7577 // Helper function that checks if N is a null or all ones constant.
7578 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7579 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7582 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7585 // Return true if N is conditionally 0 or all ones.
7586 // Detects these expressions where cc is an i1 value:
7588 // (select cc 0, y) [AllOnes=0]
7589 // (select cc y, 0) [AllOnes=0]
7590 // (zext cc) [AllOnes=0]
7591 // (sext cc) [AllOnes=0/1]
7592 // (select cc -1, y) [AllOnes=1]
7593 // (select cc y, -1) [AllOnes=1]
7595 // Invert is set when N is the null/all ones constant when CC is false.
7596 // OtherOp is set to the alternative value of N.
7597 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7598 SDValue &CC, bool &Invert,
7600 SelectionDAG &DAG) {
7601 switch (N->getOpcode()) {
7602 default: return false;
7604 CC = N->getOperand(0);
7605 SDValue N1 = N->getOperand(1);
7606 SDValue N2 = N->getOperand(2);
7607 if (isZeroOrAllOnes(N1, AllOnes)) {
7612 if (isZeroOrAllOnes(N2, AllOnes)) {
7619 case ISD::ZERO_EXTEND:
7620 // (zext cc) can never be the all ones value.
7624 case ISD::SIGN_EXTEND: {
7625 EVT VT = N->getValueType(0);
7626 CC = N->getOperand(0);
7627 if (CC.getValueType() != MVT::i1)
7631 // When looking for an AllOnes constant, N is an sext, and the 'other'
7633 OtherOp = DAG.getConstant(0, VT);
7634 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7635 // When looking for a 0 constant, N can be zext or sext.
7636 OtherOp = DAG.getConstant(1, VT);
7638 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7644 // Combine a constant select operand into its use:
7646 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7647 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7648 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7649 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7650 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7652 // The transform is rejected if the select doesn't have a constant operand that
7653 // is null, or all ones when AllOnes is set.
7655 // Also recognize sext/zext from i1:
7657 // (add (zext cc), x) -> (select cc (add x, 1), x)
7658 // (add (sext cc), x) -> (select cc (add x, -1), x)
7660 // These transformations eventually create predicated instructions.
7662 // @param N The node to transform.
7663 // @param Slct The N operand that is a select.
7664 // @param OtherOp The other N operand (x above).
7665 // @param DCI Context.
7666 // @param AllOnes Require the select constant to be all ones instead of null.
7667 // @returns The new node, or SDValue() on failure.
7669 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7670 TargetLowering::DAGCombinerInfo &DCI,
7671 bool AllOnes = false) {
7672 SelectionDAG &DAG = DCI.DAG;
7673 EVT VT = N->getValueType(0);
7674 SDValue NonConstantVal;
7677 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7678 NonConstantVal, DAG))
7681 // Slct is now know to be the desired identity constant when CC is true.
7682 SDValue TrueVal = OtherOp;
7683 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7684 OtherOp, NonConstantVal);
7685 // Unless SwapSelectOps says CC should be false.
7687 std::swap(TrueVal, FalseVal);
7689 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7690 CCOp, TrueVal, FalseVal);
7693 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7695 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7696 TargetLowering::DAGCombinerInfo &DCI) {
7697 SDValue N0 = N->getOperand(0);
7698 SDValue N1 = N->getOperand(1);
7699 if (N0.getNode()->hasOneUse()) {
7700 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7701 if (Result.getNode())
7704 if (N1.getNode()->hasOneUse()) {
7705 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7706 if (Result.getNode())
7712 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7713 // (only after legalization).
7714 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7715 TargetLowering::DAGCombinerInfo &DCI,
7716 const ARMSubtarget *Subtarget) {
7718 // Only perform optimization if after legalize, and if NEON is available. We
7719 // also expected both operands to be BUILD_VECTORs.
7720 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7721 || N0.getOpcode() != ISD::BUILD_VECTOR
7722 || N1.getOpcode() != ISD::BUILD_VECTOR)
7725 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7726 EVT VT = N->getValueType(0);
7727 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7730 // Check that the vector operands are of the right form.
7731 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7732 // operands, where N is the size of the formed vector.
7733 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7734 // index such that we have a pair wise add pattern.
7736 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7737 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7739 SDValue Vec = N0->getOperand(0)->getOperand(0);
7740 SDNode *V = Vec.getNode();
7741 unsigned nextIndex = 0;
7743 // For each operands to the ADD which are BUILD_VECTORs,
7744 // check to see if each of their operands are an EXTRACT_VECTOR with
7745 // the same vector and appropriate index.
7746 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7747 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7748 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7750 SDValue ExtVec0 = N0->getOperand(i);
7751 SDValue ExtVec1 = N1->getOperand(i);
7753 // First operand is the vector, verify its the same.
7754 if (V != ExtVec0->getOperand(0).getNode() ||
7755 V != ExtVec1->getOperand(0).getNode())
7758 // Second is the constant, verify its correct.
7759 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7760 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7762 // For the constant, we want to see all the even or all the odd.
7763 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7764 || C1->getZExtValue() != nextIndex+1)
7773 // Create VPADDL node.
7774 SelectionDAG &DAG = DCI.DAG;
7775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7777 // Build operand list.
7778 SmallVector<SDValue, 8> Ops;
7779 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7780 TLI.getPointerTy()));
7782 // Input is the vector.
7785 // Get widened type and narrowed type.
7787 unsigned numElem = VT.getVectorNumElements();
7789 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7790 switch (inputLaneType.getSimpleVT().SimpleTy) {
7791 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7792 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7793 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7795 llvm_unreachable("Invalid vector element type for padd optimization.");
7798 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7799 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7800 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7803 static SDValue findMUL_LOHI(SDValue V) {
7804 if (V->getOpcode() == ISD::UMUL_LOHI ||
7805 V->getOpcode() == ISD::SMUL_LOHI)
7810 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7811 TargetLowering::DAGCombinerInfo &DCI,
7812 const ARMSubtarget *Subtarget) {
7814 if (Subtarget->isThumb1Only()) return SDValue();
7816 // Only perform the checks after legalize when the pattern is available.
7817 if (DCI.isBeforeLegalize()) return SDValue();
7819 // Look for multiply add opportunities.
7820 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7821 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7822 // a glue link from the first add to the second add.
7823 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7824 // a S/UMLAL instruction.
7827 // \ / \ [no multiline comment]
7833 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7834 SDValue AddcOp0 = AddcNode->getOperand(0);
7835 SDValue AddcOp1 = AddcNode->getOperand(1);
7837 // Check if the two operands are from the same mul_lohi node.
7838 if (AddcOp0.getNode() == AddcOp1.getNode())
7841 assert(AddcNode->getNumValues() == 2 &&
7842 AddcNode->getValueType(0) == MVT::i32 &&
7843 "Expect ADDC with two result values. First: i32");
7845 // Check that we have a glued ADDC node.
7846 if (AddcNode->getValueType(1) != MVT::Glue)
7849 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7850 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7851 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7852 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7853 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7856 // Look for the glued ADDE.
7857 SDNode* AddeNode = AddcNode->getGluedUser();
7861 // Make sure it is really an ADDE.
7862 if (AddeNode->getOpcode() != ISD::ADDE)
7865 assert(AddeNode->getNumOperands() == 3 &&
7866 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7867 "ADDE node has the wrong inputs");
7869 // Check for the triangle shape.
7870 SDValue AddeOp0 = AddeNode->getOperand(0);
7871 SDValue AddeOp1 = AddeNode->getOperand(1);
7873 // Make sure that the ADDE operands are not coming from the same node.
7874 if (AddeOp0.getNode() == AddeOp1.getNode())
7877 // Find the MUL_LOHI node walking up ADDE's operands.
7878 bool IsLeftOperandMUL = false;
7879 SDValue MULOp = findMUL_LOHI(AddeOp0);
7880 if (MULOp == SDValue())
7881 MULOp = findMUL_LOHI(AddeOp1);
7883 IsLeftOperandMUL = true;
7884 if (MULOp == SDValue())
7887 // Figure out the right opcode.
7888 unsigned Opc = MULOp->getOpcode();
7889 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7891 // Figure out the high and low input values to the MLAL node.
7892 SDValue* HiMul = &MULOp;
7893 SDValue* HiAdd = nullptr;
7894 SDValue* LoMul = nullptr;
7895 SDValue* LowAdd = nullptr;
7897 if (IsLeftOperandMUL)
7903 if (AddcOp0->getOpcode() == Opc) {
7907 if (AddcOp1->getOpcode() == Opc) {
7915 if (LoMul->getNode() != HiMul->getNode())
7918 // Create the merged node.
7919 SelectionDAG &DAG = DCI.DAG;
7921 // Build operand list.
7922 SmallVector<SDValue, 8> Ops;
7923 Ops.push_back(LoMul->getOperand(0));
7924 Ops.push_back(LoMul->getOperand(1));
7925 Ops.push_back(*LowAdd);
7926 Ops.push_back(*HiAdd);
7928 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7929 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7931 // Replace the ADDs' nodes uses by the MLA node's values.
7932 SDValue HiMLALResult(MLALNode.getNode(), 1);
7933 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7935 SDValue LoMLALResult(MLALNode.getNode(), 0);
7936 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7938 // Return original node to notify the driver to stop replacing.
7939 SDValue resNode(AddcNode, 0);
7943 /// PerformADDCCombine - Target-specific dag combine transform from
7944 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7945 static SDValue PerformADDCCombine(SDNode *N,
7946 TargetLowering::DAGCombinerInfo &DCI,
7947 const ARMSubtarget *Subtarget) {
7949 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7953 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7954 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7955 /// called with the default operands, and if that fails, with commuted
7957 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7958 TargetLowering::DAGCombinerInfo &DCI,
7959 const ARMSubtarget *Subtarget){
7961 // Attempt to create vpaddl for this add.
7962 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7963 if (Result.getNode())
7966 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7967 if (N0.getNode()->hasOneUse()) {
7968 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7969 if (Result.getNode()) return Result;
7974 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7976 static SDValue PerformADDCombine(SDNode *N,
7977 TargetLowering::DAGCombinerInfo &DCI,
7978 const ARMSubtarget *Subtarget) {
7979 SDValue N0 = N->getOperand(0);
7980 SDValue N1 = N->getOperand(1);
7982 // First try with the default operand order.
7983 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7984 if (Result.getNode())
7987 // If that didn't work, try again with the operands commuted.
7988 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7991 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7993 static SDValue PerformSUBCombine(SDNode *N,
7994 TargetLowering::DAGCombinerInfo &DCI) {
7995 SDValue N0 = N->getOperand(0);
7996 SDValue N1 = N->getOperand(1);
7998 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7999 if (N1.getNode()->hasOneUse()) {
8000 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8001 if (Result.getNode()) return Result;
8007 /// PerformVMULCombine
8008 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8009 /// special multiplier accumulator forwarding.
8015 // However, for (A + B) * (A + B),
8022 static SDValue PerformVMULCombine(SDNode *N,
8023 TargetLowering::DAGCombinerInfo &DCI,
8024 const ARMSubtarget *Subtarget) {
8025 if (!Subtarget->hasVMLxForwarding())
8028 SelectionDAG &DAG = DCI.DAG;
8029 SDValue N0 = N->getOperand(0);
8030 SDValue N1 = N->getOperand(1);
8031 unsigned Opcode = N0.getOpcode();
8032 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8033 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8034 Opcode = N1.getOpcode();
8035 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8036 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8044 EVT VT = N->getValueType(0);
8046 SDValue N00 = N0->getOperand(0);
8047 SDValue N01 = N0->getOperand(1);
8048 return DAG.getNode(Opcode, DL, VT,
8049 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8050 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8053 static SDValue PerformMULCombine(SDNode *N,
8054 TargetLowering::DAGCombinerInfo &DCI,
8055 const ARMSubtarget *Subtarget) {
8056 SelectionDAG &DAG = DCI.DAG;
8058 if (Subtarget->isThumb1Only())
8061 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8064 EVT VT = N->getValueType(0);
8065 if (VT.is64BitVector() || VT.is128BitVector())
8066 return PerformVMULCombine(N, DCI, Subtarget);
8070 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8074 int64_t MulAmt = C->getSExtValue();
8075 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8077 ShiftAmt = ShiftAmt & (32 - 1);
8078 SDValue V = N->getOperand(0);
8082 MulAmt >>= ShiftAmt;
8085 if (isPowerOf2_32(MulAmt - 1)) {
8086 // (mul x, 2^N + 1) => (add (shl x, N), x)
8087 Res = DAG.getNode(ISD::ADD, DL, VT,
8089 DAG.getNode(ISD::SHL, DL, VT,
8091 DAG.getConstant(Log2_32(MulAmt - 1),
8093 } else if (isPowerOf2_32(MulAmt + 1)) {
8094 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8095 Res = DAG.getNode(ISD::SUB, DL, VT,
8096 DAG.getNode(ISD::SHL, DL, VT,
8098 DAG.getConstant(Log2_32(MulAmt + 1),
8104 uint64_t MulAmtAbs = -MulAmt;
8105 if (isPowerOf2_32(MulAmtAbs + 1)) {
8106 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8107 Res = DAG.getNode(ISD::SUB, DL, VT,
8109 DAG.getNode(ISD::SHL, DL, VT,
8111 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8113 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8114 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8115 Res = DAG.getNode(ISD::ADD, DL, VT,
8117 DAG.getNode(ISD::SHL, DL, VT,
8119 DAG.getConstant(Log2_32(MulAmtAbs-1),
8121 Res = DAG.getNode(ISD::SUB, DL, VT,
8122 DAG.getConstant(0, MVT::i32),Res);
8129 Res = DAG.getNode(ISD::SHL, DL, VT,
8130 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8132 // Do not add new nodes to DAG combiner worklist.
8133 DCI.CombineTo(N, Res, false);
8137 static SDValue PerformANDCombine(SDNode *N,
8138 TargetLowering::DAGCombinerInfo &DCI,
8139 const ARMSubtarget *Subtarget) {
8141 // Attempt to use immediate-form VBIC
8142 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8144 EVT VT = N->getValueType(0);
8145 SelectionDAG &DAG = DCI.DAG;
8147 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8150 APInt SplatBits, SplatUndef;
8151 unsigned SplatBitSize;
8154 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8155 if (SplatBitSize <= 64) {
8157 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8158 SplatUndef.getZExtValue(), SplatBitSize,
8159 DAG, VbicVT, VT.is128BitVector(),
8161 if (Val.getNode()) {
8163 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8164 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8165 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8170 if (!Subtarget->isThumb1Only()) {
8171 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8172 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8173 if (Result.getNode())
8180 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8181 static SDValue PerformORCombine(SDNode *N,
8182 TargetLowering::DAGCombinerInfo &DCI,
8183 const ARMSubtarget *Subtarget) {
8184 // Attempt to use immediate-form VORR
8185 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8187 EVT VT = N->getValueType(0);
8188 SelectionDAG &DAG = DCI.DAG;
8190 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8193 APInt SplatBits, SplatUndef;
8194 unsigned SplatBitSize;
8196 if (BVN && Subtarget->hasNEON() &&
8197 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8198 if (SplatBitSize <= 64) {
8200 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8201 SplatUndef.getZExtValue(), SplatBitSize,
8202 DAG, VorrVT, VT.is128BitVector(),
8204 if (Val.getNode()) {
8206 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8207 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8208 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8213 if (!Subtarget->isThumb1Only()) {
8214 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8215 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8216 if (Result.getNode())
8220 // The code below optimizes (or (and X, Y), Z).
8221 // The AND operand needs to have a single user to make these optimizations
8223 SDValue N0 = N->getOperand(0);
8224 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8226 SDValue N1 = N->getOperand(1);
8228 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8229 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8230 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8232 unsigned SplatBitSize;
8235 APInt SplatBits0, SplatBits1;
8236 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8237 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8238 // Ensure that the second operand of both ands are constants
8239 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8240 HasAnyUndefs) && !HasAnyUndefs) {
8241 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8242 HasAnyUndefs) && !HasAnyUndefs) {
8243 // Ensure that the bit width of the constants are the same and that
8244 // the splat arguments are logical inverses as per the pattern we
8245 // are trying to simplify.
8246 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8247 SplatBits0 == ~SplatBits1) {
8248 // Canonicalize the vector type to make instruction selection
8250 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8251 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8255 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8261 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8264 // BFI is only available on V6T2+
8265 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8269 // 1) or (and A, mask), val => ARMbfi A, val, mask
8270 // iff (val & mask) == val
8272 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8273 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8274 // && mask == ~mask2
8275 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8276 // && ~mask == mask2
8277 // (i.e., copy a bitfield value into another bitfield of the same width)
8282 SDValue N00 = N0.getOperand(0);
8284 // The value and the mask need to be constants so we can verify this is
8285 // actually a bitfield set. If the mask is 0xffff, we can do better
8286 // via a movt instruction, so don't use BFI in that case.
8287 SDValue MaskOp = N0.getOperand(1);
8288 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8291 unsigned Mask = MaskC->getZExtValue();
8295 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8296 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8298 unsigned Val = N1C->getZExtValue();
8299 if ((Val & ~Mask) != Val)
8302 if (ARM::isBitFieldInvertedMask(Mask)) {
8303 Val >>= countTrailingZeros(~Mask);
8305 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8306 DAG.getConstant(Val, MVT::i32),
8307 DAG.getConstant(Mask, MVT::i32));
8309 // Do not add new nodes to DAG combiner worklist.
8310 DCI.CombineTo(N, Res, false);
8313 } else if (N1.getOpcode() == ISD::AND) {
8314 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8315 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8318 unsigned Mask2 = N11C->getZExtValue();
8320 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8322 if (ARM::isBitFieldInvertedMask(Mask) &&
8324 // The pack halfword instruction works better for masks that fit it,
8325 // so use that when it's available.
8326 if (Subtarget->hasT2ExtractPack() &&
8327 (Mask == 0xffff || Mask == 0xffff0000))
8330 unsigned amt = countTrailingZeros(Mask2);
8331 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8332 DAG.getConstant(amt, MVT::i32));
8333 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8334 DAG.getConstant(Mask, MVT::i32));
8335 // Do not add new nodes to DAG combiner worklist.
8336 DCI.CombineTo(N, Res, false);
8338 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8340 // The pack halfword instruction works better for masks that fit it,
8341 // so use that when it's available.
8342 if (Subtarget->hasT2ExtractPack() &&
8343 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8346 unsigned lsb = countTrailingZeros(Mask);
8347 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8348 DAG.getConstant(lsb, MVT::i32));
8349 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8350 DAG.getConstant(Mask2, MVT::i32));
8351 // Do not add new nodes to DAG combiner worklist.
8352 DCI.CombineTo(N, Res, false);
8357 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8358 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8359 ARM::isBitFieldInvertedMask(~Mask)) {
8360 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8361 // where lsb(mask) == #shamt and masked bits of B are known zero.
8362 SDValue ShAmt = N00.getOperand(1);
8363 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8364 unsigned LSB = countTrailingZeros(Mask);
8368 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8369 DAG.getConstant(~Mask, MVT::i32));
8371 // Do not add new nodes to DAG combiner worklist.
8372 DCI.CombineTo(N, Res, false);
8378 static SDValue PerformXORCombine(SDNode *N,
8379 TargetLowering::DAGCombinerInfo &DCI,
8380 const ARMSubtarget *Subtarget) {
8381 EVT VT = N->getValueType(0);
8382 SelectionDAG &DAG = DCI.DAG;
8384 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8387 if (!Subtarget->isThumb1Only()) {
8388 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8389 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8390 if (Result.getNode())
8397 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8398 /// the bits being cleared by the AND are not demanded by the BFI.
8399 static SDValue PerformBFICombine(SDNode *N,
8400 TargetLowering::DAGCombinerInfo &DCI) {
8401 SDValue N1 = N->getOperand(1);
8402 if (N1.getOpcode() == ISD::AND) {
8403 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8406 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8407 unsigned LSB = countTrailingZeros(~InvMask);
8408 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8409 unsigned Mask = (1 << Width)-1;
8410 unsigned Mask2 = N11C->getZExtValue();
8411 if ((Mask & (~Mask2)) == 0)
8412 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8413 N->getOperand(0), N1.getOperand(0),
8419 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8420 /// ARMISD::VMOVRRD.
8421 static SDValue PerformVMOVRRDCombine(SDNode *N,
8422 TargetLowering::DAGCombinerInfo &DCI) {
8423 // vmovrrd(vmovdrr x, y) -> x,y
8424 SDValue InDouble = N->getOperand(0);
8425 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8426 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8428 // vmovrrd(load f64) -> (load i32), (load i32)
8429 SDNode *InNode = InDouble.getNode();
8430 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8431 InNode->getValueType(0) == MVT::f64 &&
8432 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8433 !cast<LoadSDNode>(InNode)->isVolatile()) {
8434 // TODO: Should this be done for non-FrameIndex operands?
8435 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8437 SelectionDAG &DAG = DCI.DAG;
8439 SDValue BasePtr = LD->getBasePtr();
8440 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8441 LD->getPointerInfo(), LD->isVolatile(),
8442 LD->isNonTemporal(), LD->isInvariant(),
8443 LD->getAlignment());
8445 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8446 DAG.getConstant(4, MVT::i32));
8447 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8448 LD->getPointerInfo(), LD->isVolatile(),
8449 LD->isNonTemporal(), LD->isInvariant(),
8450 std::min(4U, LD->getAlignment() / 2));
8452 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8453 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8454 std::swap (NewLD1, NewLD2);
8455 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8462 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8463 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8464 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8465 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8466 SDValue Op0 = N->getOperand(0);
8467 SDValue Op1 = N->getOperand(1);
8468 if (Op0.getOpcode() == ISD::BITCAST)
8469 Op0 = Op0.getOperand(0);
8470 if (Op1.getOpcode() == ISD::BITCAST)
8471 Op1 = Op1.getOperand(0);
8472 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8473 Op0.getNode() == Op1.getNode() &&
8474 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8475 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8476 N->getValueType(0), Op0.getOperand(0));
8480 /// PerformSTORECombine - Target-specific dag combine xforms for
8482 static SDValue PerformSTORECombine(SDNode *N,
8483 TargetLowering::DAGCombinerInfo &DCI) {
8484 StoreSDNode *St = cast<StoreSDNode>(N);
8485 if (St->isVolatile())
8488 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8489 // pack all of the elements in one place. Next, store to memory in fewer
8491 SDValue StVal = St->getValue();
8492 EVT VT = StVal.getValueType();
8493 if (St->isTruncatingStore() && VT.isVector()) {
8494 SelectionDAG &DAG = DCI.DAG;
8495 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8496 EVT StVT = St->getMemoryVT();
8497 unsigned NumElems = VT.getVectorNumElements();
8498 assert(StVT != VT && "Cannot truncate to the same type");
8499 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8500 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8502 // From, To sizes and ElemCount must be pow of two
8503 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8505 // We are going to use the original vector elt for storing.
8506 // Accumulated smaller vector elements must be a multiple of the store size.
8507 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8509 unsigned SizeRatio = FromEltSz / ToEltSz;
8510 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8512 // Create a type on which we perform the shuffle.
8513 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8514 NumElems*SizeRatio);
8515 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8518 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8519 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8520 for (unsigned i = 0; i < NumElems; ++i)
8521 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8523 // Can't shuffle using an illegal type.
8524 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8526 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8527 DAG.getUNDEF(WideVec.getValueType()),
8529 // At this point all of the data is stored at the bottom of the
8530 // register. We now need to save it to mem.
8532 // Find the largest store unit
8533 MVT StoreType = MVT::i8;
8534 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8535 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8536 MVT Tp = (MVT::SimpleValueType)tp;
8537 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8540 // Didn't find a legal store type.
8541 if (!TLI.isTypeLegal(StoreType))
8544 // Bitcast the original vector into a vector of store-size units
8545 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8546 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8547 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8548 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8549 SmallVector<SDValue, 8> Chains;
8550 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8551 TLI.getPointerTy());
8552 SDValue BasePtr = St->getBasePtr();
8554 // Perform one or more big stores into memory.
8555 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8556 for (unsigned I = 0; I < E; I++) {
8557 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8558 StoreType, ShuffWide,
8559 DAG.getIntPtrConstant(I));
8560 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8561 St->getPointerInfo(), St->isVolatile(),
8562 St->isNonTemporal(), St->getAlignment());
8563 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8565 Chains.push_back(Ch);
8567 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8570 if (!ISD::isNormalStore(St))
8573 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8574 // ARM stores of arguments in the same cache line.
8575 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8576 StVal.getNode()->hasOneUse()) {
8577 SelectionDAG &DAG = DCI.DAG;
8578 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8580 SDValue BasePtr = St->getBasePtr();
8581 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8582 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8583 BasePtr, St->getPointerInfo(), St->isVolatile(),
8584 St->isNonTemporal(), St->getAlignment());
8586 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8587 DAG.getConstant(4, MVT::i32));
8588 return DAG.getStore(NewST1.getValue(0), DL,
8589 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8590 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8591 St->isNonTemporal(),
8592 std::min(4U, St->getAlignment() / 2));
8595 if (StVal.getValueType() != MVT::i64 ||
8596 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8599 // Bitcast an i64 store extracted from a vector to f64.
8600 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8601 SelectionDAG &DAG = DCI.DAG;
8603 SDValue IntVec = StVal.getOperand(0);
8604 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8605 IntVec.getValueType().getVectorNumElements());
8606 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8607 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8608 Vec, StVal.getOperand(1));
8610 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8611 // Make the DAGCombiner fold the bitcasts.
8612 DCI.AddToWorklist(Vec.getNode());
8613 DCI.AddToWorklist(ExtElt.getNode());
8614 DCI.AddToWorklist(V.getNode());
8615 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8616 St->getPointerInfo(), St->isVolatile(),
8617 St->isNonTemporal(), St->getAlignment(),
8621 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8622 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8623 /// i64 vector to have f64 elements, since the value can then be loaded
8624 /// directly into a VFP register.
8625 static bool hasNormalLoadOperand(SDNode *N) {
8626 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8627 for (unsigned i = 0; i < NumElts; ++i) {
8628 SDNode *Elt = N->getOperand(i).getNode();
8629 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8635 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8636 /// ISD::BUILD_VECTOR.
8637 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8638 TargetLowering::DAGCombinerInfo &DCI){
8639 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8640 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8641 // into a pair of GPRs, which is fine when the value is used as a scalar,
8642 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8643 SelectionDAG &DAG = DCI.DAG;
8644 if (N->getNumOperands() == 2) {
8645 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8650 // Load i64 elements as f64 values so that type legalization does not split
8651 // them up into i32 values.
8652 EVT VT = N->getValueType(0);
8653 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8656 SmallVector<SDValue, 8> Ops;
8657 unsigned NumElts = VT.getVectorNumElements();
8658 for (unsigned i = 0; i < NumElts; ++i) {
8659 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8661 // Make the DAGCombiner fold the bitcast.
8662 DCI.AddToWorklist(V.getNode());
8664 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8665 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8666 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8669 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8671 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8672 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8673 // At that time, we may have inserted bitcasts from integer to float.
8674 // If these bitcasts have survived DAGCombine, change the lowering of this
8675 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8676 // force to use floating point types.
8678 // Make sure we can change the type of the vector.
8679 // This is possible iff:
8680 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8681 // 1.1. Vector is used only once.
8682 // 1.2. Use is a bit convert to an integer type.
8683 // 2. The size of its operands are 32-bits (64-bits are not legal).
8684 EVT VT = N->getValueType(0);
8685 EVT EltVT = VT.getVectorElementType();
8687 // Check 1.1. and 2.
8688 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8691 // By construction, the input type must be float.
8692 assert(EltVT == MVT::f32 && "Unexpected type!");
8695 SDNode *Use = *N->use_begin();
8696 if (Use->getOpcode() != ISD::BITCAST ||
8697 Use->getValueType(0).isFloatingPoint())
8700 // Check profitability.
8701 // Model is, if more than half of the relevant operands are bitcast from
8702 // i32, turn the build_vector into a sequence of insert_vector_elt.
8703 // Relevant operands are everything that is not statically
8704 // (i.e., at compile time) bitcasted.
8705 unsigned NumOfBitCastedElts = 0;
8706 unsigned NumElts = VT.getVectorNumElements();
8707 unsigned NumOfRelevantElts = NumElts;
8708 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8709 SDValue Elt = N->getOperand(Idx);
8710 if (Elt->getOpcode() == ISD::BITCAST) {
8711 // Assume only bit cast to i32 will go away.
8712 if (Elt->getOperand(0).getValueType() == MVT::i32)
8713 ++NumOfBitCastedElts;
8714 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8715 // Constants are statically casted, thus do not count them as
8716 // relevant operands.
8717 --NumOfRelevantElts;
8720 // Check if more than half of the elements require a non-free bitcast.
8721 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8724 SelectionDAG &DAG = DCI.DAG;
8725 // Create the new vector type.
8726 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8727 // Check if the type is legal.
8728 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8729 if (!TLI.isTypeLegal(VecVT))
8733 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8734 // => BITCAST INSERT_VECTOR_ELT
8735 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8737 SDValue Vec = DAG.getUNDEF(VecVT);
8739 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8740 SDValue V = N->getOperand(Idx);
8741 if (V.getOpcode() == ISD::UNDEF)
8743 if (V.getOpcode() == ISD::BITCAST &&
8744 V->getOperand(0).getValueType() == MVT::i32)
8745 // Fold obvious case.
8746 V = V.getOperand(0);
8748 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8749 // Make the DAGCombiner fold the bitcasts.
8750 DCI.AddToWorklist(V.getNode());
8752 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8753 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8755 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8756 // Make the DAGCombiner fold the bitcasts.
8757 DCI.AddToWorklist(Vec.getNode());
8761 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8762 /// ISD::INSERT_VECTOR_ELT.
8763 static SDValue PerformInsertEltCombine(SDNode *N,
8764 TargetLowering::DAGCombinerInfo &DCI) {
8765 // Bitcast an i64 load inserted into a vector to f64.
8766 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8767 EVT VT = N->getValueType(0);
8768 SDNode *Elt = N->getOperand(1).getNode();
8769 if (VT.getVectorElementType() != MVT::i64 ||
8770 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8773 SelectionDAG &DAG = DCI.DAG;
8775 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8776 VT.getVectorNumElements());
8777 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8778 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8779 // Make the DAGCombiner fold the bitcasts.
8780 DCI.AddToWorklist(Vec.getNode());
8781 DCI.AddToWorklist(V.getNode());
8782 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8783 Vec, V, N->getOperand(2));
8784 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8787 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8788 /// ISD::VECTOR_SHUFFLE.
8789 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8790 // The LLVM shufflevector instruction does not require the shuffle mask
8791 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8792 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8793 // operands do not match the mask length, they are extended by concatenating
8794 // them with undef vectors. That is probably the right thing for other
8795 // targets, but for NEON it is better to concatenate two double-register
8796 // size vector operands into a single quad-register size vector. Do that
8797 // transformation here:
8798 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8799 // shuffle(concat(v1, v2), undef)
8800 SDValue Op0 = N->getOperand(0);
8801 SDValue Op1 = N->getOperand(1);
8802 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8803 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8804 Op0.getNumOperands() != 2 ||
8805 Op1.getNumOperands() != 2)
8807 SDValue Concat0Op1 = Op0.getOperand(1);
8808 SDValue Concat1Op1 = Op1.getOperand(1);
8809 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8810 Concat1Op1.getOpcode() != ISD::UNDEF)
8812 // Skip the transformation if any of the types are illegal.
8813 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8814 EVT VT = N->getValueType(0);
8815 if (!TLI.isTypeLegal(VT) ||
8816 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8817 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8820 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8821 Op0.getOperand(0), Op1.getOperand(0));
8822 // Translate the shuffle mask.
8823 SmallVector<int, 16> NewMask;
8824 unsigned NumElts = VT.getVectorNumElements();
8825 unsigned HalfElts = NumElts/2;
8826 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8827 for (unsigned n = 0; n < NumElts; ++n) {
8828 int MaskElt = SVN->getMaskElt(n);
8830 if (MaskElt < (int)HalfElts)
8832 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8833 NewElt = HalfElts + MaskElt - NumElts;
8834 NewMask.push_back(NewElt);
8836 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8837 DAG.getUNDEF(VT), NewMask.data());
8840 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8841 /// NEON load/store intrinsics to merge base address updates.
8842 static SDValue CombineBaseUpdate(SDNode *N,
8843 TargetLowering::DAGCombinerInfo &DCI) {
8844 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8847 SelectionDAG &DAG = DCI.DAG;
8848 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8849 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8850 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8851 SDValue Addr = N->getOperand(AddrOpIdx);
8853 // Search for a use of the address operand that is an increment.
8854 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8855 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8857 if (User->getOpcode() != ISD::ADD ||
8858 UI.getUse().getResNo() != Addr.getResNo())
8861 // Check that the add is independent of the load/store. Otherwise, folding
8862 // it would create a cycle.
8863 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8866 // Find the new opcode for the updating load/store.
8868 bool isLaneOp = false;
8869 unsigned NewOpc = 0;
8870 unsigned NumVecs = 0;
8872 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8874 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8875 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8877 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8879 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8881 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8883 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8884 NumVecs = 2; isLaneOp = true; break;
8885 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8886 NumVecs = 3; isLaneOp = true; break;
8887 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8888 NumVecs = 4; isLaneOp = true; break;
8889 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8890 NumVecs = 1; isLoad = false; break;
8891 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8892 NumVecs = 2; isLoad = false; break;
8893 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8894 NumVecs = 3; isLoad = false; break;
8895 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8896 NumVecs = 4; isLoad = false; break;
8897 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8898 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8899 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8900 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8901 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8902 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8906 switch (N->getOpcode()) {
8907 default: llvm_unreachable("unexpected opcode for Neon base update");
8908 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8909 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8910 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8914 // Find the size of memory referenced by the load/store.
8917 VecTy = N->getValueType(0);
8919 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8920 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8922 NumBytes /= VecTy.getVectorNumElements();
8924 // If the increment is a constant, it must match the memory ref size.
8925 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8926 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8927 uint64_t IncVal = CInc->getZExtValue();
8928 if (IncVal != NumBytes)
8930 } else if (NumBytes >= 3 * 16) {
8931 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8932 // separate instructions that make it harder to use a non-constant update.
8936 // Create the new updating load/store node.
8938 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8940 for (n = 0; n < NumResultVecs; ++n)
8942 Tys[n++] = MVT::i32;
8943 Tys[n] = MVT::Other;
8944 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8945 SmallVector<SDValue, 8> Ops;
8946 Ops.push_back(N->getOperand(0)); // incoming chain
8947 Ops.push_back(N->getOperand(AddrOpIdx));
8949 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8950 Ops.push_back(N->getOperand(i));
8952 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8953 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8954 Ops, MemInt->getMemoryVT(),
8955 MemInt->getMemOperand());
8958 std::vector<SDValue> NewResults;
8959 for (unsigned i = 0; i < NumResultVecs; ++i) {
8960 NewResults.push_back(SDValue(UpdN.getNode(), i));
8962 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8963 DCI.CombineTo(N, NewResults);
8964 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8971 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8972 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8973 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8975 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8976 SelectionDAG &DAG = DCI.DAG;
8977 EVT VT = N->getValueType(0);
8978 // vldN-dup instructions only support 64-bit vectors for N > 1.
8979 if (!VT.is64BitVector())
8982 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8983 SDNode *VLD = N->getOperand(0).getNode();
8984 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8986 unsigned NumVecs = 0;
8987 unsigned NewOpc = 0;
8988 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8989 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8991 NewOpc = ARMISD::VLD2DUP;
8992 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8994 NewOpc = ARMISD::VLD3DUP;
8995 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8997 NewOpc = ARMISD::VLD4DUP;
9002 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9003 // numbers match the load.
9004 unsigned VLDLaneNo =
9005 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9006 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9008 // Ignore uses of the chain result.
9009 if (UI.getUse().getResNo() == NumVecs)
9012 if (User->getOpcode() != ARMISD::VDUPLANE ||
9013 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9017 // Create the vldN-dup node.
9020 for (n = 0; n < NumVecs; ++n)
9022 Tys[n] = MVT::Other;
9023 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9024 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9025 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9026 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9027 Ops, VLDMemInt->getMemoryVT(),
9028 VLDMemInt->getMemOperand());
9031 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9033 unsigned ResNo = UI.getUse().getResNo();
9034 // Ignore uses of the chain result.
9035 if (ResNo == NumVecs)
9038 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9041 // Now the vldN-lane intrinsic is dead except for its chain result.
9042 // Update uses of the chain.
9043 std::vector<SDValue> VLDDupResults;
9044 for (unsigned n = 0; n < NumVecs; ++n)
9045 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9046 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9047 DCI.CombineTo(VLD, VLDDupResults);
9052 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9053 /// ARMISD::VDUPLANE.
9054 static SDValue PerformVDUPLANECombine(SDNode *N,
9055 TargetLowering::DAGCombinerInfo &DCI) {
9056 SDValue Op = N->getOperand(0);
9058 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9059 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9060 if (CombineVLDDUP(N, DCI))
9061 return SDValue(N, 0);
9063 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9064 // redundant. Ignore bit_converts for now; element sizes are checked below.
9065 while (Op.getOpcode() == ISD::BITCAST)
9066 Op = Op.getOperand(0);
9067 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9070 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9071 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9072 // The canonical VMOV for a zero vector uses a 32-bit element size.
9073 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9075 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9077 EVT VT = N->getValueType(0);
9078 if (EltSize > VT.getVectorElementType().getSizeInBits())
9081 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9084 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9085 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9086 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9090 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9092 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9097 APFloat APF = C->getValueAPF();
9098 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9099 != APFloat::opOK || !isExact)
9102 c0 = (I == 0) ? cN : c0;
9103 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9110 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9111 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9112 /// when the VMUL has a constant operand that is a power of 2.
9114 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9115 /// vmul.f32 d16, d17, d16
9116 /// vcvt.s32.f32 d16, d16
9118 /// vcvt.s32.f32 d16, d16, #3
9119 static SDValue PerformVCVTCombine(SDNode *N,
9120 TargetLowering::DAGCombinerInfo &DCI,
9121 const ARMSubtarget *Subtarget) {
9122 SelectionDAG &DAG = DCI.DAG;
9123 SDValue Op = N->getOperand(0);
9125 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9126 Op.getOpcode() != ISD::FMUL)
9130 SDValue N0 = Op->getOperand(0);
9131 SDValue ConstVec = Op->getOperand(1);
9132 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9134 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9135 !isConstVecPow2(ConstVec, isSigned, C))
9138 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9139 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9140 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9141 // These instructions only exist converting from f32 to i32. We can handle
9142 // smaller integers by generating an extra truncate, but larger ones would
9147 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9148 Intrinsic::arm_neon_vcvtfp2fxu;
9149 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9150 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9151 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9152 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9153 DAG.getConstant(Log2_64(C), MVT::i32));
9155 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9156 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9161 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9162 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9163 /// when the VDIV has a constant operand that is a power of 2.
9165 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9166 /// vcvt.f32.s32 d16, d16
9167 /// vdiv.f32 d16, d17, d16
9169 /// vcvt.f32.s32 d16, d16, #3
9170 static SDValue PerformVDIVCombine(SDNode *N,
9171 TargetLowering::DAGCombinerInfo &DCI,
9172 const ARMSubtarget *Subtarget) {
9173 SelectionDAG &DAG = DCI.DAG;
9174 SDValue Op = N->getOperand(0);
9175 unsigned OpOpcode = Op.getNode()->getOpcode();
9177 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9178 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9182 SDValue ConstVec = N->getOperand(1);
9183 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9185 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9186 !isConstVecPow2(ConstVec, isSigned, C))
9189 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9190 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9191 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9192 // These instructions only exist converting from i32 to f32. We can handle
9193 // smaller integers by generating an extra extend, but larger ones would
9198 SDValue ConvInput = Op.getOperand(0);
9199 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9200 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9201 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9202 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9205 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9206 Intrinsic::arm_neon_vcvtfxu2fp;
9207 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9209 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9210 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9213 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9214 /// operand of a vector shift operation, where all the elements of the
9215 /// build_vector must have the same constant integer value.
9216 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9217 // Ignore bit_converts.
9218 while (Op.getOpcode() == ISD::BITCAST)
9219 Op = Op.getOperand(0);
9220 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9221 APInt SplatBits, SplatUndef;
9222 unsigned SplatBitSize;
9224 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9225 HasAnyUndefs, ElementBits) ||
9226 SplatBitSize > ElementBits)
9228 Cnt = SplatBits.getSExtValue();
9232 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9233 /// operand of a vector shift left operation. That value must be in the range:
9234 /// 0 <= Value < ElementBits for a left shift; or
9235 /// 0 <= Value <= ElementBits for a long left shift.
9236 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9237 assert(VT.isVector() && "vector shift count is not a vector type");
9238 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9239 if (! getVShiftImm(Op, ElementBits, Cnt))
9241 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9244 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9245 /// operand of a vector shift right operation. For a shift opcode, the value
9246 /// is positive, but for an intrinsic the value count must be negative. The
9247 /// absolute value must be in the range:
9248 /// 1 <= |Value| <= ElementBits for a right shift; or
9249 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9250 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9252 assert(VT.isVector() && "vector shift count is not a vector type");
9253 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9254 if (! getVShiftImm(Op, ElementBits, Cnt))
9258 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9261 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9262 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9263 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9266 // Don't do anything for most intrinsics.
9269 // Vector shifts: check for immediate versions and lower them.
9270 // Note: This is done during DAG combining instead of DAG legalizing because
9271 // the build_vectors for 64-bit vector element shift counts are generally
9272 // not legal, and it is hard to see their values after they get legalized to
9273 // loads from a constant pool.
9274 case Intrinsic::arm_neon_vshifts:
9275 case Intrinsic::arm_neon_vshiftu:
9276 case Intrinsic::arm_neon_vrshifts:
9277 case Intrinsic::arm_neon_vrshiftu:
9278 case Intrinsic::arm_neon_vrshiftn:
9279 case Intrinsic::arm_neon_vqshifts:
9280 case Intrinsic::arm_neon_vqshiftu:
9281 case Intrinsic::arm_neon_vqshiftsu:
9282 case Intrinsic::arm_neon_vqshiftns:
9283 case Intrinsic::arm_neon_vqshiftnu:
9284 case Intrinsic::arm_neon_vqshiftnsu:
9285 case Intrinsic::arm_neon_vqrshiftns:
9286 case Intrinsic::arm_neon_vqrshiftnu:
9287 case Intrinsic::arm_neon_vqrshiftnsu: {
9288 EVT VT = N->getOperand(1).getValueType();
9290 unsigned VShiftOpc = 0;
9293 case Intrinsic::arm_neon_vshifts:
9294 case Intrinsic::arm_neon_vshiftu:
9295 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9296 VShiftOpc = ARMISD::VSHL;
9299 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9300 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9301 ARMISD::VSHRs : ARMISD::VSHRu);
9306 case Intrinsic::arm_neon_vrshifts:
9307 case Intrinsic::arm_neon_vrshiftu:
9308 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9312 case Intrinsic::arm_neon_vqshifts:
9313 case Intrinsic::arm_neon_vqshiftu:
9314 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9318 case Intrinsic::arm_neon_vqshiftsu:
9319 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9321 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9323 case Intrinsic::arm_neon_vrshiftn:
9324 case Intrinsic::arm_neon_vqshiftns:
9325 case Intrinsic::arm_neon_vqshiftnu:
9326 case Intrinsic::arm_neon_vqshiftnsu:
9327 case Intrinsic::arm_neon_vqrshiftns:
9328 case Intrinsic::arm_neon_vqrshiftnu:
9329 case Intrinsic::arm_neon_vqrshiftnsu:
9330 // Narrowing shifts require an immediate right shift.
9331 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9333 llvm_unreachable("invalid shift count for narrowing vector shift "
9337 llvm_unreachable("unhandled vector shift");
9341 case Intrinsic::arm_neon_vshifts:
9342 case Intrinsic::arm_neon_vshiftu:
9343 // Opcode already set above.
9345 case Intrinsic::arm_neon_vrshifts:
9346 VShiftOpc = ARMISD::VRSHRs; break;
9347 case Intrinsic::arm_neon_vrshiftu:
9348 VShiftOpc = ARMISD::VRSHRu; break;
9349 case Intrinsic::arm_neon_vrshiftn:
9350 VShiftOpc = ARMISD::VRSHRN; break;
9351 case Intrinsic::arm_neon_vqshifts:
9352 VShiftOpc = ARMISD::VQSHLs; break;
9353 case Intrinsic::arm_neon_vqshiftu:
9354 VShiftOpc = ARMISD::VQSHLu; break;
9355 case Intrinsic::arm_neon_vqshiftsu:
9356 VShiftOpc = ARMISD::VQSHLsu; break;
9357 case Intrinsic::arm_neon_vqshiftns:
9358 VShiftOpc = ARMISD::VQSHRNs; break;
9359 case Intrinsic::arm_neon_vqshiftnu:
9360 VShiftOpc = ARMISD::VQSHRNu; break;
9361 case Intrinsic::arm_neon_vqshiftnsu:
9362 VShiftOpc = ARMISD::VQSHRNsu; break;
9363 case Intrinsic::arm_neon_vqrshiftns:
9364 VShiftOpc = ARMISD::VQRSHRNs; break;
9365 case Intrinsic::arm_neon_vqrshiftnu:
9366 VShiftOpc = ARMISD::VQRSHRNu; break;
9367 case Intrinsic::arm_neon_vqrshiftnsu:
9368 VShiftOpc = ARMISD::VQRSHRNsu; break;
9371 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9372 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9375 case Intrinsic::arm_neon_vshiftins: {
9376 EVT VT = N->getOperand(1).getValueType();
9378 unsigned VShiftOpc = 0;
9380 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9381 VShiftOpc = ARMISD::VSLI;
9382 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9383 VShiftOpc = ARMISD::VSRI;
9385 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9388 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9389 N->getOperand(1), N->getOperand(2),
9390 DAG.getConstant(Cnt, MVT::i32));
9393 case Intrinsic::arm_neon_vqrshifts:
9394 case Intrinsic::arm_neon_vqrshiftu:
9395 // No immediate versions of these to check for.
9402 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9403 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9404 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9405 /// vector element shift counts are generally not legal, and it is hard to see
9406 /// their values after they get legalized to loads from a constant pool.
9407 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9408 const ARMSubtarget *ST) {
9409 EVT VT = N->getValueType(0);
9410 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9411 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9412 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9413 SDValue N1 = N->getOperand(1);
9414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9415 SDValue N0 = N->getOperand(0);
9416 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9417 DAG.MaskedValueIsZero(N0.getOperand(0),
9418 APInt::getHighBitsSet(32, 16)))
9419 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9423 // Nothing to be done for scalar shifts.
9424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9425 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9428 assert(ST->hasNEON() && "unexpected vector shift");
9431 switch (N->getOpcode()) {
9432 default: llvm_unreachable("unexpected shift opcode");
9435 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9436 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9437 DAG.getConstant(Cnt, MVT::i32));
9442 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9443 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9444 ARMISD::VSHRs : ARMISD::VSHRu);
9445 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9446 DAG.getConstant(Cnt, MVT::i32));
9452 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9453 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9454 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9455 const ARMSubtarget *ST) {
9456 SDValue N0 = N->getOperand(0);
9458 // Check for sign- and zero-extensions of vector extract operations of 8-
9459 // and 16-bit vector elements. NEON supports these directly. They are
9460 // handled during DAG combining because type legalization will promote them
9461 // to 32-bit types and it is messy to recognize the operations after that.
9462 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9463 SDValue Vec = N0.getOperand(0);
9464 SDValue Lane = N0.getOperand(1);
9465 EVT VT = N->getValueType(0);
9466 EVT EltVT = N0.getValueType();
9467 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9469 if (VT == MVT::i32 &&
9470 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9471 TLI.isTypeLegal(Vec.getValueType()) &&
9472 isa<ConstantSDNode>(Lane)) {
9475 switch (N->getOpcode()) {
9476 default: llvm_unreachable("unexpected opcode");
9477 case ISD::SIGN_EXTEND:
9478 Opc = ARMISD::VGETLANEs;
9480 case ISD::ZERO_EXTEND:
9481 case ISD::ANY_EXTEND:
9482 Opc = ARMISD::VGETLANEu;
9485 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9492 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9493 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9494 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9495 const ARMSubtarget *ST) {
9496 // If the target supports NEON, try to use vmax/vmin instructions for f32
9497 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9498 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9499 // a NaN; only do the transformation when it matches that behavior.
9501 // For now only do this when using NEON for FP operations; if using VFP, it
9502 // is not obvious that the benefit outweighs the cost of switching to the
9504 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9505 N->getValueType(0) != MVT::f32)
9508 SDValue CondLHS = N->getOperand(0);
9509 SDValue CondRHS = N->getOperand(1);
9510 SDValue LHS = N->getOperand(2);
9511 SDValue RHS = N->getOperand(3);
9512 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9514 unsigned Opcode = 0;
9516 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9517 IsReversed = false; // x CC y ? x : y
9518 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9519 IsReversed = true ; // x CC y ? y : x
9533 // If LHS is NaN, an ordered comparison will be false and the result will
9534 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9535 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9536 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9537 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9539 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9540 // will return -0, so vmin can only be used for unsafe math or if one of
9541 // the operands is known to be nonzero.
9542 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9543 !DAG.getTarget().Options.UnsafeFPMath &&
9544 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9546 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9555 // If LHS is NaN, an ordered comparison will be false and the result will
9556 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9557 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9558 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9559 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9561 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9562 // will return +0, so vmax can only be used for unsafe math or if one of
9563 // the operands is known to be nonzero.
9564 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9565 !DAG.getTarget().Options.UnsafeFPMath &&
9566 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9568 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9574 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9577 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9579 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9580 SDValue Cmp = N->getOperand(4);
9581 if (Cmp.getOpcode() != ARMISD::CMPZ)
9582 // Only looking at EQ and NE cases.
9585 EVT VT = N->getValueType(0);
9587 SDValue LHS = Cmp.getOperand(0);
9588 SDValue RHS = Cmp.getOperand(1);
9589 SDValue FalseVal = N->getOperand(0);
9590 SDValue TrueVal = N->getOperand(1);
9591 SDValue ARMcc = N->getOperand(2);
9592 ARMCC::CondCodes CC =
9593 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9611 /// FIXME: Turn this into a target neutral optimization?
9613 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9614 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9615 N->getOperand(3), Cmp);
9616 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9618 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9619 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9620 N->getOperand(3), NewCmp);
9623 if (Res.getNode()) {
9624 APInt KnownZero, KnownOne;
9625 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9626 // Capture demanded bits information that would be otherwise lost.
9627 if (KnownZero == 0xfffffffe)
9628 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9629 DAG.getValueType(MVT::i1));
9630 else if (KnownZero == 0xffffff00)
9631 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9632 DAG.getValueType(MVT::i8));
9633 else if (KnownZero == 0xffff0000)
9634 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9635 DAG.getValueType(MVT::i16));
9641 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9642 DAGCombinerInfo &DCI) const {
9643 switch (N->getOpcode()) {
9645 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9646 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9647 case ISD::SUB: return PerformSUBCombine(N, DCI);
9648 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9649 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9650 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9651 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9652 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9653 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9654 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9655 case ISD::STORE: return PerformSTORECombine(N, DCI);
9656 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9657 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9658 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9659 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9660 case ISD::FP_TO_SINT:
9661 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9662 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9663 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9666 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9667 case ISD::SIGN_EXTEND:
9668 case ISD::ZERO_EXTEND:
9669 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9670 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9671 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9672 case ARMISD::VLD2DUP:
9673 case ARMISD::VLD3DUP:
9674 case ARMISD::VLD4DUP:
9675 return CombineBaseUpdate(N, DCI);
9676 case ARMISD::BUILD_VECTOR:
9677 return PerformARMBUILD_VECTORCombine(N, DCI);
9678 case ISD::INTRINSIC_VOID:
9679 case ISD::INTRINSIC_W_CHAIN:
9680 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9681 case Intrinsic::arm_neon_vld1:
9682 case Intrinsic::arm_neon_vld2:
9683 case Intrinsic::arm_neon_vld3:
9684 case Intrinsic::arm_neon_vld4:
9685 case Intrinsic::arm_neon_vld2lane:
9686 case Intrinsic::arm_neon_vld3lane:
9687 case Intrinsic::arm_neon_vld4lane:
9688 case Intrinsic::arm_neon_vst1:
9689 case Intrinsic::arm_neon_vst2:
9690 case Intrinsic::arm_neon_vst3:
9691 case Intrinsic::arm_neon_vst4:
9692 case Intrinsic::arm_neon_vst2lane:
9693 case Intrinsic::arm_neon_vst3lane:
9694 case Intrinsic::arm_neon_vst4lane:
9695 return CombineBaseUpdate(N, DCI);
9703 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9705 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9708 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9712 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9713 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9715 switch (VT.getSimpleVT().SimpleTy) {
9721 // Unaligned access can use (for example) LRDB, LRDH, LDR
9722 if (AllowsUnaligned) {
9724 *Fast = Subtarget->hasV7Ops();
9731 // For any little-endian targets with neon, we can support unaligned ld/st
9732 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9733 // A big-endian target may also explicitly support unaligned accesses
9734 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9744 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9745 unsigned AlignCheck) {
9746 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9747 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9750 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9751 unsigned DstAlign, unsigned SrcAlign,
9752 bool IsMemset, bool ZeroMemset,
9754 MachineFunction &MF) const {
9755 const Function *F = MF.getFunction();
9757 // See if we can use NEON instructions for this...
9758 if ((!IsMemset || ZeroMemset) &&
9759 Subtarget->hasNEON() &&
9760 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9761 Attribute::NoImplicitFloat)) {
9764 (memOpAlign(SrcAlign, DstAlign, 16) ||
9765 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9767 } else if (Size >= 8 &&
9768 (memOpAlign(SrcAlign, DstAlign, 8) ||
9769 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9775 // Lowering to i32/i16 if the size permits.
9781 // Let the target-independent logic figure it out.
9785 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9786 if (Val.getOpcode() != ISD::LOAD)
9789 EVT VT1 = Val.getValueType();
9790 if (!VT1.isSimple() || !VT1.isInteger() ||
9791 !VT2.isSimple() || !VT2.isInteger())
9794 switch (VT1.getSimpleVT().SimpleTy) {
9799 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9806 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9807 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9810 if (!isTypeLegal(EVT::getEVT(Ty1)))
9813 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9815 // Assuming the caller doesn't have a zeroext or signext return parameter,
9816 // truncation all the way down to i1 is valid.
9821 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9826 switch (VT.getSimpleVT().SimpleTy) {
9827 default: return false;
9842 if ((V & (Scale - 1)) != 0)
9845 return V == (V & ((1LL << 5) - 1));
9848 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9849 const ARMSubtarget *Subtarget) {
9856 switch (VT.getSimpleVT().SimpleTy) {
9857 default: return false;
9862 // + imm12 or - imm8
9864 return V == (V & ((1LL << 8) - 1));
9865 return V == (V & ((1LL << 12) - 1));
9868 // Same as ARM mode. FIXME: NEON?
9869 if (!Subtarget->hasVFP2())
9874 return V == (V & ((1LL << 8) - 1));
9878 /// isLegalAddressImmediate - Return true if the integer value can be used
9879 /// as the offset of the target addressing mode for load / store of the
9881 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9882 const ARMSubtarget *Subtarget) {
9889 if (Subtarget->isThumb1Only())
9890 return isLegalT1AddressImmediate(V, VT);
9891 else if (Subtarget->isThumb2())
9892 return isLegalT2AddressImmediate(V, VT, Subtarget);
9897 switch (VT.getSimpleVT().SimpleTy) {
9898 default: return false;
9903 return V == (V & ((1LL << 12) - 1));
9906 return V == (V & ((1LL << 8) - 1));
9909 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9914 return V == (V & ((1LL << 8) - 1));
9918 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9920 int Scale = AM.Scale;
9924 switch (VT.getSimpleVT().SimpleTy) {
9925 default: return false;
9934 return Scale == 2 || Scale == 4 || Scale == 8;
9937 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9941 // Note, we allow "void" uses (basically, uses that aren't loads or
9942 // stores), because arm allows folding a scale into many arithmetic
9943 // operations. This should be made more precise and revisited later.
9945 // Allow r << imm, but the imm has to be a multiple of two.
9946 if (Scale & 1) return false;
9947 return isPowerOf2_32(Scale);
9951 /// isLegalAddressingMode - Return true if the addressing mode represented
9952 /// by AM is legal for this target, for a load/store of the specified type.
9953 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9955 EVT VT = getValueType(Ty, true);
9956 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9959 // Can never fold addr of global into load/store.
9964 case 0: // no scale reg, must be "r+i" or "r", or "i".
9967 if (Subtarget->isThumb1Only())
9971 // ARM doesn't support any R+R*scale+imm addr modes.
9978 if (Subtarget->isThumb2())
9979 return isLegalT2ScaledAddressingMode(AM, VT);
9981 int Scale = AM.Scale;
9982 switch (VT.getSimpleVT().SimpleTy) {
9983 default: return false;
9987 if (Scale < 0) Scale = -Scale;
9991 return isPowerOf2_32(Scale & ~1);
9995 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10000 // Note, we allow "void" uses (basically, uses that aren't loads or
10001 // stores), because arm allows folding a scale into many arithmetic
10002 // operations. This should be made more precise and revisited later.
10004 // Allow r << imm, but the imm has to be a multiple of two.
10005 if (Scale & 1) return false;
10006 return isPowerOf2_32(Scale);
10012 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10013 /// icmp immediate, that is the target has icmp instructions which can compare
10014 /// a register against the immediate without having to materialize the
10015 /// immediate into a register.
10016 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10017 // Thumb2 and ARM modes can use cmn for negative immediates.
10018 if (!Subtarget->isThumb())
10019 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10020 if (Subtarget->isThumb2())
10021 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10022 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10023 return Imm >= 0 && Imm <= 255;
10026 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10027 /// *or sub* immediate, that is the target has add or sub instructions which can
10028 /// add a register with the immediate without having to materialize the
10029 /// immediate into a register.
10030 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10031 // Same encoding for add/sub, just flip the sign.
10032 int64_t AbsImm = llvm::abs64(Imm);
10033 if (!Subtarget->isThumb())
10034 return ARM_AM::getSOImmVal(AbsImm) != -1;
10035 if (Subtarget->isThumb2())
10036 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10037 // Thumb1 only has 8-bit unsigned immediate.
10038 return AbsImm >= 0 && AbsImm <= 255;
10041 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10042 bool isSEXTLoad, SDValue &Base,
10043 SDValue &Offset, bool &isInc,
10044 SelectionDAG &DAG) {
10045 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10048 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10049 // AddressingMode 3
10050 Base = Ptr->getOperand(0);
10051 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10052 int RHSC = (int)RHS->getZExtValue();
10053 if (RHSC < 0 && RHSC > -256) {
10054 assert(Ptr->getOpcode() == ISD::ADD);
10056 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10060 isInc = (Ptr->getOpcode() == ISD::ADD);
10061 Offset = Ptr->getOperand(1);
10063 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10064 // AddressingMode 2
10065 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10066 int RHSC = (int)RHS->getZExtValue();
10067 if (RHSC < 0 && RHSC > -0x1000) {
10068 assert(Ptr->getOpcode() == ISD::ADD);
10070 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10071 Base = Ptr->getOperand(0);
10076 if (Ptr->getOpcode() == ISD::ADD) {
10078 ARM_AM::ShiftOpc ShOpcVal=
10079 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10080 if (ShOpcVal != ARM_AM::no_shift) {
10081 Base = Ptr->getOperand(1);
10082 Offset = Ptr->getOperand(0);
10084 Base = Ptr->getOperand(0);
10085 Offset = Ptr->getOperand(1);
10090 isInc = (Ptr->getOpcode() == ISD::ADD);
10091 Base = Ptr->getOperand(0);
10092 Offset = Ptr->getOperand(1);
10096 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10100 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10101 bool isSEXTLoad, SDValue &Base,
10102 SDValue &Offset, bool &isInc,
10103 SelectionDAG &DAG) {
10104 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10107 Base = Ptr->getOperand(0);
10108 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10109 int RHSC = (int)RHS->getZExtValue();
10110 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10111 assert(Ptr->getOpcode() == ISD::ADD);
10113 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10115 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10116 isInc = Ptr->getOpcode() == ISD::ADD;
10117 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10125 /// getPreIndexedAddressParts - returns true by value, base pointer and
10126 /// offset pointer and addressing mode by reference if the node's address
10127 /// can be legally represented as pre-indexed load / store address.
10129 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10131 ISD::MemIndexedMode &AM,
10132 SelectionDAG &DAG) const {
10133 if (Subtarget->isThumb1Only())
10138 bool isSEXTLoad = false;
10139 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10140 Ptr = LD->getBasePtr();
10141 VT = LD->getMemoryVT();
10142 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10143 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10144 Ptr = ST->getBasePtr();
10145 VT = ST->getMemoryVT();
10150 bool isLegal = false;
10151 if (Subtarget->isThumb2())
10152 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10153 Offset, isInc, DAG);
10155 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10156 Offset, isInc, DAG);
10160 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10164 /// getPostIndexedAddressParts - returns true by value, base pointer and
10165 /// offset pointer and addressing mode by reference if this node can be
10166 /// combined with a load / store to form a post-indexed load / store.
10167 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10170 ISD::MemIndexedMode &AM,
10171 SelectionDAG &DAG) const {
10172 if (Subtarget->isThumb1Only())
10177 bool isSEXTLoad = false;
10178 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10179 VT = LD->getMemoryVT();
10180 Ptr = LD->getBasePtr();
10181 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10182 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10183 VT = ST->getMemoryVT();
10184 Ptr = ST->getBasePtr();
10189 bool isLegal = false;
10190 if (Subtarget->isThumb2())
10191 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10194 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10200 // Swap base ptr and offset to catch more post-index load / store when
10201 // it's legal. In Thumb2 mode, offset must be an immediate.
10202 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10203 !Subtarget->isThumb2())
10204 std::swap(Base, Offset);
10206 // Post-indexed load / store update the base pointer.
10211 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10215 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10218 const SelectionDAG &DAG,
10219 unsigned Depth) const {
10220 unsigned BitWidth = KnownOne.getBitWidth();
10221 KnownZero = KnownOne = APInt(BitWidth, 0);
10222 switch (Op.getOpcode()) {
10228 // These nodes' second result is a boolean
10229 if (Op.getResNo() == 0)
10231 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10233 case ARMISD::CMOV: {
10234 // Bits are known zero/one if known on the LHS and RHS.
10235 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10236 if (KnownZero == 0 && KnownOne == 0) return;
10238 APInt KnownZeroRHS, KnownOneRHS;
10239 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10240 KnownZero &= KnownZeroRHS;
10241 KnownOne &= KnownOneRHS;
10244 case ISD::INTRINSIC_W_CHAIN: {
10245 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10246 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10249 case Intrinsic::arm_ldaex:
10250 case Intrinsic::arm_ldrex: {
10251 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10252 unsigned MemBits = VT.getScalarType().getSizeInBits();
10253 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10261 //===----------------------------------------------------------------------===//
10262 // ARM Inline Assembly Support
10263 //===----------------------------------------------------------------------===//
10265 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10266 // Looking for "rev" which is V6+.
10267 if (!Subtarget->hasV6Ops())
10270 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10271 std::string AsmStr = IA->getAsmString();
10272 SmallVector<StringRef, 4> AsmPieces;
10273 SplitString(AsmStr, AsmPieces, ";\n");
10275 switch (AsmPieces.size()) {
10276 default: return false;
10278 AsmStr = AsmPieces[0];
10280 SplitString(AsmStr, AsmPieces, " \t,");
10283 if (AsmPieces.size() == 3 &&
10284 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10285 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10286 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10287 if (Ty && Ty->getBitWidth() == 32)
10288 return IntrinsicLowering::LowerToByteSwap(CI);
10296 /// getConstraintType - Given a constraint letter, return the type of
10297 /// constraint it is for this target.
10298 ARMTargetLowering::ConstraintType
10299 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10300 if (Constraint.size() == 1) {
10301 switch (Constraint[0]) {
10303 case 'l': return C_RegisterClass;
10304 case 'w': return C_RegisterClass;
10305 case 'h': return C_RegisterClass;
10306 case 'x': return C_RegisterClass;
10307 case 't': return C_RegisterClass;
10308 case 'j': return C_Other; // Constant for movw.
10309 // An address with a single base register. Due to the way we
10310 // currently handle addresses it is the same as an 'r' memory constraint.
10311 case 'Q': return C_Memory;
10313 } else if (Constraint.size() == 2) {
10314 switch (Constraint[0]) {
10316 // All 'U+' constraints are addresses.
10317 case 'U': return C_Memory;
10320 return TargetLowering::getConstraintType(Constraint);
10323 /// Examine constraint type and operand type and determine a weight value.
10324 /// This object must already have been set up with the operand type
10325 /// and the current alternative constraint selected.
10326 TargetLowering::ConstraintWeight
10327 ARMTargetLowering::getSingleConstraintMatchWeight(
10328 AsmOperandInfo &info, const char *constraint) const {
10329 ConstraintWeight weight = CW_Invalid;
10330 Value *CallOperandVal = info.CallOperandVal;
10331 // If we don't have a value, we can't do a match,
10332 // but allow it at the lowest weight.
10333 if (!CallOperandVal)
10335 Type *type = CallOperandVal->getType();
10336 // Look at the constraint type.
10337 switch (*constraint) {
10339 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10342 if (type->isIntegerTy()) {
10343 if (Subtarget->isThumb())
10344 weight = CW_SpecificReg;
10346 weight = CW_Register;
10350 if (type->isFloatingPointTy())
10351 weight = CW_Register;
10357 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10359 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10361 if (Constraint.size() == 1) {
10362 // GCC ARM Constraint Letters
10363 switch (Constraint[0]) {
10364 case 'l': // Low regs or general regs.
10365 if (Subtarget->isThumb())
10366 return RCPair(0U, &ARM::tGPRRegClass);
10367 return RCPair(0U, &ARM::GPRRegClass);
10368 case 'h': // High regs or no regs.
10369 if (Subtarget->isThumb())
10370 return RCPair(0U, &ARM::hGPRRegClass);
10373 return RCPair(0U, &ARM::GPRRegClass);
10375 if (VT == MVT::Other)
10377 if (VT == MVT::f32)
10378 return RCPair(0U, &ARM::SPRRegClass);
10379 if (VT.getSizeInBits() == 64)
10380 return RCPair(0U, &ARM::DPRRegClass);
10381 if (VT.getSizeInBits() == 128)
10382 return RCPair(0U, &ARM::QPRRegClass);
10385 if (VT == MVT::Other)
10387 if (VT == MVT::f32)
10388 return RCPair(0U, &ARM::SPR_8RegClass);
10389 if (VT.getSizeInBits() == 64)
10390 return RCPair(0U, &ARM::DPR_8RegClass);
10391 if (VT.getSizeInBits() == 128)
10392 return RCPair(0U, &ARM::QPR_8RegClass);
10395 if (VT == MVT::f32)
10396 return RCPair(0U, &ARM::SPRRegClass);
10400 if (StringRef("{cc}").equals_lower(Constraint))
10401 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10403 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10406 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10407 /// vector. If it is invalid, don't add anything to Ops.
10408 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10409 std::string &Constraint,
10410 std::vector<SDValue>&Ops,
10411 SelectionDAG &DAG) const {
10414 // Currently only support length 1 constraints.
10415 if (Constraint.length() != 1) return;
10417 char ConstraintLetter = Constraint[0];
10418 switch (ConstraintLetter) {
10421 case 'I': case 'J': case 'K': case 'L':
10422 case 'M': case 'N': case 'O':
10423 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10427 int64_t CVal64 = C->getSExtValue();
10428 int CVal = (int) CVal64;
10429 // None of these constraints allow values larger than 32 bits. Check
10430 // that the value fits in an int.
10431 if (CVal != CVal64)
10434 switch (ConstraintLetter) {
10436 // Constant suitable for movw, must be between 0 and
10438 if (Subtarget->hasV6T2Ops())
10439 if (CVal >= 0 && CVal <= 65535)
10443 if (Subtarget->isThumb1Only()) {
10444 // This must be a constant between 0 and 255, for ADD
10446 if (CVal >= 0 && CVal <= 255)
10448 } else if (Subtarget->isThumb2()) {
10449 // A constant that can be used as an immediate value in a
10450 // data-processing instruction.
10451 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10454 // A constant that can be used as an immediate value in a
10455 // data-processing instruction.
10456 if (ARM_AM::getSOImmVal(CVal) != -1)
10462 if (Subtarget->isThumb()) { // FIXME thumb2
10463 // This must be a constant between -255 and -1, for negated ADD
10464 // immediates. This can be used in GCC with an "n" modifier that
10465 // prints the negated value, for use with SUB instructions. It is
10466 // not useful otherwise but is implemented for compatibility.
10467 if (CVal >= -255 && CVal <= -1)
10470 // This must be a constant between -4095 and 4095. It is not clear
10471 // what this constraint is intended for. Implemented for
10472 // compatibility with GCC.
10473 if (CVal >= -4095 && CVal <= 4095)
10479 if (Subtarget->isThumb1Only()) {
10480 // A 32-bit value where only one byte has a nonzero value. Exclude
10481 // zero to match GCC. This constraint is used by GCC internally for
10482 // constants that can be loaded with a move/shift combination.
10483 // It is not useful otherwise but is implemented for compatibility.
10484 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10486 } else if (Subtarget->isThumb2()) {
10487 // A constant whose bitwise inverse can be used as an immediate
10488 // value in a data-processing instruction. This can be used in GCC
10489 // with a "B" modifier that prints the inverted value, for use with
10490 // BIC and MVN instructions. It is not useful otherwise but is
10491 // implemented for compatibility.
10492 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10495 // A constant whose bitwise inverse can be used as an immediate
10496 // value in a data-processing instruction. This can be used in GCC
10497 // with a "B" modifier that prints the inverted value, for use with
10498 // BIC and MVN instructions. It is not useful otherwise but is
10499 // implemented for compatibility.
10500 if (ARM_AM::getSOImmVal(~CVal) != -1)
10506 if (Subtarget->isThumb1Only()) {
10507 // This must be a constant between -7 and 7,
10508 // for 3-operand ADD/SUB immediate instructions.
10509 if (CVal >= -7 && CVal < 7)
10511 } else if (Subtarget->isThumb2()) {
10512 // A constant whose negation can be used as an immediate value in a
10513 // data-processing instruction. This can be used in GCC with an "n"
10514 // modifier that prints the negated value, for use with SUB
10515 // instructions. It is not useful otherwise but is implemented for
10517 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10520 // A constant whose negation can be used as an immediate value in a
10521 // data-processing instruction. This can be used in GCC with an "n"
10522 // modifier that prints the negated value, for use with SUB
10523 // instructions. It is not useful otherwise but is implemented for
10525 if (ARM_AM::getSOImmVal(-CVal) != -1)
10531 if (Subtarget->isThumb()) { // FIXME thumb2
10532 // This must be a multiple of 4 between 0 and 1020, for
10533 // ADD sp + immediate.
10534 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10537 // A power of two or a constant between 0 and 32. This is used in
10538 // GCC for the shift amount on shifted register operands, but it is
10539 // useful in general for any shift amounts.
10540 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10546 if (Subtarget->isThumb()) { // FIXME thumb2
10547 // This must be a constant between 0 and 31, for shift amounts.
10548 if (CVal >= 0 && CVal <= 31)
10554 if (Subtarget->isThumb()) { // FIXME thumb2
10555 // This must be a multiple of 4 between -508 and 508, for
10556 // ADD/SUB sp = sp + immediate.
10557 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10562 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10566 if (Result.getNode()) {
10567 Ops.push_back(Result);
10570 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10573 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10574 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10575 unsigned Opcode = Op->getOpcode();
10576 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10577 "Invalid opcode for Div/Rem lowering");
10578 bool isSigned = (Opcode == ISD::SDIVREM);
10579 EVT VT = Op->getValueType(0);
10580 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10583 switch (VT.getSimpleVT().SimpleTy) {
10584 default: llvm_unreachable("Unexpected request for libcall!");
10585 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10586 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10587 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10588 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10591 SDValue InChain = DAG.getEntryNode();
10593 TargetLowering::ArgListTy Args;
10594 TargetLowering::ArgListEntry Entry;
10595 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10596 EVT ArgVT = Op->getOperand(i).getValueType();
10597 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10598 Entry.Node = Op->getOperand(i);
10600 Entry.isSExt = isSigned;
10601 Entry.isZExt = !isSigned;
10602 Args.push_back(Entry);
10605 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10608 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10611 TargetLowering::CallLoweringInfo CLI(DAG);
10612 CLI.setDebugLoc(dl).setChain(InChain)
10613 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10614 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10616 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10617 return CallInfo.first;
10621 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10622 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10626 SDValue Chain = Op.getOperand(0);
10627 SDValue Size = Op.getOperand(1);
10629 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10630 DAG.getConstant(2, MVT::i32));
10633 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10634 Flag = Chain.getValue(1);
10636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10637 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10639 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10640 Chain = NewSP.getValue(1);
10642 SDValue Ops[2] = { NewSP, Chain };
10643 return DAG.getMergeValues(Ops, DL);
10647 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10648 // The ARM target isn't yet aware of offsets.
10652 bool ARM::isBitFieldInvertedMask(unsigned v) {
10653 if (v == 0xffffffff)
10656 // there can be 1's on either or both "outsides", all the "inside"
10657 // bits must be 0's
10658 unsigned TO = CountTrailingOnes_32(v);
10659 unsigned LO = CountLeadingOnes_32(v);
10660 v = (v >> TO) << TO;
10661 v = (v << LO) >> LO;
10665 /// isFPImmLegal - Returns true if the target can instruction select the
10666 /// specified FP immediate natively. If false, the legalizer will
10667 /// materialize the FP immediate as a load from a constant pool.
10668 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10669 if (!Subtarget->hasVFP3())
10671 if (VT == MVT::f32)
10672 return ARM_AM::getFP32Imm(Imm) != -1;
10673 if (VT == MVT::f64)
10674 return ARM_AM::getFP64Imm(Imm) != -1;
10678 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10679 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10680 /// specified in the intrinsic calls.
10681 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10683 unsigned Intrinsic) const {
10684 switch (Intrinsic) {
10685 case Intrinsic::arm_neon_vld1:
10686 case Intrinsic::arm_neon_vld2:
10687 case Intrinsic::arm_neon_vld3:
10688 case Intrinsic::arm_neon_vld4:
10689 case Intrinsic::arm_neon_vld2lane:
10690 case Intrinsic::arm_neon_vld3lane:
10691 case Intrinsic::arm_neon_vld4lane: {
10692 Info.opc = ISD::INTRINSIC_W_CHAIN;
10693 // Conservatively set memVT to the entire set of vectors loaded.
10694 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10695 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10696 Info.ptrVal = I.getArgOperand(0);
10698 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10699 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10700 Info.vol = false; // volatile loads with NEON intrinsics not supported
10701 Info.readMem = true;
10702 Info.writeMem = false;
10705 case Intrinsic::arm_neon_vst1:
10706 case Intrinsic::arm_neon_vst2:
10707 case Intrinsic::arm_neon_vst3:
10708 case Intrinsic::arm_neon_vst4:
10709 case Intrinsic::arm_neon_vst2lane:
10710 case Intrinsic::arm_neon_vst3lane:
10711 case Intrinsic::arm_neon_vst4lane: {
10712 Info.opc = ISD::INTRINSIC_VOID;
10713 // Conservatively set memVT to the entire set of vectors stored.
10714 unsigned NumElts = 0;
10715 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10716 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10717 if (!ArgTy->isVectorTy())
10719 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10721 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10722 Info.ptrVal = I.getArgOperand(0);
10724 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10725 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10726 Info.vol = false; // volatile stores with NEON intrinsics not supported
10727 Info.readMem = false;
10728 Info.writeMem = true;
10731 case Intrinsic::arm_ldaex:
10732 case Intrinsic::arm_ldrex: {
10733 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10734 Info.opc = ISD::INTRINSIC_W_CHAIN;
10735 Info.memVT = MVT::getVT(PtrTy->getElementType());
10736 Info.ptrVal = I.getArgOperand(0);
10738 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10740 Info.readMem = true;
10741 Info.writeMem = false;
10744 case Intrinsic::arm_stlex:
10745 case Intrinsic::arm_strex: {
10746 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10747 Info.opc = ISD::INTRINSIC_W_CHAIN;
10748 Info.memVT = MVT::getVT(PtrTy->getElementType());
10749 Info.ptrVal = I.getArgOperand(1);
10751 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10753 Info.readMem = false;
10754 Info.writeMem = true;
10757 case Intrinsic::arm_stlexd:
10758 case Intrinsic::arm_strexd: {
10759 Info.opc = ISD::INTRINSIC_W_CHAIN;
10760 Info.memVT = MVT::i64;
10761 Info.ptrVal = I.getArgOperand(2);
10765 Info.readMem = false;
10766 Info.writeMem = true;
10769 case Intrinsic::arm_ldaexd:
10770 case Intrinsic::arm_ldrexd: {
10771 Info.opc = ISD::INTRINSIC_W_CHAIN;
10772 Info.memVT = MVT::i64;
10773 Info.ptrVal = I.getArgOperand(0);
10777 Info.readMem = true;
10778 Info.writeMem = false;
10788 /// \brief Returns true if it is beneficial to convert a load of a constant
10789 /// to just the constant itself.
10790 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10792 assert(Ty->isIntegerTy());
10794 unsigned Bits = Ty->getPrimitiveSizeInBits();
10795 if (Bits == 0 || Bits > 32)
10800 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10801 // Loads and stores less than 64-bits are already atomic; ones above that
10802 // are doomed anyway, so defer to the default libcall and blame the OS when
10803 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10804 // anything for those.
10805 bool IsMClass = Subtarget->isMClass();
10806 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10807 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10808 return Size == 64 && !IsMClass;
10809 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10810 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10813 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10814 // and up to 64 bits on the non-M profiles
10815 unsigned AtomicLimit = IsMClass ? 32 : 64;
10816 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10819 // This has so far only been implemented for MachO.
10820 bool ARMTargetLowering::useLoadStackGuardNode() const {
10821 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10824 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10825 AtomicOrdering Ord) const {
10826 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10827 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10829 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10831 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10832 // intrinsic must return {i32, i32} and we have to recombine them into a
10833 // single i64 here.
10834 if (ValTy->getPrimitiveSizeInBits() == 64) {
10835 Intrinsic::ID Int =
10836 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10837 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10839 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10840 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10842 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10843 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10844 if (!Subtarget->isLittle())
10845 std::swap (Lo, Hi);
10846 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10847 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10848 return Builder.CreateOr(
10849 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10852 Type *Tys[] = { Addr->getType() };
10853 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10854 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10856 return Builder.CreateTruncOrBitCast(
10857 Builder.CreateCall(Ldrex, Addr),
10858 cast<PointerType>(Addr->getType())->getElementType());
10861 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10863 AtomicOrdering Ord) const {
10864 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10866 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10868 // Since the intrinsics must have legal type, the i64 intrinsics take two
10869 // parameters: "i32, i32". We must marshal Val into the appropriate form
10870 // before the call.
10871 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10872 Intrinsic::ID Int =
10873 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10874 Function *Strex = Intrinsic::getDeclaration(M, Int);
10875 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10877 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10878 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10879 if (!Subtarget->isLittle())
10880 std::swap (Lo, Hi);
10881 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10882 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10885 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10886 Type *Tys[] = { Addr->getType() };
10887 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10889 return Builder.CreateCall2(
10890 Strex, Builder.CreateZExtOrBitCast(
10891 Val, Strex->getFunctionType()->getParamType(0)),
10903 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10904 uint64_t &Members) {
10905 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10906 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10907 uint64_t SubMembers = 0;
10908 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10910 Members += SubMembers;
10912 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10913 uint64_t SubMembers = 0;
10914 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10916 Members += SubMembers * AT->getNumElements();
10917 } else if (Ty->isFloatTy()) {
10918 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10922 } else if (Ty->isDoubleTy()) {
10923 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10927 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10934 return VT->getBitWidth() == 64;
10936 return VT->getBitWidth() == 128;
10938 switch (VT->getBitWidth()) {
10951 return (Members > 0 && Members <= 4);
10954 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10955 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10956 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10957 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10958 CallingConv::ARM_AAPCS_VFP)
10961 HABaseType Base = HA_UNKNOWN;
10962 uint64_t Members = 0;
10963 bool result = isHomogeneousAggregate(Ty, Base, Members);
10964 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");