1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75 : CCState(CC, isVarArg, MF, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159 if (TT.isOSBinFormatMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TT.isOSWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168 Subtarget = &TM.getSubtarget<ARMSubtarget>();
169 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
170 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 if (Subtarget->isTargetMachO()) {
175 // Uses VFP for Thumb libfuncs if available.
176 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178 // Single-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184 // Double-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190 // Single-precision comparisons.
191 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
198 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
200 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
209 // Double-precision comparisons.
210 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
217 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
219 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
228 // Floating-point to integer conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236 // Conversions between floating types.
237 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
240 // Integer to floating-point conversions.
241 // i64 conversions are done via library routines even when generating VFP
242 // instructions, so use the same ones.
243 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244 // e.g., __floatunsidf vs. __floatunssidfvfp.
245 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
252 // These libcalls are not available in 32-bit.
253 setLibcallName(RTLIB::SHL_I128, nullptr);
254 setLibcallName(RTLIB::SRL_I128, nullptr);
255 setLibcallName(RTLIB::SRA_I128, nullptr);
257 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258 !Subtarget->isTargetWindows()) {
259 static const struct {
260 const RTLIB::Libcall Op;
261 const char * const Name;
262 const CallingConv::ID CC;
263 const ISD::CondCode Cond;
265 // Double-precision floating-point arithmetic helper functions
266 // RTABI chapter 4.1.2, Table 2
267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283 // Single-precision floating-point arithmetic helper functions
284 // RTABI chapter 4.1.2, Table 4
285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 // Single-precision floating-point comparison helper functions
291 // RTABI chapter 4.1.2, Table 5
292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301 // Floating-point to integer conversions.
302 // RTABI chapter 4.1.2, Table 6
303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Conversions between floating types.
313 // RTABI chapter 4.1.2, Table 7
314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 // Integer to floating-point conversions.
319 // RTABI chapter 4.1.2, Table 8
320 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Long long helper functions
330 // RTABI chapter 4.2, Table 9
331 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 // Integer division functions
337 // RTABI chapter 4.3.1
338 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348 // RTABI chapter 4.3.4
349 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
354 for (const auto &LC : LibraryCalls) {
355 setLibcallName(LC.Op, LC.Name);
356 setLibcallCallingConv(LC.Op, LC.CC);
357 if (LC.Cond != ISD::SETCC_INVALID)
358 setCmpLibcallCC(LC.Op, LC.Cond);
362 if (Subtarget->isTargetWindows()) {
363 static const struct {
364 const RTLIB::Libcall Op;
365 const char * const Name;
366 const CallingConv::ID CC;
368 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
378 for (const auto &LC : LibraryCalls) {
379 setLibcallName(LC.Op, LC.Name);
380 setLibcallCallingConv(LC.Op, LC.CC);
384 // Use divmod compiler-rt calls for iOS 5.0 and later.
385 if (Subtarget->getTargetTriple().isiOS() &&
386 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
391 // The half <-> float conversion functions are always soft-float, but are
392 // needed for some targets which use a hard-float calling convention by
394 if (Subtarget->isAAPCS_ABI()) {
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
404 if (Subtarget->isThumb1Only())
405 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
408 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
409 !Subtarget->isThumb1Only()) {
410 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
411 if (!Subtarget->isFPOnlySP())
412 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
415 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419 setTruncStoreAction((MVT::SimpleValueType)VT,
420 (MVT::SimpleValueType)InnerVT, Expand);
421 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
425 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
430 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
433 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
436 if (Subtarget->hasNEON()) {
437 addDRTypeForNEON(MVT::v2f32);
438 addDRTypeForNEON(MVT::v8i8);
439 addDRTypeForNEON(MVT::v4i16);
440 addDRTypeForNEON(MVT::v2i32);
441 addDRTypeForNEON(MVT::v1i64);
443 addQRTypeForNEON(MVT::v4f32);
444 addQRTypeForNEON(MVT::v2f64);
445 addQRTypeForNEON(MVT::v16i8);
446 addQRTypeForNEON(MVT::v8i16);
447 addQRTypeForNEON(MVT::v4i32);
448 addQRTypeForNEON(MVT::v2i64);
450 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451 // neither Neon nor VFP support any arithmetic operations on it.
452 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453 // supported for v4f32.
454 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457 // FIXME: Code duplication: FDIV and FREM are expanded always, see
458 // ARMTargetLowering::addTypeForNEON method for details.
459 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461 // FIXME: Create unittest.
462 // In another words, find a way when "copysign" appears in DAG with vector
464 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465 // FIXME: Code duplication: SETCC has custom operation action, see
466 // ARMTargetLowering::addTypeForNEON method for details.
467 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FNEG and for FABS.
469 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
489 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
505 // Mark v2f32 intrinsics.
506 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
545 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
547 // NEON does not have single instruction CTPOP for vectors with element
548 // types wider than 8-bits. However, custom lowering can leverage the
549 // v8i8/v16i8 vcnt instruction.
550 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
551 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
552 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
555 // NEON only has FMA instructions as of VFP4.
556 if (!Subtarget->hasVFP4()) {
557 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
561 setTargetDAGCombine(ISD::INTRINSIC_VOID);
562 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564 setTargetDAGCombine(ISD::SHL);
565 setTargetDAGCombine(ISD::SRL);
566 setTargetDAGCombine(ISD::SRA);
567 setTargetDAGCombine(ISD::SIGN_EXTEND);
568 setTargetDAGCombine(ISD::ZERO_EXTEND);
569 setTargetDAGCombine(ISD::ANY_EXTEND);
570 setTargetDAGCombine(ISD::SELECT_CC);
571 setTargetDAGCombine(ISD::BUILD_VECTOR);
572 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574 setTargetDAGCombine(ISD::STORE);
575 setTargetDAGCombine(ISD::FP_TO_SINT);
576 setTargetDAGCombine(ISD::FP_TO_UINT);
577 setTargetDAGCombine(ISD::FDIV);
579 // It is legal to extload from v4i8 to v4i16 or v4i32.
580 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581 MVT::v4i16, MVT::v2i16,
583 for (unsigned i = 0; i < 6; ++i) {
584 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
590 // ARM and Thumb2 support UMLAL/SMLAL.
591 if (!Subtarget->isThumb1Only())
592 setTargetDAGCombine(ISD::ADDC);
595 computeRegisterProperties();
597 // ARM does not have floating-point extending loads.
598 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
599 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
601 // ... or truncating stores
602 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
603 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
604 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
606 // ARM does not have i1 sign extending load.
607 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
609 // ARM supports all 4 flavors of integer indexed load / store.
610 if (!Subtarget->isThumb1Only()) {
611 for (unsigned im = (unsigned)ISD::PRE_INC;
612 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
613 setIndexedLoadAction(im, MVT::i1, Legal);
614 setIndexedLoadAction(im, MVT::i8, Legal);
615 setIndexedLoadAction(im, MVT::i16, Legal);
616 setIndexedLoadAction(im, MVT::i32, Legal);
617 setIndexedStoreAction(im, MVT::i1, Legal);
618 setIndexedStoreAction(im, MVT::i8, Legal);
619 setIndexedStoreAction(im, MVT::i16, Legal);
620 setIndexedStoreAction(im, MVT::i32, Legal);
624 setOperationAction(ISD::SADDO, MVT::i32, Custom);
625 setOperationAction(ISD::UADDO, MVT::i32, Custom);
626 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
627 setOperationAction(ISD::USUBO, MVT::i32, Custom);
629 // i64 operation support.
630 setOperationAction(ISD::MUL, MVT::i64, Expand);
631 setOperationAction(ISD::MULHU, MVT::i32, Expand);
632 if (Subtarget->isThumb1Only()) {
633 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
634 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
636 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
637 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
638 setOperationAction(ISD::MULHS, MVT::i32, Expand);
640 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
641 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
642 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
643 setOperationAction(ISD::SRL, MVT::i64, Custom);
644 setOperationAction(ISD::SRA, MVT::i64, Custom);
646 if (!Subtarget->isThumb1Only()) {
647 // FIXME: We should do this for Thumb1 as well.
648 setOperationAction(ISD::ADDC, MVT::i32, Custom);
649 setOperationAction(ISD::ADDE, MVT::i32, Custom);
650 setOperationAction(ISD::SUBC, MVT::i32, Custom);
651 setOperationAction(ISD::SUBE, MVT::i32, Custom);
654 // ARM does not have ROTL.
655 setOperationAction(ISD::ROTL, MVT::i32, Expand);
656 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
657 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
658 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
659 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
661 // These just redirect to CTTZ and CTLZ on ARM.
662 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
663 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
665 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
667 // Only ARMv6 has BSWAP.
668 if (!Subtarget->hasV6Ops())
669 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
671 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
672 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
673 // These are expanded into libcalls if the cpu doesn't have HW divider.
674 setOperationAction(ISD::SDIV, MVT::i32, Expand);
675 setOperationAction(ISD::UDIV, MVT::i32, Expand);
678 // FIXME: Also set divmod for SREM on EABI
679 setOperationAction(ISD::SREM, MVT::i32, Expand);
680 setOperationAction(ISD::UREM, MVT::i32, Expand);
681 // Register based DivRem for AEABI (RTABI 4.2)
682 if (Subtarget->isTargetAEABI()) {
683 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
684 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
685 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
686 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
687 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
688 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
689 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
690 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
692 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
693 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
694 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
695 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
696 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
697 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
698 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
699 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
701 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
702 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
704 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
705 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
708 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
709 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
710 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
711 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
712 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
714 setOperationAction(ISD::TRAP, MVT::Other, Legal);
716 // Use the default implementation.
717 setOperationAction(ISD::VASTART, MVT::Other, Custom);
718 setOperationAction(ISD::VAARG, MVT::Other, Expand);
719 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
720 setOperationAction(ISD::VAEND, MVT::Other, Expand);
721 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
722 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
724 if (!Subtarget->isTargetMachO()) {
725 // Non-MachO platforms may return values in these registers via the
726 // personality function.
727 setExceptionPointerRegister(ARM::R0);
728 setExceptionSelectorRegister(ARM::R1);
731 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
732 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
734 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
736 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
737 // the default expansion.
738 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
739 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
740 // to ldrex/strex loops already.
741 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
743 // On v8, we have particularly efficient implementations of atomic fences
744 // if they can be combined with nearby atomic loads and stores.
745 if (!Subtarget->hasV8Ops()) {
746 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
747 setInsertFencesForAtomic(true);
750 // If there's anything we can use as a barrier, go through custom lowering
752 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
753 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
755 // Set them all for expansion, which will force libcalls.
756 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
757 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
758 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
759 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
760 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
761 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
762 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
763 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
764 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
765 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
766 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
767 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
768 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
769 // Unordered/Monotonic case.
770 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
771 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
774 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
776 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
777 if (!Subtarget->hasV6Ops()) {
778 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
779 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
781 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
783 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
784 !Subtarget->isThumb1Only()) {
785 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
786 // iff target supports vfp2.
787 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
788 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
791 // We want to custom lower some of our intrinsics.
792 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
793 if (Subtarget->isTargetDarwin()) {
794 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
795 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
796 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
799 setOperationAction(ISD::SETCC, MVT::i32, Expand);
800 setOperationAction(ISD::SETCC, MVT::f32, Expand);
801 setOperationAction(ISD::SETCC, MVT::f64, Expand);
802 setOperationAction(ISD::SELECT, MVT::i32, Custom);
803 setOperationAction(ISD::SELECT, MVT::f32, Custom);
804 setOperationAction(ISD::SELECT, MVT::f64, Custom);
805 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
806 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
807 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
809 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
810 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
811 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
812 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
813 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
815 // We don't support sin/cos/fmod/copysign/pow
816 setOperationAction(ISD::FSIN, MVT::f64, Expand);
817 setOperationAction(ISD::FSIN, MVT::f32, Expand);
818 setOperationAction(ISD::FCOS, MVT::f32, Expand);
819 setOperationAction(ISD::FCOS, MVT::f64, Expand);
820 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
821 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
822 setOperationAction(ISD::FREM, MVT::f64, Expand);
823 setOperationAction(ISD::FREM, MVT::f32, Expand);
824 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
825 !Subtarget->isThumb1Only()) {
826 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
827 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
829 setOperationAction(ISD::FPOW, MVT::f64, Expand);
830 setOperationAction(ISD::FPOW, MVT::f32, Expand);
832 if (!Subtarget->hasVFP4()) {
833 setOperationAction(ISD::FMA, MVT::f64, Expand);
834 setOperationAction(ISD::FMA, MVT::f32, Expand);
837 // Various VFP goodness
838 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
839 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
840 if (Subtarget->hasVFP2()) {
841 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
842 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
843 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
844 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
847 // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
848 if (!Subtarget->hasV8Ops()) {
849 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
850 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
853 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
854 if (!Subtarget->hasFP16()) {
855 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
856 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
860 // Combine sin / cos into one node or libcall if possible.
861 if (Subtarget->hasSinCos()) {
862 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
863 setLibcallName(RTLIB::SINCOS_F64, "sincos");
864 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
865 // For iOS, we don't want to the normal expansion of a libcall to
866 // sincos. We want to issue a libcall to __sincos_stret.
867 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
868 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
872 // We have target-specific dag combine patterns for the following nodes:
873 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
874 setTargetDAGCombine(ISD::ADD);
875 setTargetDAGCombine(ISD::SUB);
876 setTargetDAGCombine(ISD::MUL);
877 setTargetDAGCombine(ISD::AND);
878 setTargetDAGCombine(ISD::OR);
879 setTargetDAGCombine(ISD::XOR);
881 if (Subtarget->hasV6Ops())
882 setTargetDAGCombine(ISD::SRL);
884 setStackPointerRegisterToSaveRestore(ARM::SP);
886 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
887 !Subtarget->hasVFP2())
888 setSchedulingPreference(Sched::RegPressure);
890 setSchedulingPreference(Sched::Hybrid);
892 //// temporary - rewrite interface to use type
893 MaxStoresPerMemset = 8;
894 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
895 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
896 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
897 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
898 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
900 // On ARM arguments smaller than 4 bytes are extended, so all arguments
901 // are at least 4 bytes aligned.
902 setMinStackArgumentAlignment(4);
904 // Prefer likely predicted branches to selects on out-of-order cores.
905 PredictableSelectIsExpensive = Subtarget->isLikeA9();
907 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
910 // FIXME: It might make sense to define the representative register class as the
911 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
912 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
913 // SPR's representative would be DPR_VFP2. This should work well if register
914 // pressure tracking were modified such that a register use would increment the
915 // pressure of the register class's representative and all of it's super
916 // classes' representatives transitively. We have not implemented this because
917 // of the difficulty prior to coalescing of modeling operand register classes
918 // due to the common occurrence of cross class copies and subregister insertions
920 std::pair<const TargetRegisterClass*, uint8_t>
921 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
922 const TargetRegisterClass *RRC = nullptr;
924 switch (VT.SimpleTy) {
926 return TargetLowering::findRepresentativeClass(VT);
927 // Use DPR as representative register class for all floating point
928 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
929 // the cost is 1 for both f32 and f64.
930 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
931 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
932 RRC = &ARM::DPRRegClass;
933 // When NEON is used for SP, only half of the register file is available
934 // because operations that define both SP and DP results will be constrained
935 // to the VFP2 class (D0-D15). We currently model this constraint prior to
936 // coalescing by double-counting the SP regs. See the FIXME above.
937 if (Subtarget->useNEONForSinglePrecisionFP())
940 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
941 case MVT::v4f32: case MVT::v2f64:
942 RRC = &ARM::DPRRegClass;
946 RRC = &ARM::DPRRegClass;
950 RRC = &ARM::DPRRegClass;
954 return std::make_pair(RRC, Cost);
957 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
959 default: return nullptr;
960 case ARMISD::Wrapper: return "ARMISD::Wrapper";
961 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
962 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
963 case ARMISD::CALL: return "ARMISD::CALL";
964 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
965 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
966 case ARMISD::tCALL: return "ARMISD::tCALL";
967 case ARMISD::BRCOND: return "ARMISD::BRCOND";
968 case ARMISD::BR_JT: return "ARMISD::BR_JT";
969 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
970 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
971 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
972 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
973 case ARMISD::CMP: return "ARMISD::CMP";
974 case ARMISD::CMN: return "ARMISD::CMN";
975 case ARMISD::CMPZ: return "ARMISD::CMPZ";
976 case ARMISD::CMPFP: return "ARMISD::CMPFP";
977 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
978 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
979 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
981 case ARMISD::CMOV: return "ARMISD::CMOV";
983 case ARMISD::RBIT: return "ARMISD::RBIT";
985 case ARMISD::FTOSI: return "ARMISD::FTOSI";
986 case ARMISD::FTOUI: return "ARMISD::FTOUI";
987 case ARMISD::SITOF: return "ARMISD::SITOF";
988 case ARMISD::UITOF: return "ARMISD::UITOF";
990 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
991 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
992 case ARMISD::RRX: return "ARMISD::RRX";
994 case ARMISD::ADDC: return "ARMISD::ADDC";
995 case ARMISD::ADDE: return "ARMISD::ADDE";
996 case ARMISD::SUBC: return "ARMISD::SUBC";
997 case ARMISD::SUBE: return "ARMISD::SUBE";
999 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1000 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1002 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1003 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1005 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1007 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1009 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1011 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1013 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1015 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1017 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1018 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1019 case ARMISD::VCGE: return "ARMISD::VCGE";
1020 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1021 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1022 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1023 case ARMISD::VCGT: return "ARMISD::VCGT";
1024 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1025 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1026 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1027 case ARMISD::VTST: return "ARMISD::VTST";
1029 case ARMISD::VSHL: return "ARMISD::VSHL";
1030 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1031 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1032 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1033 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1034 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1035 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1036 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1037 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1038 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1039 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1040 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1041 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1042 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1043 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1044 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1045 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1046 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1047 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1048 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1049 case ARMISD::VDUP: return "ARMISD::VDUP";
1050 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1051 case ARMISD::VEXT: return "ARMISD::VEXT";
1052 case ARMISD::VREV64: return "ARMISD::VREV64";
1053 case ARMISD::VREV32: return "ARMISD::VREV32";
1054 case ARMISD::VREV16: return "ARMISD::VREV16";
1055 case ARMISD::VZIP: return "ARMISD::VZIP";
1056 case ARMISD::VUZP: return "ARMISD::VUZP";
1057 case ARMISD::VTRN: return "ARMISD::VTRN";
1058 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1059 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1060 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1061 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1062 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1063 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1064 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1065 case ARMISD::FMAX: return "ARMISD::FMAX";
1066 case ARMISD::FMIN: return "ARMISD::FMIN";
1067 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1068 case ARMISD::VMINNM: return "ARMISD::VMIN";
1069 case ARMISD::BFI: return "ARMISD::BFI";
1070 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1071 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1072 case ARMISD::VBSL: return "ARMISD::VBSL";
1073 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1074 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1075 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1076 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1077 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1078 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1079 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1080 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1081 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1082 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1083 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1084 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1085 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1086 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1087 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1088 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1089 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1090 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1091 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1092 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1096 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1097 if (!VT.isVector()) return getPointerTy();
1098 return VT.changeVectorElementTypeToInteger();
1101 /// getRegClassFor - Return the register class that should be used for the
1102 /// specified value type.
1103 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1104 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1105 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1106 // load / store 4 to 8 consecutive D registers.
1107 if (Subtarget->hasNEON()) {
1108 if (VT == MVT::v4i64)
1109 return &ARM::QQPRRegClass;
1110 if (VT == MVT::v8i64)
1111 return &ARM::QQQQPRRegClass;
1113 return TargetLowering::getRegClassFor(VT);
1116 // Create a fast isel object.
1118 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1119 const TargetLibraryInfo *libInfo) const {
1120 return ARM::createFastISel(funcInfo, libInfo);
1123 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1124 /// be used for loads / stores from the global.
1125 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1126 return (Subtarget->isThumb1Only() ? 127 : 4095);
1129 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1130 unsigned NumVals = N->getNumValues();
1132 return Sched::RegPressure;
1134 for (unsigned i = 0; i != NumVals; ++i) {
1135 EVT VT = N->getValueType(i);
1136 if (VT == MVT::Glue || VT == MVT::Other)
1138 if (VT.isFloatingPoint() || VT.isVector())
1142 if (!N->isMachineOpcode())
1143 return Sched::RegPressure;
1145 // Load are scheduled for latency even if there instruction itinerary
1146 // is not available.
1147 const TargetInstrInfo *TII =
1148 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1149 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1151 if (MCID.getNumDefs() == 0)
1152 return Sched::RegPressure;
1153 if (!Itins->isEmpty() &&
1154 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1157 return Sched::RegPressure;
1160 //===----------------------------------------------------------------------===//
1162 //===----------------------------------------------------------------------===//
1164 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1165 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1167 default: llvm_unreachable("Unknown condition code!");
1168 case ISD::SETNE: return ARMCC::NE;
1169 case ISD::SETEQ: return ARMCC::EQ;
1170 case ISD::SETGT: return ARMCC::GT;
1171 case ISD::SETGE: return ARMCC::GE;
1172 case ISD::SETLT: return ARMCC::LT;
1173 case ISD::SETLE: return ARMCC::LE;
1174 case ISD::SETUGT: return ARMCC::HI;
1175 case ISD::SETUGE: return ARMCC::HS;
1176 case ISD::SETULT: return ARMCC::LO;
1177 case ISD::SETULE: return ARMCC::LS;
1181 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1182 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1183 ARMCC::CondCodes &CondCode2) {
1184 CondCode2 = ARMCC::AL;
1186 default: llvm_unreachable("Unknown FP condition!");
1188 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1190 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1192 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1193 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1194 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1195 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1196 case ISD::SETO: CondCode = ARMCC::VC; break;
1197 case ISD::SETUO: CondCode = ARMCC::VS; break;
1198 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1199 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1200 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1202 case ISD::SETULT: CondCode = ARMCC::LT; break;
1204 case ISD::SETULE: CondCode = ARMCC::LE; break;
1206 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1210 //===----------------------------------------------------------------------===//
1211 // Calling Convention Implementation
1212 //===----------------------------------------------------------------------===//
1214 #include "ARMGenCallingConv.inc"
1216 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1217 /// account presence of floating point hardware and calling convention
1218 /// limitations, such as support for variadic functions.
1220 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1221 bool isVarArg) const {
1224 llvm_unreachable("Unsupported calling convention");
1225 case CallingConv::ARM_AAPCS:
1226 case CallingConv::ARM_APCS:
1227 case CallingConv::GHC:
1229 case CallingConv::ARM_AAPCS_VFP:
1230 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1231 case CallingConv::C:
1232 if (!Subtarget->isAAPCS_ABI())
1233 return CallingConv::ARM_APCS;
1234 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1235 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1237 return CallingConv::ARM_AAPCS_VFP;
1239 return CallingConv::ARM_AAPCS;
1240 case CallingConv::Fast:
1241 if (!Subtarget->isAAPCS_ABI()) {
1242 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1243 return CallingConv::Fast;
1244 return CallingConv::ARM_APCS;
1245 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1246 return CallingConv::ARM_AAPCS_VFP;
1248 return CallingConv::ARM_AAPCS;
1252 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1253 /// CallingConvention.
1254 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1256 bool isVarArg) const {
1257 switch (getEffectiveCallingConv(CC, isVarArg)) {
1259 llvm_unreachable("Unsupported calling convention");
1260 case CallingConv::ARM_APCS:
1261 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1262 case CallingConv::ARM_AAPCS:
1263 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1264 case CallingConv::ARM_AAPCS_VFP:
1265 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1266 case CallingConv::Fast:
1267 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1268 case CallingConv::GHC:
1269 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1273 /// LowerCallResult - Lower the result values of a call into the
1274 /// appropriate copies out of appropriate physical registers.
1276 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1277 CallingConv::ID CallConv, bool isVarArg,
1278 const SmallVectorImpl<ISD::InputArg> &Ins,
1279 SDLoc dl, SelectionDAG &DAG,
1280 SmallVectorImpl<SDValue> &InVals,
1281 bool isThisReturn, SDValue ThisVal) const {
1283 // Assign locations to each value returned by this call.
1284 SmallVector<CCValAssign, 16> RVLocs;
1285 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1286 *DAG.getContext(), Call);
1287 CCInfo.AnalyzeCallResult(Ins,
1288 CCAssignFnForNode(CallConv, /* Return*/ true,
1291 // Copy all of the result registers out of their specified physreg.
1292 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1293 CCValAssign VA = RVLocs[i];
1295 // Pass 'this' value directly from the argument to return value, to avoid
1296 // reg unit interference
1297 if (i == 0 && isThisReturn) {
1298 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1299 "unexpected return calling convention register assignment");
1300 InVals.push_back(ThisVal);
1305 if (VA.needsCustom()) {
1306 // Handle f64 or half of a v2f64.
1307 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1309 Chain = Lo.getValue(1);
1310 InFlag = Lo.getValue(2);
1311 VA = RVLocs[++i]; // skip ahead to next loc
1312 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1314 Chain = Hi.getValue(1);
1315 InFlag = Hi.getValue(2);
1316 if (!Subtarget->isLittle())
1318 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1320 if (VA.getLocVT() == MVT::v2f64) {
1321 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1322 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1323 DAG.getConstant(0, MVT::i32));
1325 VA = RVLocs[++i]; // skip ahead to next loc
1326 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1327 Chain = Lo.getValue(1);
1328 InFlag = Lo.getValue(2);
1329 VA = RVLocs[++i]; // skip ahead to next loc
1330 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1331 Chain = Hi.getValue(1);
1332 InFlag = Hi.getValue(2);
1333 if (!Subtarget->isLittle())
1335 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1336 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1337 DAG.getConstant(1, MVT::i32));
1340 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1342 Chain = Val.getValue(1);
1343 InFlag = Val.getValue(2);
1346 switch (VA.getLocInfo()) {
1347 default: llvm_unreachable("Unknown loc info!");
1348 case CCValAssign::Full: break;
1349 case CCValAssign::BCvt:
1350 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1354 InVals.push_back(Val);
1360 /// LowerMemOpCallTo - Store the argument to the stack.
1362 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1363 SDValue StackPtr, SDValue Arg,
1364 SDLoc dl, SelectionDAG &DAG,
1365 const CCValAssign &VA,
1366 ISD::ArgFlagsTy Flags) const {
1367 unsigned LocMemOffset = VA.getLocMemOffset();
1368 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1369 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1370 return DAG.getStore(Chain, dl, Arg, PtrOff,
1371 MachinePointerInfo::getStack(LocMemOffset),
1375 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1376 SDValue Chain, SDValue &Arg,
1377 RegsToPassVector &RegsToPass,
1378 CCValAssign &VA, CCValAssign &NextVA,
1380 SmallVectorImpl<SDValue> &MemOpChains,
1381 ISD::ArgFlagsTy Flags) const {
1383 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1384 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1385 unsigned id = Subtarget->isLittle() ? 0 : 1;
1386 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1388 if (NextVA.isRegLoc())
1389 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1391 assert(NextVA.isMemLoc());
1392 if (!StackPtr.getNode())
1393 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1395 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1401 /// LowerCall - Lowering a call into a callseq_start <-
1402 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1405 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1406 SmallVectorImpl<SDValue> &InVals) const {
1407 SelectionDAG &DAG = CLI.DAG;
1409 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1410 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1411 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1412 SDValue Chain = CLI.Chain;
1413 SDValue Callee = CLI.Callee;
1414 bool &isTailCall = CLI.IsTailCall;
1415 CallingConv::ID CallConv = CLI.CallConv;
1416 bool doesNotRet = CLI.DoesNotReturn;
1417 bool isVarArg = CLI.IsVarArg;
1419 MachineFunction &MF = DAG.getMachineFunction();
1420 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1421 bool isThisReturn = false;
1422 bool isSibCall = false;
1424 // Disable tail calls if they're not supported.
1425 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1429 // Check if it's really possible to do a tail call.
1430 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1431 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1432 Outs, OutVals, Ins, DAG);
1433 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1434 report_fatal_error("failed to perform tail call elimination on a call "
1435 "site marked musttail");
1436 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1437 // detected sibcalls.
1444 // Analyze operands of the call, assigning locations to each operand.
1445 SmallVector<CCValAssign, 16> ArgLocs;
1446 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1447 *DAG.getContext(), Call);
1448 CCInfo.AnalyzeCallOperands(Outs,
1449 CCAssignFnForNode(CallConv, /* Return*/ false,
1452 // Get a count of how many bytes are to be pushed on the stack.
1453 unsigned NumBytes = CCInfo.getNextStackOffset();
1455 // For tail calls, memory operands are available in our caller's stack.
1459 // Adjust the stack pointer for the new arguments...
1460 // These operations are automatically eliminated by the prolog/epilog pass
1462 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1465 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1467 RegsToPassVector RegsToPass;
1468 SmallVector<SDValue, 8> MemOpChains;
1470 // Walk the register/memloc assignments, inserting copies/loads. In the case
1471 // of tail call optimization, arguments are handled later.
1472 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1474 ++i, ++realArgIdx) {
1475 CCValAssign &VA = ArgLocs[i];
1476 SDValue Arg = OutVals[realArgIdx];
1477 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1478 bool isByVal = Flags.isByVal();
1480 // Promote the value if needed.
1481 switch (VA.getLocInfo()) {
1482 default: llvm_unreachable("Unknown loc info!");
1483 case CCValAssign::Full: break;
1484 case CCValAssign::SExt:
1485 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1487 case CCValAssign::ZExt:
1488 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1490 case CCValAssign::AExt:
1491 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1493 case CCValAssign::BCvt:
1494 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1498 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1499 if (VA.needsCustom()) {
1500 if (VA.getLocVT() == MVT::v2f64) {
1501 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1502 DAG.getConstant(0, MVT::i32));
1503 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1504 DAG.getConstant(1, MVT::i32));
1506 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1507 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1509 VA = ArgLocs[++i]; // skip ahead to next loc
1510 if (VA.isRegLoc()) {
1511 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1512 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1514 assert(VA.isMemLoc());
1516 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1517 dl, DAG, VA, Flags));
1520 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1521 StackPtr, MemOpChains, Flags);
1523 } else if (VA.isRegLoc()) {
1524 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1525 assert(VA.getLocVT() == MVT::i32 &&
1526 "unexpected calling convention register assignment");
1527 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1528 "unexpected use of 'returned'");
1529 isThisReturn = true;
1531 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1532 } else if (isByVal) {
1533 assert(VA.isMemLoc());
1534 unsigned offset = 0;
1536 // True if this byval aggregate will be split between registers
1538 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1539 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1541 if (CurByValIdx < ByValArgsCount) {
1543 unsigned RegBegin, RegEnd;
1544 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1546 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1548 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1549 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1550 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1551 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1552 MachinePointerInfo(),
1553 false, false, false,
1554 DAG.InferPtrAlignment(AddArg));
1555 MemOpChains.push_back(Load.getValue(1));
1556 RegsToPass.push_back(std::make_pair(j, Load));
1559 // If parameter size outsides register area, "offset" value
1560 // helps us to calculate stack slot for remained part properly.
1561 offset = RegEnd - RegBegin;
1563 CCInfo.nextInRegsParam();
1566 if (Flags.getByValSize() > 4*offset) {
1567 unsigned LocMemOffset = VA.getLocMemOffset();
1568 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1569 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1571 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1572 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1573 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1575 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1577 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1578 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1579 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1582 } else if (!isSibCall) {
1583 assert(VA.isMemLoc());
1585 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1586 dl, DAG, VA, Flags));
1590 if (!MemOpChains.empty())
1591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1593 // Build a sequence of copy-to-reg nodes chained together with token chain
1594 // and flag operands which copy the outgoing args into the appropriate regs.
1596 // Tail call byval lowering might overwrite argument registers so in case of
1597 // tail call optimization the copies to registers are lowered later.
1599 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1600 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1601 RegsToPass[i].second, InFlag);
1602 InFlag = Chain.getValue(1);
1605 // For tail calls lower the arguments to the 'real' stack slot.
1607 // Force all the incoming stack arguments to be loaded from the stack
1608 // before any new outgoing arguments are stored to the stack, because the
1609 // outgoing stack slots may alias the incoming argument stack slots, and
1610 // the alias isn't otherwise explicit. This is slightly more conservative
1611 // than necessary, because it means that each store effectively depends
1612 // on every argument instead of just those arguments it would clobber.
1614 // Do not flag preceding copytoreg stuff together with the following stuff.
1616 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1617 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1618 RegsToPass[i].second, InFlag);
1619 InFlag = Chain.getValue(1);
1624 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1625 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1626 // node so that legalize doesn't hack it.
1627 bool isDirect = false;
1628 bool isARMFunc = false;
1629 bool isLocalARMFunc = false;
1630 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1632 if (EnableARMLongCalls) {
1633 assert((Subtarget->isTargetWindows() ||
1634 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1635 "long-calls with non-static relocation model!");
1636 // Handle a global address or an external symbol. If it's not one of
1637 // those, the target's already in a register, so we don't need to do
1639 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1640 const GlobalValue *GV = G->getGlobal();
1641 // Create a constant pool entry for the callee address
1642 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1643 ARMConstantPoolValue *CPV =
1644 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1646 // Get the address of the callee into a register
1647 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1648 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1649 Callee = DAG.getLoad(getPointerTy(), dl,
1650 DAG.getEntryNode(), CPAddr,
1651 MachinePointerInfo::getConstantPool(),
1652 false, false, false, 0);
1653 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1654 const char *Sym = S->getSymbol();
1656 // Create a constant pool entry for the callee address
1657 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1658 ARMConstantPoolValue *CPV =
1659 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1660 ARMPCLabelIndex, 0);
1661 // Get the address of the callee into a register
1662 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1663 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1664 Callee = DAG.getLoad(getPointerTy(), dl,
1665 DAG.getEntryNode(), CPAddr,
1666 MachinePointerInfo::getConstantPool(),
1667 false, false, false, 0);
1669 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1670 const GlobalValue *GV = G->getGlobal();
1672 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1673 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1674 getTargetMachine().getRelocationModel() != Reloc::Static;
1675 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1676 // ARM call to a local ARM function is predicable.
1677 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1678 // tBX takes a register source operand.
1679 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1680 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1681 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1682 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1683 0, ARMII::MO_NONLAZY));
1684 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1685 MachinePointerInfo::getGOT(), false, false, true, 0);
1686 } else if (Subtarget->isTargetCOFF()) {
1687 assert(Subtarget->isTargetWindows() &&
1688 "Windows is the only supported COFF target");
1689 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1690 ? ARMII::MO_DLLIMPORT
1691 : ARMII::MO_NO_FLAG;
1692 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1694 if (GV->hasDLLImportStorageClass())
1695 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1696 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1697 Callee), MachinePointerInfo::getGOT(),
1698 false, false, false, 0);
1700 // On ELF targets for PIC code, direct calls should go through the PLT
1701 unsigned OpFlags = 0;
1702 if (Subtarget->isTargetELF() &&
1703 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1704 OpFlags = ARMII::MO_PLT;
1705 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1707 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1709 bool isStub = Subtarget->isTargetMachO() &&
1710 getTargetMachine().getRelocationModel() != Reloc::Static;
1711 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1712 // tBX takes a register source operand.
1713 const char *Sym = S->getSymbol();
1714 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1715 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1716 ARMConstantPoolValue *CPV =
1717 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1718 ARMPCLabelIndex, 4);
1719 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1720 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1721 Callee = DAG.getLoad(getPointerTy(), dl,
1722 DAG.getEntryNode(), CPAddr,
1723 MachinePointerInfo::getConstantPool(),
1724 false, false, false, 0);
1725 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1726 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1727 getPointerTy(), Callee, PICLabel);
1729 unsigned OpFlags = 0;
1730 // On ELF targets for PIC code, direct calls should go through the PLT
1731 if (Subtarget->isTargetELF() &&
1732 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1733 OpFlags = ARMII::MO_PLT;
1734 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1738 // FIXME: handle tail calls differently.
1740 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1741 AttributeSet::FunctionIndex, Attribute::MinSize);
1742 if (Subtarget->isThumb()) {
1743 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1744 CallOpc = ARMISD::CALL_NOLINK;
1746 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1748 if (!isDirect && !Subtarget->hasV5TOps())
1749 CallOpc = ARMISD::CALL_NOLINK;
1750 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1751 // Emit regular call when code size is the priority
1753 // "mov lr, pc; b _foo" to avoid confusing the RSP
1754 CallOpc = ARMISD::CALL_NOLINK;
1756 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1759 std::vector<SDValue> Ops;
1760 Ops.push_back(Chain);
1761 Ops.push_back(Callee);
1763 // Add argument registers to the end of the list so that they are known live
1765 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1766 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1767 RegsToPass[i].second.getValueType()));
1769 // Add a register mask operand representing the call-preserved registers.
1771 const uint32_t *Mask;
1772 const TargetRegisterInfo *TRI =
1773 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1774 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1776 // For 'this' returns, use the R0-preserving mask if applicable
1777 Mask = ARI->getThisReturnPreservedMask(CallConv);
1779 // Set isThisReturn to false if the calling convention is not one that
1780 // allows 'returned' to be modeled in this way, so LowerCallResult does
1781 // not try to pass 'this' straight through
1782 isThisReturn = false;
1783 Mask = ARI->getCallPreservedMask(CallConv);
1786 Mask = ARI->getCallPreservedMask(CallConv);
1788 assert(Mask && "Missing call preserved mask for calling convention");
1789 Ops.push_back(DAG.getRegisterMask(Mask));
1792 if (InFlag.getNode())
1793 Ops.push_back(InFlag);
1795 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1797 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1799 // Returns a chain and a flag for retval copy to use.
1800 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1801 InFlag = Chain.getValue(1);
1803 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1804 DAG.getIntPtrConstant(0, true), InFlag, dl);
1806 InFlag = Chain.getValue(1);
1808 // Handle result values, copying them out of physregs into vregs that we
1810 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1811 InVals, isThisReturn,
1812 isThisReturn ? OutVals[0] : SDValue());
1815 /// HandleByVal - Every parameter *after* a byval parameter is passed
1816 /// on the stack. Remember the next parameter register to allocate,
1817 /// and then confiscate the rest of the parameter registers to insure
1820 ARMTargetLowering::HandleByVal(
1821 CCState *State, unsigned &size, unsigned Align) const {
1822 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1823 assert((State->getCallOrPrologue() == Prologue ||
1824 State->getCallOrPrologue() == Call) &&
1825 "unhandled ParmContext");
1827 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1828 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1829 unsigned AlignInRegs = Align / 4;
1830 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1831 for (unsigned i = 0; i < Waste; ++i)
1832 reg = State->AllocateReg(GPRArgRegs, 4);
1835 unsigned excess = 4 * (ARM::R4 - reg);
1837 // Special case when NSAA != SP and parameter size greater than size of
1838 // all remained GPR regs. In that case we can't split parameter, we must
1839 // send it to stack. We also must set NCRN to R4, so waste all
1840 // remained registers.
1841 const unsigned NSAAOffset = State->getNextStackOffset();
1842 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1843 while (State->AllocateReg(GPRArgRegs, 4))
1848 // First register for byval parameter is the first register that wasn't
1849 // allocated before this method call, so it would be "reg".
1850 // If parameter is small enough to be saved in range [reg, r4), then
1851 // the end (first after last) register would be reg + param-size-in-regs,
1852 // else parameter would be splitted between registers and stack,
1853 // end register would be r4 in this case.
1854 unsigned ByValRegBegin = reg;
1855 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1856 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1857 // Note, first register is allocated in the beginning of function already,
1858 // allocate remained amount of registers we need.
1859 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1860 State->AllocateReg(GPRArgRegs, 4);
1861 // A byval parameter that is split between registers and memory needs its
1862 // size truncated here.
1863 // In the case where the entire structure fits in registers, we set the
1864 // size in memory to zero.
1873 /// MatchingStackOffset - Return true if the given stack call argument is
1874 /// already available in the same position (relatively) of the caller's
1875 /// incoming argument stack.
1877 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1878 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1879 const TargetInstrInfo *TII) {
1880 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1882 if (Arg.getOpcode() == ISD::CopyFromReg) {
1883 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1884 if (!TargetRegisterInfo::isVirtualRegister(VR))
1886 MachineInstr *Def = MRI->getVRegDef(VR);
1889 if (!Flags.isByVal()) {
1890 if (!TII->isLoadFromStackSlot(Def, FI))
1895 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1896 if (Flags.isByVal())
1897 // ByVal argument is passed in as a pointer but it's now being
1898 // dereferenced. e.g.
1899 // define @foo(%struct.X* %A) {
1900 // tail call @bar(%struct.X* byval %A)
1903 SDValue Ptr = Ld->getBasePtr();
1904 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1907 FI = FINode->getIndex();
1911 assert(FI != INT_MAX);
1912 if (!MFI->isFixedObjectIndex(FI))
1914 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1917 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1918 /// for tail call optimization. Targets which want to do tail call
1919 /// optimization should implement this function.
1921 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1922 CallingConv::ID CalleeCC,
1924 bool isCalleeStructRet,
1925 bool isCallerStructRet,
1926 const SmallVectorImpl<ISD::OutputArg> &Outs,
1927 const SmallVectorImpl<SDValue> &OutVals,
1928 const SmallVectorImpl<ISD::InputArg> &Ins,
1929 SelectionDAG& DAG) const {
1930 const Function *CallerF = DAG.getMachineFunction().getFunction();
1931 CallingConv::ID CallerCC = CallerF->getCallingConv();
1932 bool CCMatch = CallerCC == CalleeCC;
1934 // Look for obvious safe cases to perform tail call optimization that do not
1935 // require ABI changes. This is what gcc calls sibcall.
1937 // Do not sibcall optimize vararg calls unless the call site is not passing
1939 if (isVarArg && !Outs.empty())
1942 // Exception-handling functions need a special set of instructions to indicate
1943 // a return to the hardware. Tail-calling another function would probably
1945 if (CallerF->hasFnAttribute("interrupt"))
1948 // Also avoid sibcall optimization if either caller or callee uses struct
1949 // return semantics.
1950 if (isCalleeStructRet || isCallerStructRet)
1953 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1954 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1955 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1956 // support in the assembler and linker to be used. This would need to be
1957 // fixed to fully support tail calls in Thumb1.
1959 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1960 // LR. This means if we need to reload LR, it takes an extra instructions,
1961 // which outweighs the value of the tail call; but here we don't know yet
1962 // whether LR is going to be used. Probably the right approach is to
1963 // generate the tail call here and turn it back into CALL/RET in
1964 // emitEpilogue if LR is used.
1966 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1967 // but we need to make sure there are enough registers; the only valid
1968 // registers are the 4 used for parameters. We don't currently do this
1970 if (Subtarget->isThumb1Only())
1973 // If the calling conventions do not match, then we'd better make sure the
1974 // results are returned in the same way as what the caller expects.
1976 SmallVector<CCValAssign, 16> RVLocs1;
1977 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
1978 *DAG.getContext(), Call);
1979 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1981 SmallVector<CCValAssign, 16> RVLocs2;
1982 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
1983 *DAG.getContext(), Call);
1984 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1986 if (RVLocs1.size() != RVLocs2.size())
1988 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1989 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1991 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1993 if (RVLocs1[i].isRegLoc()) {
1994 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1997 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2003 // If Caller's vararg or byval argument has been split between registers and
2004 // stack, do not perform tail call, since part of the argument is in caller's
2006 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2007 getInfo<ARMFunctionInfo>();
2008 if (AFI_Caller->getArgRegsSaveSize())
2011 // If the callee takes no arguments then go on to check the results of the
2013 if (!Outs.empty()) {
2014 // Check if stack adjustment is needed. For now, do not do this if any
2015 // argument is passed on the stack.
2016 SmallVector<CCValAssign, 16> ArgLocs;
2017 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2018 *DAG.getContext(), Call);
2019 CCInfo.AnalyzeCallOperands(Outs,
2020 CCAssignFnForNode(CalleeCC, false, isVarArg));
2021 if (CCInfo.getNextStackOffset()) {
2022 MachineFunction &MF = DAG.getMachineFunction();
2024 // Check if the arguments are already laid out in the right way as
2025 // the caller's fixed stack objects.
2026 MachineFrameInfo *MFI = MF.getFrameInfo();
2027 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2028 const TargetInstrInfo *TII =
2029 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2030 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2032 ++i, ++realArgIdx) {
2033 CCValAssign &VA = ArgLocs[i];
2034 EVT RegVT = VA.getLocVT();
2035 SDValue Arg = OutVals[realArgIdx];
2036 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2037 if (VA.getLocInfo() == CCValAssign::Indirect)
2039 if (VA.needsCustom()) {
2040 // f64 and vector types are split into multiple registers or
2041 // register/stack-slot combinations. The types will not match
2042 // the registers; give up on memory f64 refs until we figure
2043 // out what to do about this.
2046 if (!ArgLocs[++i].isRegLoc())
2048 if (RegVT == MVT::v2f64) {
2049 if (!ArgLocs[++i].isRegLoc())
2051 if (!ArgLocs[++i].isRegLoc())
2054 } else if (!VA.isRegLoc()) {
2055 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2067 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2068 MachineFunction &MF, bool isVarArg,
2069 const SmallVectorImpl<ISD::OutputArg> &Outs,
2070 LLVMContext &Context) const {
2071 SmallVector<CCValAssign, 16> RVLocs;
2072 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2073 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2077 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2078 SDLoc DL, SelectionDAG &DAG) {
2079 const MachineFunction &MF = DAG.getMachineFunction();
2080 const Function *F = MF.getFunction();
2082 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2084 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2085 // version of the "preferred return address". These offsets affect the return
2086 // instruction if this is a return from PL1 without hypervisor extensions.
2087 // IRQ/FIQ: +4 "subs pc, lr, #4"
2088 // SWI: 0 "subs pc, lr, #0"
2089 // ABORT: +4 "subs pc, lr, #4"
2090 // UNDEF: +4/+2 "subs pc, lr, #0"
2091 // UNDEF varies depending on where the exception came from ARM or Thumb
2092 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2095 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2098 else if (IntKind == "SWI" || IntKind == "UNDEF")
2101 report_fatal_error("Unsupported interrupt attribute. If present, value "
2102 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2104 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2106 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2110 ARMTargetLowering::LowerReturn(SDValue Chain,
2111 CallingConv::ID CallConv, bool isVarArg,
2112 const SmallVectorImpl<ISD::OutputArg> &Outs,
2113 const SmallVectorImpl<SDValue> &OutVals,
2114 SDLoc dl, SelectionDAG &DAG) const {
2116 // CCValAssign - represent the assignment of the return value to a location.
2117 SmallVector<CCValAssign, 16> RVLocs;
2119 // CCState - Info about the registers and stack slots.
2120 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2121 *DAG.getContext(), Call);
2123 // Analyze outgoing return values.
2124 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2128 SmallVector<SDValue, 4> RetOps;
2129 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2130 bool isLittleEndian = Subtarget->isLittle();
2132 MachineFunction &MF = DAG.getMachineFunction();
2133 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2134 AFI->setReturnRegsCount(RVLocs.size());
2136 // Copy the result values into the output registers.
2137 for (unsigned i = 0, realRVLocIdx = 0;
2139 ++i, ++realRVLocIdx) {
2140 CCValAssign &VA = RVLocs[i];
2141 assert(VA.isRegLoc() && "Can only return in registers!");
2143 SDValue Arg = OutVals[realRVLocIdx];
2145 switch (VA.getLocInfo()) {
2146 default: llvm_unreachable("Unknown loc info!");
2147 case CCValAssign::Full: break;
2148 case CCValAssign::BCvt:
2149 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2153 if (VA.needsCustom()) {
2154 if (VA.getLocVT() == MVT::v2f64) {
2155 // Extract the first half and return it in two registers.
2156 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2157 DAG.getConstant(0, MVT::i32));
2158 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2159 DAG.getVTList(MVT::i32, MVT::i32), Half);
2161 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2162 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2164 Flag = Chain.getValue(1);
2165 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2166 VA = RVLocs[++i]; // skip ahead to next loc
2167 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2168 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2170 Flag = Chain.getValue(1);
2171 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2172 VA = RVLocs[++i]; // skip ahead to next loc
2174 // Extract the 2nd half and fall through to handle it as an f64 value.
2175 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2176 DAG.getConstant(1, MVT::i32));
2178 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2180 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2181 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2182 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2183 fmrrd.getValue(isLittleEndian ? 0 : 1),
2185 Flag = Chain.getValue(1);
2186 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2187 VA = RVLocs[++i]; // skip ahead to next loc
2188 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2189 fmrrd.getValue(isLittleEndian ? 1 : 0),
2192 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2194 // Guarantee that all emitted copies are
2195 // stuck together, avoiding something bad.
2196 Flag = Chain.getValue(1);
2197 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2200 // Update chain and glue.
2203 RetOps.push_back(Flag);
2205 // CPUs which aren't M-class use a special sequence to return from
2206 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2207 // though we use "subs pc, lr, #N").
2209 // M-class CPUs actually use a normal return sequence with a special
2210 // (hardware-provided) value in LR, so the normal code path works.
2211 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2212 !Subtarget->isMClass()) {
2213 if (Subtarget->isThumb1Only())
2214 report_fatal_error("interrupt attribute is not supported in Thumb1");
2215 return LowerInterruptReturn(RetOps, dl, DAG);
2218 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2221 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2222 if (N->getNumValues() != 1)
2224 if (!N->hasNUsesOfValue(1, 0))
2227 SDValue TCChain = Chain;
2228 SDNode *Copy = *N->use_begin();
2229 if (Copy->getOpcode() == ISD::CopyToReg) {
2230 // If the copy has a glue operand, we conservatively assume it isn't safe to
2231 // perform a tail call.
2232 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2234 TCChain = Copy->getOperand(0);
2235 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2236 SDNode *VMov = Copy;
2237 // f64 returned in a pair of GPRs.
2238 SmallPtrSet<SDNode*, 2> Copies;
2239 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2241 if (UI->getOpcode() != ISD::CopyToReg)
2245 if (Copies.size() > 2)
2248 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2250 SDValue UseChain = UI->getOperand(0);
2251 if (Copies.count(UseChain.getNode()))
2258 } else if (Copy->getOpcode() == ISD::BITCAST) {
2259 // f32 returned in a single GPR.
2260 if (!Copy->hasOneUse())
2262 Copy = *Copy->use_begin();
2263 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2265 TCChain = Copy->getOperand(0);
2270 bool HasRet = false;
2271 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2273 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2274 UI->getOpcode() != ARMISD::INTRET_FLAG)
2286 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2287 if (!Subtarget->supportsTailCall())
2290 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2293 return !Subtarget->isThumb1Only();
2296 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2297 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2298 // one of the above mentioned nodes. It has to be wrapped because otherwise
2299 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2300 // be used to form addressing mode. These wrapped nodes will be selected
2302 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2303 EVT PtrVT = Op.getValueType();
2304 // FIXME there is no actual debug info here
2306 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2308 if (CP->isMachineConstantPoolEntry())
2309 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2310 CP->getAlignment());
2312 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2313 CP->getAlignment());
2314 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2317 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2318 return MachineJumpTableInfo::EK_Inline;
2321 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2322 SelectionDAG &DAG) const {
2323 MachineFunction &MF = DAG.getMachineFunction();
2324 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2325 unsigned ARMPCLabelIndex = 0;
2327 EVT PtrVT = getPointerTy();
2328 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2329 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2331 if (RelocM == Reloc::Static) {
2332 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2334 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2335 ARMPCLabelIndex = AFI->createPICLabelUId();
2336 ARMConstantPoolValue *CPV =
2337 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2338 ARMCP::CPBlockAddress, PCAdj);
2339 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2341 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2342 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2343 MachinePointerInfo::getConstantPool(),
2344 false, false, false, 0);
2345 if (RelocM == Reloc::Static)
2347 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2348 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2351 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2353 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2354 SelectionDAG &DAG) const {
2356 EVT PtrVT = getPointerTy();
2357 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2358 MachineFunction &MF = DAG.getMachineFunction();
2359 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2360 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2361 ARMConstantPoolValue *CPV =
2362 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2363 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2364 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2365 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2366 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2367 MachinePointerInfo::getConstantPool(),
2368 false, false, false, 0);
2369 SDValue Chain = Argument.getValue(1);
2371 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2372 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2374 // call __tls_get_addr.
2377 Entry.Node = Argument;
2378 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2379 Args.push_back(Entry);
2381 // FIXME: is there useful debug info available here?
2382 TargetLowering::CallLoweringInfo CLI(DAG);
2383 CLI.setDebugLoc(dl).setChain(Chain)
2384 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2385 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2388 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2389 return CallResult.first;
2392 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2393 // "local exec" model.
2395 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2397 TLSModel::Model model) const {
2398 const GlobalValue *GV = GA->getGlobal();
2401 SDValue Chain = DAG.getEntryNode();
2402 EVT PtrVT = getPointerTy();
2403 // Get the Thread Pointer
2404 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2406 if (model == TLSModel::InitialExec) {
2407 MachineFunction &MF = DAG.getMachineFunction();
2408 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2409 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2410 // Initial exec model.
2411 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2412 ARMConstantPoolValue *CPV =
2413 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2414 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2416 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2417 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2418 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2419 MachinePointerInfo::getConstantPool(),
2420 false, false, false, 0);
2421 Chain = Offset.getValue(1);
2423 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2424 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2426 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2427 MachinePointerInfo::getConstantPool(),
2428 false, false, false, 0);
2431 assert(model == TLSModel::LocalExec);
2432 ARMConstantPoolValue *CPV =
2433 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2434 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2436 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2437 MachinePointerInfo::getConstantPool(),
2438 false, false, false, 0);
2441 // The address of the thread local variable is the add of the thread
2442 // pointer with the offset of the variable.
2443 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2447 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2448 // TODO: implement the "local dynamic" model
2449 assert(Subtarget->isTargetELF() &&
2450 "TLS not implemented for non-ELF targets");
2451 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2453 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2456 case TLSModel::GeneralDynamic:
2457 case TLSModel::LocalDynamic:
2458 return LowerToTLSGeneralDynamicModel(GA, DAG);
2459 case TLSModel::InitialExec:
2460 case TLSModel::LocalExec:
2461 return LowerToTLSExecModels(GA, DAG, model);
2463 llvm_unreachable("bogus TLS model");
2466 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2467 SelectionDAG &DAG) const {
2468 EVT PtrVT = getPointerTy();
2470 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2471 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2472 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2473 ARMConstantPoolValue *CPV =
2474 ARMConstantPoolConstant::Create(GV,
2475 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2476 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2477 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2478 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2480 MachinePointerInfo::getConstantPool(),
2481 false, false, false, 0);
2482 SDValue Chain = Result.getValue(1);
2483 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2484 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2486 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2487 MachinePointerInfo::getGOT(),
2488 false, false, false, 0);
2492 // If we have T2 ops, we can materialize the address directly via movt/movw
2493 // pair. This is always cheaper.
2494 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2496 // FIXME: Once remat is capable of dealing with instructions with register
2497 // operands, expand this into two nodes.
2498 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2499 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2501 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2502 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2503 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2504 MachinePointerInfo::getConstantPool(),
2505 false, false, false, 0);
2509 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2510 SelectionDAG &DAG) const {
2511 EVT PtrVT = getPointerTy();
2513 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2514 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2516 if (Subtarget->useMovt(DAG.getMachineFunction()))
2519 // FIXME: Once remat is capable of dealing with instructions with register
2520 // operands, expand this into multiple nodes
2522 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2524 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2525 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2527 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2528 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2529 MachinePointerInfo::getGOT(), false, false, false, 0);
2533 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2534 SelectionDAG &DAG) const {
2535 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2536 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2537 "Windows on ARM expects to use movw/movt");
2539 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2540 const ARMII::TOF TargetFlags =
2541 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2542 EVT PtrVT = getPointerTy();
2548 // FIXME: Once remat is capable of dealing with instructions with register
2549 // operands, expand this into two nodes.
2550 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2551 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2553 if (GV->hasDLLImportStorageClass())
2554 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2555 MachinePointerInfo::getGOT(), false, false, false, 0);
2559 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2560 SelectionDAG &DAG) const {
2561 assert(Subtarget->isTargetELF() &&
2562 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2563 MachineFunction &MF = DAG.getMachineFunction();
2564 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2565 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2566 EVT PtrVT = getPointerTy();
2568 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2569 ARMConstantPoolValue *CPV =
2570 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2571 ARMPCLabelIndex, PCAdj);
2572 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2573 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2574 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2575 MachinePointerInfo::getConstantPool(),
2576 false, false, false, 0);
2577 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2578 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2582 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2584 SDValue Val = DAG.getConstant(0, MVT::i32);
2585 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2586 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2587 Op.getOperand(1), Val);
2591 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2593 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2594 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2598 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2599 const ARMSubtarget *Subtarget) const {
2600 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2603 default: return SDValue(); // Don't custom lower most intrinsics.
2604 case Intrinsic::arm_rbit: {
2605 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2606 "RBIT intrinsic must have i32 type!");
2607 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2609 case Intrinsic::arm_thread_pointer: {
2610 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2611 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2613 case Intrinsic::eh_sjlj_lsda: {
2614 MachineFunction &MF = DAG.getMachineFunction();
2615 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2616 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2617 EVT PtrVT = getPointerTy();
2618 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2620 unsigned PCAdj = (RelocM != Reloc::PIC_)
2621 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2622 ARMConstantPoolValue *CPV =
2623 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2624 ARMCP::CPLSDA, PCAdj);
2625 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2626 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2628 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2629 MachinePointerInfo::getConstantPool(),
2630 false, false, false, 0);
2632 if (RelocM == Reloc::PIC_) {
2633 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2634 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2638 case Intrinsic::arm_neon_vmulls:
2639 case Intrinsic::arm_neon_vmullu: {
2640 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2641 ? ARMISD::VMULLs : ARMISD::VMULLu;
2642 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2643 Op.getOperand(1), Op.getOperand(2));
2648 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2649 const ARMSubtarget *Subtarget) {
2650 // FIXME: handle "fence singlethread" more efficiently.
2652 if (!Subtarget->hasDataBarrier()) {
2653 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2654 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2656 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2657 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2658 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2659 DAG.getConstant(0, MVT::i32));
2662 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2663 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2664 unsigned Domain = ARM_MB::ISH;
2665 if (Subtarget->isMClass()) {
2666 // Only a full system barrier exists in the M-class architectures.
2667 Domain = ARM_MB::SY;
2668 } else if (Subtarget->isSwift() && Ord == Release) {
2669 // Swift happens to implement ISHST barriers in a way that's compatible with
2670 // Release semantics but weaker than ISH so we'd be fools not to use
2671 // it. Beware: other processors probably don't!
2672 Domain = ARM_MB::ISHST;
2675 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2676 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2677 DAG.getConstant(Domain, MVT::i32));
2680 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2681 const ARMSubtarget *Subtarget) {
2682 // ARM pre v5TE and Thumb1 does not have preload instructions.
2683 if (!(Subtarget->isThumb2() ||
2684 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2685 // Just preserve the chain.
2686 return Op.getOperand(0);
2689 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2691 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2692 // ARMv7 with MP extension has PLDW.
2693 return Op.getOperand(0);
2695 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2696 if (Subtarget->isThumb()) {
2698 isRead = ~isRead & 1;
2699 isData = ~isData & 1;
2702 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2703 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2704 DAG.getConstant(isData, MVT::i32));
2707 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2708 MachineFunction &MF = DAG.getMachineFunction();
2709 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2711 // vastart just stores the address of the VarArgsFrameIndex slot into the
2712 // memory location argument.
2714 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2715 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2716 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2717 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2718 MachinePointerInfo(SV), false, false, 0);
2722 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2723 SDValue &Root, SelectionDAG &DAG,
2725 MachineFunction &MF = DAG.getMachineFunction();
2726 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2728 const TargetRegisterClass *RC;
2729 if (AFI->isThumb1OnlyFunction())
2730 RC = &ARM::tGPRRegClass;
2732 RC = &ARM::GPRRegClass;
2734 // Transform the arguments stored in physical registers into virtual ones.
2735 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2736 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2739 if (NextVA.isMemLoc()) {
2740 MachineFrameInfo *MFI = MF.getFrameInfo();
2741 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2743 // Create load node to retrieve arguments from the stack.
2744 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2745 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2746 MachinePointerInfo::getFixedStack(FI),
2747 false, false, false, 0);
2749 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2750 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2752 if (!Subtarget->isLittle())
2753 std::swap (ArgValue, ArgValue2);
2754 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2758 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2759 unsigned InRegsParamRecordIdx,
2761 unsigned &ArgRegsSize,
2762 unsigned &ArgRegsSaveSize)
2765 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2766 unsigned RBegin, REnd;
2767 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2768 NumGPRs = REnd - RBegin;
2770 unsigned int firstUnalloced;
2771 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2772 sizeof(GPRArgRegs) /
2773 sizeof(GPRArgRegs[0]));
2774 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2777 unsigned Align = MF.getTarget()
2779 ->getFrameLowering()
2780 ->getStackAlignment();
2781 ArgRegsSize = NumGPRs * 4;
2783 // If parameter is split between stack and GPRs...
2784 if (NumGPRs && Align > 4 &&
2785 (ArgRegsSize < ArgSize ||
2786 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2787 // Add padding for part of param recovered from GPRs. For example,
2788 // if Align == 8, its last byte must be at address K*8 - 1.
2789 // We need to do it, since remained (stack) part of parameter has
2790 // stack alignment, and we need to "attach" "GPRs head" without gaps
2793 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2794 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2796 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2798 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2799 ArgRegsSaveSize = ArgRegsSize + Padding;
2801 // We don't need to extend regs save size for byval parameters if they
2802 // are passed via GPRs only.
2803 ArgRegsSaveSize = ArgRegsSize;
2806 // The remaining GPRs hold either the beginning of variable-argument
2807 // data, or the beginning of an aggregate passed by value (usually
2808 // byval). Either way, we allocate stack slots adjacent to the data
2809 // provided by our caller, and store the unallocated registers there.
2810 // If this is a variadic function, the va_list pointer will begin with
2811 // these values; otherwise, this reassembles a (byval) structure that
2812 // was split between registers and memory.
2813 // Return: The frame index registers were stored into.
2815 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2816 SDLoc dl, SDValue &Chain,
2817 const Value *OrigArg,
2818 unsigned InRegsParamRecordIdx,
2819 unsigned OffsetFromOrigArg,
2823 unsigned ByValStoreOffset,
2824 unsigned TotalArgRegsSaveSize) const {
2826 // Currently, two use-cases possible:
2827 // Case #1. Non-var-args function, and we meet first byval parameter.
2828 // Setup first unallocated register as first byval register;
2829 // eat all remained registers
2830 // (these two actions are performed by HandleByVal method).
2831 // Then, here, we initialize stack frame with
2832 // "store-reg" instructions.
2833 // Case #2. Var-args function, that doesn't contain byval parameters.
2834 // The same: eat all remained unallocated registers,
2835 // initialize stack frame.
2837 MachineFunction &MF = DAG.getMachineFunction();
2838 MachineFrameInfo *MFI = MF.getFrameInfo();
2839 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2840 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2841 unsigned RBegin, REnd;
2842 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2843 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2844 firstRegToSaveIndex = RBegin - ARM::R0;
2845 lastRegToSaveIndex = REnd - ARM::R0;
2847 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2848 (GPRArgRegs, array_lengthof(GPRArgRegs));
2849 lastRegToSaveIndex = 4;
2852 unsigned ArgRegsSize, ArgRegsSaveSize;
2853 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2854 ArgRegsSize, ArgRegsSaveSize);
2856 // Store any by-val regs to their spots on the stack so that they may be
2857 // loaded by deferencing the result of formal parameter pointer or va_next.
2858 // Note: once stack area for byval/varargs registers
2859 // was initialized, it can't be initialized again.
2860 if (ArgRegsSaveSize) {
2861 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2864 assert(AFI->getStoredByValParamsPadding() == 0 &&
2865 "The only parameter may be padded.");
2866 AFI->setStoredByValParamsPadding(Padding);
2869 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2872 (int64_t)TotalArgRegsSaveSize,
2874 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2876 MFI->CreateFixedObject(Padding,
2877 ArgOffset + ByValStoreOffset -
2878 (int64_t)ArgRegsSaveSize,
2882 SmallVector<SDValue, 4> MemOps;
2883 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2884 ++firstRegToSaveIndex, ++i) {
2885 const TargetRegisterClass *RC;
2886 if (AFI->isThumb1OnlyFunction())
2887 RC = &ARM::tGPRRegClass;
2889 RC = &ARM::GPRRegClass;
2891 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2892 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2894 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2895 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2897 MemOps.push_back(Store);
2898 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2899 DAG.getConstant(4, getPointerTy()));
2902 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2904 if (!MemOps.empty())
2905 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2909 // We cannot allocate a zero-byte object for the first variadic argument,
2910 // so just make up a size.
2913 // This will point to the next argument passed via stack.
2914 return MFI->CreateFixedObject(
2915 ArgSize, ArgOffset, !ForceMutable);
2919 // Setup stack frame, the va_list pointer will start from.
2921 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2922 SDLoc dl, SDValue &Chain,
2924 unsigned TotalArgRegsSaveSize,
2925 bool ForceMutable) const {
2926 MachineFunction &MF = DAG.getMachineFunction();
2927 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2929 // Try to store any remaining integer argument regs
2930 // to their spots on the stack so that they may be loaded by deferencing
2931 // the result of va_next.
2932 // If there is no regs to be stored, just point address after last
2933 // argument passed via stack.
2935 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2936 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2937 0, TotalArgRegsSaveSize);
2939 AFI->setVarArgsFrameIndex(FrameIndex);
2943 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2944 CallingConv::ID CallConv, bool isVarArg,
2945 const SmallVectorImpl<ISD::InputArg>
2947 SDLoc dl, SelectionDAG &DAG,
2948 SmallVectorImpl<SDValue> &InVals)
2950 MachineFunction &MF = DAG.getMachineFunction();
2951 MachineFrameInfo *MFI = MF.getFrameInfo();
2953 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2955 // Assign locations to all of the incoming arguments.
2956 SmallVector<CCValAssign, 16> ArgLocs;
2957 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2958 *DAG.getContext(), Prologue);
2959 CCInfo.AnalyzeFormalArguments(Ins,
2960 CCAssignFnForNode(CallConv, /* Return*/ false,
2963 SmallVector<SDValue, 16> ArgValues;
2964 int lastInsIndex = -1;
2966 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2967 unsigned CurArgIdx = 0;
2969 // Initially ArgRegsSaveSize is zero.
2970 // Then we increase this value each time we meet byval parameter.
2971 // We also increase this value in case of varargs function.
2972 AFI->setArgRegsSaveSize(0);
2974 unsigned ByValStoreOffset = 0;
2975 unsigned TotalArgRegsSaveSize = 0;
2976 unsigned ArgRegsSaveSizeMaxAlign = 4;
2978 // Calculate the amount of stack space that we need to allocate to store
2979 // byval and variadic arguments that are passed in registers.
2980 // We need to know this before we allocate the first byval or variadic
2981 // argument, as they will be allocated a stack slot below the CFA (Canonical
2982 // Frame Address, the stack pointer at entry to the function).
2983 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2984 CCValAssign &VA = ArgLocs[i];
2985 if (VA.isMemLoc()) {
2986 int index = VA.getValNo();
2987 if (index != lastInsIndex) {
2988 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2989 if (Flags.isByVal()) {
2990 unsigned ExtraArgRegsSize;
2991 unsigned ExtraArgRegsSaveSize;
2992 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2993 Flags.getByValSize(),
2994 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2996 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2997 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2998 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2999 CCInfo.nextInRegsParam();
3001 lastInsIndex = index;
3005 CCInfo.rewindByValRegsInfo();
3008 unsigned ExtraArgRegsSize;
3009 unsigned ExtraArgRegsSaveSize;
3010 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3011 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3012 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3014 // If the arg regs save area contains N-byte aligned values, the
3015 // bottom of it must be at least N-byte aligned.
3016 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3017 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3019 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3020 CCValAssign &VA = ArgLocs[i];
3021 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3022 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3023 // Arguments stored in registers.
3024 if (VA.isRegLoc()) {
3025 EVT RegVT = VA.getLocVT();
3027 if (VA.needsCustom()) {
3028 // f64 and vector types are split up into multiple registers or
3029 // combinations of registers and stack slots.
3030 if (VA.getLocVT() == MVT::v2f64) {
3031 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3033 VA = ArgLocs[++i]; // skip ahead to next loc
3035 if (VA.isMemLoc()) {
3036 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3037 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3038 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3039 MachinePointerInfo::getFixedStack(FI),
3040 false, false, false, 0);
3042 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3045 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3046 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3047 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3048 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3049 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3051 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3054 const TargetRegisterClass *RC;
3056 if (RegVT == MVT::f32)
3057 RC = &ARM::SPRRegClass;
3058 else if (RegVT == MVT::f64)
3059 RC = &ARM::DPRRegClass;
3060 else if (RegVT == MVT::v2f64)
3061 RC = &ARM::QPRRegClass;
3062 else if (RegVT == MVT::i32)
3063 RC = AFI->isThumb1OnlyFunction() ?
3064 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3065 (const TargetRegisterClass*)&ARM::GPRRegClass;
3067 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3069 // Transform the arguments in physical registers into virtual ones.
3070 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3071 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3074 // If this is an 8 or 16-bit value, it is really passed promoted
3075 // to 32 bits. Insert an assert[sz]ext to capture this, then
3076 // truncate to the right size.
3077 switch (VA.getLocInfo()) {
3078 default: llvm_unreachable("Unknown loc info!");
3079 case CCValAssign::Full: break;
3080 case CCValAssign::BCvt:
3081 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3083 case CCValAssign::SExt:
3084 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3085 DAG.getValueType(VA.getValVT()));
3086 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3088 case CCValAssign::ZExt:
3089 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3090 DAG.getValueType(VA.getValVT()));
3091 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3095 InVals.push_back(ArgValue);
3097 } else { // VA.isRegLoc()
3100 assert(VA.isMemLoc());
3101 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3103 int index = ArgLocs[i].getValNo();
3105 // Some Ins[] entries become multiple ArgLoc[] entries.
3106 // Process them only once.
3107 if (index != lastInsIndex)
3109 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3110 // FIXME: For now, all byval parameter objects are marked mutable.
3111 // This can be changed with more analysis.
3112 // In case of tail call optimization mark all arguments mutable.
3113 // Since they could be overwritten by lowering of arguments in case of
3115 if (Flags.isByVal()) {
3116 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3118 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3119 int FrameIndex = StoreByValRegs(
3120 CCInfo, DAG, dl, Chain, CurOrigArg,
3122 Ins[VA.getValNo()].PartOffset,
3123 VA.getLocMemOffset(),
3124 Flags.getByValSize(),
3125 true /*force mutable frames*/,
3127 TotalArgRegsSaveSize);
3128 ByValStoreOffset += Flags.getByValSize();
3129 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3130 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3131 CCInfo.nextInRegsParam();
3133 unsigned FIOffset = VA.getLocMemOffset();
3134 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3137 // Create load nodes to retrieve arguments from the stack.
3138 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3139 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3140 MachinePointerInfo::getFixedStack(FI),
3141 false, false, false, 0));
3143 lastInsIndex = index;
3150 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3151 CCInfo.getNextStackOffset(),
3152 TotalArgRegsSaveSize);
3154 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3159 /// isFloatingPointZero - Return true if this is +0.0.
3160 static bool isFloatingPointZero(SDValue Op) {
3161 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3162 return CFP->getValueAPF().isPosZero();
3163 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3164 // Maybe this has already been legalized into the constant pool?
3165 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3166 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3167 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3168 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3169 return CFP->getValueAPF().isPosZero();
3175 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3176 /// the given operands.
3178 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3179 SDValue &ARMcc, SelectionDAG &DAG,
3181 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3182 unsigned C = RHSC->getZExtValue();
3183 if (!isLegalICmpImmediate(C)) {
3184 // Constant does not fit, try adjusting it by one?
3189 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3190 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3191 RHS = DAG.getConstant(C-1, MVT::i32);
3196 if (C != 0 && isLegalICmpImmediate(C-1)) {
3197 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3198 RHS = DAG.getConstant(C-1, MVT::i32);
3203 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3204 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3205 RHS = DAG.getConstant(C+1, MVT::i32);
3210 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3211 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3212 RHS = DAG.getConstant(C+1, MVT::i32);
3219 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3220 ARMISD::NodeType CompareType;
3223 CompareType = ARMISD::CMP;
3228 CompareType = ARMISD::CMPZ;
3231 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3232 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3235 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3237 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3240 if (!isFloatingPointZero(RHS))
3241 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3243 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3244 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3247 /// duplicateCmp - Glue values can have only one use, so this function
3248 /// duplicates a comparison node.
3250 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3251 unsigned Opc = Cmp.getOpcode();
3253 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3254 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3256 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3257 Cmp = Cmp.getOperand(0);
3258 Opc = Cmp.getOpcode();
3259 if (Opc == ARMISD::CMPFP)
3260 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3262 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3263 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3265 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3268 std::pair<SDValue, SDValue>
3269 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3270 SDValue &ARMcc) const {
3271 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3273 SDValue Value, OverflowCmp;
3274 SDValue LHS = Op.getOperand(0);
3275 SDValue RHS = Op.getOperand(1);
3278 // FIXME: We are currently always generating CMPs because we don't support
3279 // generating CMN through the backend. This is not as good as the natural
3280 // CMP case because it causes a register dependency and cannot be folded
3283 switch (Op.getOpcode()) {
3285 llvm_unreachable("Unknown overflow instruction!");
3287 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3288 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3289 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3292 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3293 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3294 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3297 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3298 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3299 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3302 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3303 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3304 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3308 return std::make_pair(Value, OverflowCmp);
3313 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3314 // Let legalize expand this if it isn't a legal type yet.
3315 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3318 SDValue Value, OverflowCmp;
3320 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3321 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3322 // We use 0 and 1 as false and true values.
3323 SDValue TVal = DAG.getConstant(1, MVT::i32);
3324 SDValue FVal = DAG.getConstant(0, MVT::i32);
3325 EVT VT = Op.getValueType();
3327 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3328 ARMcc, CCR, OverflowCmp);
3330 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3331 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3335 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3336 SDValue Cond = Op.getOperand(0);
3337 SDValue SelectTrue = Op.getOperand(1);
3338 SDValue SelectFalse = Op.getOperand(2);
3340 unsigned Opc = Cond.getOpcode();
3342 if (Cond.getResNo() == 1 &&
3343 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3344 Opc == ISD::USUBO)) {
3345 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3348 SDValue Value, OverflowCmp;
3350 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3351 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3352 EVT VT = Op.getValueType();
3354 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3355 ARMcc, CCR, OverflowCmp);
3361 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3362 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3364 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3365 const ConstantSDNode *CMOVTrue =
3366 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3367 const ConstantSDNode *CMOVFalse =
3368 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3370 if (CMOVTrue && CMOVFalse) {
3371 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3372 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3376 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3378 False = SelectFalse;
3379 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3384 if (True.getNode() && False.getNode()) {
3385 EVT VT = Op.getValueType();
3386 SDValue ARMcc = Cond.getOperand(2);
3387 SDValue CCR = Cond.getOperand(3);
3388 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3389 assert(True.getValueType() == VT);
3390 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3395 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3396 // undefined bits before doing a full-word comparison with zero.
3397 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3398 DAG.getConstant(1, Cond.getValueType()));
3400 return DAG.getSelectCC(dl, Cond,
3401 DAG.getConstant(0, Cond.getValueType()),
3402 SelectTrue, SelectFalse, ISD::SETNE);
3405 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3406 if (CC == ISD::SETNE)
3408 return ISD::getSetCCInverse(CC, true);
3411 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3412 bool &swpCmpOps, bool &swpVselOps) {
3413 // Start by selecting the GE condition code for opcodes that return true for
3415 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3417 CondCode = ARMCC::GE;
3419 // and GT for opcodes that return false for 'equality'.
3420 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3422 CondCode = ARMCC::GT;
3424 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3425 // to swap the compare operands.
3426 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3430 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3431 // If we have an unordered opcode, we need to swap the operands to the VSEL
3432 // instruction (effectively negating the condition).
3434 // This also has the effect of swapping which one of 'less' or 'greater'
3435 // returns true, so we also swap the compare operands. It also switches
3436 // whether we return true for 'equality', so we compensate by picking the
3437 // opposite condition code to our original choice.
3438 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3439 CC == ISD::SETUGT) {
3440 swpCmpOps = !swpCmpOps;
3441 swpVselOps = !swpVselOps;
3442 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3445 // 'ordered' is 'anything but unordered', so use the VS condition code and
3446 // swap the VSEL operands.
3447 if (CC == ISD::SETO) {
3448 CondCode = ARMCC::VS;
3452 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3453 // code and swap the VSEL operands.
3454 if (CC == ISD::SETUNE) {
3455 CondCode = ARMCC::EQ;
3460 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3461 EVT VT = Op.getValueType();
3462 SDValue LHS = Op.getOperand(0);
3463 SDValue RHS = Op.getOperand(1);
3464 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3465 SDValue TrueVal = Op.getOperand(2);
3466 SDValue FalseVal = Op.getOperand(3);
3469 if (LHS.getValueType() == MVT::i32) {
3470 // Try to generate VSEL on ARMv8.
3471 // The VSEL instruction can't use all the usual ARM condition
3472 // codes: it only has two bits to select the condition code, so it's
3473 // constrained to use only GE, GT, VS and EQ.
3475 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3476 // swap the operands of the previous compare instruction (effectively
3477 // inverting the compare condition, swapping 'less' and 'greater') and
3478 // sometimes need to swap the operands to the VSEL (which inverts the
3479 // condition in the sense of firing whenever the previous condition didn't)
3480 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3481 TrueVal.getValueType() == MVT::f64)) {
3482 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3483 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3484 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3485 CC = getInverseCCForVSEL(CC);
3486 std::swap(TrueVal, FalseVal);
3491 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3492 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3493 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3497 ARMCC::CondCodes CondCode, CondCode2;
3498 FPCCToARMCC(CC, CondCode, CondCode2);
3500 // Try to generate VSEL on ARMv8.
3501 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3502 TrueVal.getValueType() == MVT::f64)) {
3503 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3504 // same operands, as follows:
3505 // c = fcmp [ogt, olt, ugt, ult] a, b
3507 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3508 // handled differently than the original code sequence.
3509 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3511 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3512 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3513 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3514 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3517 bool swpCmpOps = false;
3518 bool swpVselOps = false;
3519 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3521 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3522 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3524 std::swap(LHS, RHS);
3526 std::swap(TrueVal, FalseVal);
3530 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3531 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3532 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3533 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3535 if (CondCode2 != ARMCC::AL) {
3536 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3537 // FIXME: Needs another CMP because flag can have but one use.
3538 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3539 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3540 Result, TrueVal, ARMcc2, CCR, Cmp2);
3545 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3546 /// to morph to an integer compare sequence.
3547 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3548 const ARMSubtarget *Subtarget) {
3549 SDNode *N = Op.getNode();
3550 if (!N->hasOneUse())
3551 // Otherwise it requires moving the value from fp to integer registers.
3553 if (!N->getNumValues())
3555 EVT VT = Op.getValueType();
3556 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3557 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3558 // vmrs are very slow, e.g. cortex-a8.
3561 if (isFloatingPointZero(Op)) {
3565 return ISD::isNormalLoad(N);
3568 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3569 if (isFloatingPointZero(Op))
3570 return DAG.getConstant(0, MVT::i32);
3572 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3573 return DAG.getLoad(MVT::i32, SDLoc(Op),
3574 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3575 Ld->isVolatile(), Ld->isNonTemporal(),
3576 Ld->isInvariant(), Ld->getAlignment());
3578 llvm_unreachable("Unknown VFP cmp argument!");
3581 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3582 SDValue &RetVal1, SDValue &RetVal2) {
3583 if (isFloatingPointZero(Op)) {
3584 RetVal1 = DAG.getConstant(0, MVT::i32);
3585 RetVal2 = DAG.getConstant(0, MVT::i32);
3589 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3590 SDValue Ptr = Ld->getBasePtr();
3591 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3592 Ld->getChain(), Ptr,
3593 Ld->getPointerInfo(),
3594 Ld->isVolatile(), Ld->isNonTemporal(),
3595 Ld->isInvariant(), Ld->getAlignment());
3597 EVT PtrType = Ptr.getValueType();
3598 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3599 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3600 PtrType, Ptr, DAG.getConstant(4, PtrType));
3601 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3602 Ld->getChain(), NewPtr,
3603 Ld->getPointerInfo().getWithOffset(4),
3604 Ld->isVolatile(), Ld->isNonTemporal(),
3605 Ld->isInvariant(), NewAlign);
3609 llvm_unreachable("Unknown VFP cmp argument!");
3612 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3613 /// f32 and even f64 comparisons to integer ones.
3615 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3616 SDValue Chain = Op.getOperand(0);
3617 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3618 SDValue LHS = Op.getOperand(2);
3619 SDValue RHS = Op.getOperand(3);
3620 SDValue Dest = Op.getOperand(4);
3623 bool LHSSeenZero = false;
3624 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3625 bool RHSSeenZero = false;
3626 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3627 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3628 // If unsafe fp math optimization is enabled and there are no other uses of
3629 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3630 // to an integer comparison.
3631 if (CC == ISD::SETOEQ)
3633 else if (CC == ISD::SETUNE)
3636 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3638 if (LHS.getValueType() == MVT::f32) {
3639 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3640 bitcastf32Toi32(LHS, DAG), Mask);
3641 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3642 bitcastf32Toi32(RHS, DAG), Mask);
3643 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3644 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3645 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3646 Chain, Dest, ARMcc, CCR, Cmp);
3651 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3652 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3653 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3654 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3655 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3656 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3657 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3658 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3659 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3665 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3666 SDValue Chain = Op.getOperand(0);
3667 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3668 SDValue LHS = Op.getOperand(2);
3669 SDValue RHS = Op.getOperand(3);
3670 SDValue Dest = Op.getOperand(4);
3673 if (LHS.getValueType() == MVT::i32) {
3675 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3676 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3677 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3678 Chain, Dest, ARMcc, CCR, Cmp);
3681 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3683 if (getTargetMachine().Options.UnsafeFPMath &&
3684 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3685 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3686 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3687 if (Result.getNode())
3691 ARMCC::CondCodes CondCode, CondCode2;
3692 FPCCToARMCC(CC, CondCode, CondCode2);
3694 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3695 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3696 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3697 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3698 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3699 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3700 if (CondCode2 != ARMCC::AL) {
3701 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3702 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3703 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3708 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3709 SDValue Chain = Op.getOperand(0);
3710 SDValue Table = Op.getOperand(1);
3711 SDValue Index = Op.getOperand(2);
3714 EVT PTy = getPointerTy();
3715 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3716 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3717 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3718 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3719 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3720 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3721 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3722 if (Subtarget->isThumb2()) {
3723 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3724 // which does another jump to the destination. This also makes it easier
3725 // to translate it to TBB / TBH later.
3726 // FIXME: This might not work if the function is extremely large.
3727 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3728 Addr, Op.getOperand(2), JTI, UId);
3730 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3731 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3732 MachinePointerInfo::getJumpTable(),
3733 false, false, false, 0);
3734 Chain = Addr.getValue(1);
3735 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3736 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3738 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3739 MachinePointerInfo::getJumpTable(),
3740 false, false, false, 0);
3741 Chain = Addr.getValue(1);
3742 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3746 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3747 EVT VT = Op.getValueType();
3750 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3751 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3753 return DAG.UnrollVectorOp(Op.getNode());
3756 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3757 "Invalid type for custom lowering!");
3758 if (VT != MVT::v4i16)
3759 return DAG.UnrollVectorOp(Op.getNode());
3761 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3762 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3765 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3766 EVT VT = Op.getValueType();
3768 return LowerVectorFP_TO_INT(Op, DAG);
3773 switch (Op.getOpcode()) {
3774 default: llvm_unreachable("Invalid opcode!");
3775 case ISD::FP_TO_SINT:
3776 Opc = ARMISD::FTOSI;
3778 case ISD::FP_TO_UINT:
3779 Opc = ARMISD::FTOUI;
3782 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3783 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3786 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3787 EVT VT = Op.getValueType();
3790 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3791 if (VT.getVectorElementType() == MVT::f32)
3793 return DAG.UnrollVectorOp(Op.getNode());
3796 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3797 "Invalid type for custom lowering!");
3798 if (VT != MVT::v4f32)
3799 return DAG.UnrollVectorOp(Op.getNode());
3803 switch (Op.getOpcode()) {
3804 default: llvm_unreachable("Invalid opcode!");
3805 case ISD::SINT_TO_FP:
3806 CastOpc = ISD::SIGN_EXTEND;
3807 Opc = ISD::SINT_TO_FP;
3809 case ISD::UINT_TO_FP:
3810 CastOpc = ISD::ZERO_EXTEND;
3811 Opc = ISD::UINT_TO_FP;
3815 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3816 return DAG.getNode(Opc, dl, VT, Op);
3819 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3820 EVT VT = Op.getValueType();
3822 return LowerVectorINT_TO_FP(Op, DAG);
3827 switch (Op.getOpcode()) {
3828 default: llvm_unreachable("Invalid opcode!");
3829 case ISD::SINT_TO_FP:
3830 Opc = ARMISD::SITOF;
3832 case ISD::UINT_TO_FP:
3833 Opc = ARMISD::UITOF;
3837 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3838 return DAG.getNode(Opc, dl, VT, Op);
3841 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3842 // Implement fcopysign with a fabs and a conditional fneg.
3843 SDValue Tmp0 = Op.getOperand(0);
3844 SDValue Tmp1 = Op.getOperand(1);
3846 EVT VT = Op.getValueType();
3847 EVT SrcVT = Tmp1.getValueType();
3848 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3849 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3850 bool UseNEON = !InGPR && Subtarget->hasNEON();
3853 // Use VBSL to copy the sign bit.
3854 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3855 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3856 DAG.getTargetConstant(EncodedVal, MVT::i32));
3857 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3859 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3860 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3861 DAG.getConstant(32, MVT::i32));
3862 else /*if (VT == MVT::f32)*/
3863 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3864 if (SrcVT == MVT::f32) {
3865 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3867 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3868 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3869 DAG.getConstant(32, MVT::i32));
3870 } else if (VT == MVT::f32)
3871 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3872 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3873 DAG.getConstant(32, MVT::i32));
3874 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3875 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3877 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3879 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3880 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3881 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3883 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3884 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3885 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3886 if (VT == MVT::f32) {
3887 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3888 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3889 DAG.getConstant(0, MVT::i32));
3891 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3897 // Bitcast operand 1 to i32.
3898 if (SrcVT == MVT::f64)
3899 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3901 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3903 // Or in the signbit with integer operations.
3904 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3905 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3906 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3907 if (VT == MVT::f32) {
3908 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3909 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3910 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3911 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3914 // f64: Or the high part with signbit and then combine two parts.
3915 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3917 SDValue Lo = Tmp0.getValue(0);
3918 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3919 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3920 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3923 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3924 MachineFunction &MF = DAG.getMachineFunction();
3925 MachineFrameInfo *MFI = MF.getFrameInfo();
3926 MFI->setReturnAddressIsTaken(true);
3928 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3931 EVT VT = Op.getValueType();
3933 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3935 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3936 SDValue Offset = DAG.getConstant(4, MVT::i32);
3937 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3938 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3939 MachinePointerInfo(), false, false, false, 0);
3942 // Return LR, which contains the return address. Mark it an implicit live-in.
3943 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3944 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3947 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3948 const ARMBaseRegisterInfo &ARI =
3949 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3950 MachineFunction &MF = DAG.getMachineFunction();
3951 MachineFrameInfo *MFI = MF.getFrameInfo();
3952 MFI->setFrameAddressIsTaken(true);
3954 EVT VT = Op.getValueType();
3955 SDLoc dl(Op); // FIXME probably not meaningful
3956 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3957 unsigned FrameReg = ARI.getFrameRegister(MF);
3958 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3960 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3961 MachinePointerInfo(),
3962 false, false, false, 0);
3966 // FIXME? Maybe this could be a TableGen attribute on some registers and
3967 // this table could be generated automatically from RegInfo.
3968 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3970 unsigned Reg = StringSwitch<unsigned>(RegName)
3971 .Case("sp", ARM::SP)
3975 report_fatal_error("Invalid register name global variable");
3978 /// ExpandBITCAST - If the target supports VFP, this function is called to
3979 /// expand a bit convert where either the source or destination type is i64 to
3980 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3981 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3982 /// vectors), since the legalizer won't know what to do with that.
3983 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3984 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3986 SDValue Op = N->getOperand(0);
3988 // This function is only supposed to be called for i64 types, either as the
3989 // source or destination of the bit convert.
3990 EVT SrcVT = Op.getValueType();
3991 EVT DstVT = N->getValueType(0);
3992 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3993 "ExpandBITCAST called for non-i64 type");
3995 // Turn i64->f64 into VMOVDRR.
3996 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3997 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3998 DAG.getConstant(0, MVT::i32));
3999 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4000 DAG.getConstant(1, MVT::i32));
4001 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4002 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4005 // Turn f64->i64 into VMOVRRD.
4006 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4008 if (TLI.isBigEndian() && SrcVT.isVector() &&
4009 SrcVT.getVectorNumElements() > 1)
4010 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4011 DAG.getVTList(MVT::i32, MVT::i32),
4012 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4014 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4015 DAG.getVTList(MVT::i32, MVT::i32), Op);
4016 // Merge the pieces into a single i64 value.
4017 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4023 /// getZeroVector - Returns a vector of specified type with all zero elements.
4024 /// Zero vectors are used to represent vector negation and in those cases
4025 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4026 /// not support i64 elements, so sometimes the zero vectors will need to be
4027 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4029 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4030 assert(VT.isVector() && "Expected a vector type");
4031 // The canonical modified immediate encoding of a zero vector is....0!
4032 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4033 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4034 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4035 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4038 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4039 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4040 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4041 SelectionDAG &DAG) const {
4042 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4043 EVT VT = Op.getValueType();
4044 unsigned VTBits = VT.getSizeInBits();
4046 SDValue ShOpLo = Op.getOperand(0);
4047 SDValue ShOpHi = Op.getOperand(1);
4048 SDValue ShAmt = Op.getOperand(2);
4050 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4052 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4054 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4055 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4056 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4057 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4058 DAG.getConstant(VTBits, MVT::i32));
4059 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4060 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4061 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4063 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4064 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4066 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4067 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4070 SDValue Ops[2] = { Lo, Hi };
4071 return DAG.getMergeValues(Ops, dl);
4074 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4075 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4076 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4077 SelectionDAG &DAG) const {
4078 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4079 EVT VT = Op.getValueType();
4080 unsigned VTBits = VT.getSizeInBits();
4082 SDValue ShOpLo = Op.getOperand(0);
4083 SDValue ShOpHi = Op.getOperand(1);
4084 SDValue ShAmt = Op.getOperand(2);
4087 assert(Op.getOpcode() == ISD::SHL_PARTS);
4088 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4089 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4090 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4091 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4092 DAG.getConstant(VTBits, MVT::i32));
4093 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4094 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4096 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4097 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4098 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4100 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4101 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4104 SDValue Ops[2] = { Lo, Hi };
4105 return DAG.getMergeValues(Ops, dl);
4108 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4109 SelectionDAG &DAG) const {
4110 // The rounding mode is in bits 23:22 of the FPSCR.
4111 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4112 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4113 // so that the shift + and get folded into a bitfield extract.
4115 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4116 DAG.getConstant(Intrinsic::arm_get_fpscr,
4118 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4119 DAG.getConstant(1U << 22, MVT::i32));
4120 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4121 DAG.getConstant(22, MVT::i32));
4122 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4123 DAG.getConstant(3, MVT::i32));
4126 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4127 const ARMSubtarget *ST) {
4128 EVT VT = N->getValueType(0);
4131 if (!ST->hasV6T2Ops())
4134 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4135 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4138 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4139 /// for each 16-bit element from operand, repeated. The basic idea is to
4140 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4142 /// Trace for v4i16:
4143 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4144 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4145 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4146 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4147 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4148 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4149 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4150 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4151 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4152 EVT VT = N->getValueType(0);
4155 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4156 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4157 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4158 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4159 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4160 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4163 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4164 /// bit-count for each 16-bit element from the operand. We need slightly
4165 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4166 /// 64/128-bit registers.
4168 /// Trace for v4i16:
4169 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4170 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4171 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4172 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4173 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4174 EVT VT = N->getValueType(0);
4177 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4178 if (VT.is64BitVector()) {
4179 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4180 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4181 DAG.getIntPtrConstant(0));
4183 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4184 BitCounts, DAG.getIntPtrConstant(0));
4185 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4189 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4190 /// bit-count for each 32-bit element from the operand. The idea here is
4191 /// to split the vector into 16-bit elements, leverage the 16-bit count
4192 /// routine, and then combine the results.
4194 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4195 /// input = [v0 v1 ] (vi: 32-bit elements)
4196 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4197 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4198 /// vrev: N0 = [k1 k0 k3 k2 ]
4200 /// N1 =+[k1 k0 k3 k2 ]
4202 /// N2 =+[k1 k3 k0 k2 ]
4204 /// Extended =+[k1 k3 k0 k2 ]
4206 /// Extracted=+[k1 k3 ]
4208 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4209 EVT VT = N->getValueType(0);
4212 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4214 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4215 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4216 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4217 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4218 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4220 if (VT.is64BitVector()) {
4221 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4222 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4223 DAG.getIntPtrConstant(0));
4225 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4226 DAG.getIntPtrConstant(0));
4227 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4231 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4232 const ARMSubtarget *ST) {
4233 EVT VT = N->getValueType(0);
4235 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4236 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4237 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4238 "Unexpected type for custom ctpop lowering");
4240 if (VT.getVectorElementType() == MVT::i32)
4241 return lowerCTPOP32BitElements(N, DAG);
4243 return lowerCTPOP16BitElements(N, DAG);
4246 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4247 const ARMSubtarget *ST) {
4248 EVT VT = N->getValueType(0);
4254 // Lower vector shifts on NEON to use VSHL.
4255 assert(ST->hasNEON() && "unexpected vector shift");
4257 // Left shifts translate directly to the vshiftu intrinsic.
4258 if (N->getOpcode() == ISD::SHL)
4259 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4260 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4261 N->getOperand(0), N->getOperand(1));
4263 assert((N->getOpcode() == ISD::SRA ||
4264 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4266 // NEON uses the same intrinsics for both left and right shifts. For
4267 // right shifts, the shift amounts are negative, so negate the vector of
4269 EVT ShiftVT = N->getOperand(1).getValueType();
4270 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4271 getZeroVector(ShiftVT, DAG, dl),
4273 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4274 Intrinsic::arm_neon_vshifts :
4275 Intrinsic::arm_neon_vshiftu);
4276 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4277 DAG.getConstant(vshiftInt, MVT::i32),
4278 N->getOperand(0), NegatedCount);
4281 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4282 const ARMSubtarget *ST) {
4283 EVT VT = N->getValueType(0);
4286 // We can get here for a node like i32 = ISD::SHL i32, i64
4290 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4291 "Unknown shift to lower!");
4293 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4294 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4295 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4298 // If we are in thumb mode, we don't have RRX.
4299 if (ST->isThumb1Only()) return SDValue();
4301 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4302 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4303 DAG.getConstant(0, MVT::i32));
4304 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4305 DAG.getConstant(1, MVT::i32));
4307 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4308 // captures the result into a carry flag.
4309 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4310 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4312 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4313 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4315 // Merge the pieces into a single i64 value.
4316 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4319 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4320 SDValue TmpOp0, TmpOp1;
4321 bool Invert = false;
4325 SDValue Op0 = Op.getOperand(0);
4326 SDValue Op1 = Op.getOperand(1);
4327 SDValue CC = Op.getOperand(2);
4328 EVT VT = Op.getValueType();
4329 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4332 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4333 switch (SetCCOpcode) {
4334 default: llvm_unreachable("Illegal FP comparison");
4336 case ISD::SETNE: Invert = true; // Fallthrough
4338 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4340 case ISD::SETLT: Swap = true; // Fallthrough
4342 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4344 case ISD::SETLE: Swap = true; // Fallthrough
4346 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4347 case ISD::SETUGE: Swap = true; // Fallthrough
4348 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4349 case ISD::SETUGT: Swap = true; // Fallthrough
4350 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4351 case ISD::SETUEQ: Invert = true; // Fallthrough
4353 // Expand this to (OLT | OGT).
4357 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4358 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4360 case ISD::SETUO: Invert = true; // Fallthrough
4362 // Expand this to (OLT | OGE).
4366 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4367 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4371 // Integer comparisons.
4372 switch (SetCCOpcode) {
4373 default: llvm_unreachable("Illegal integer comparison");
4374 case ISD::SETNE: Invert = true;
4375 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4376 case ISD::SETLT: Swap = true;
4377 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4378 case ISD::SETLE: Swap = true;
4379 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4380 case ISD::SETULT: Swap = true;
4381 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4382 case ISD::SETULE: Swap = true;
4383 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4386 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4387 if (Opc == ARMISD::VCEQ) {
4390 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4392 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4395 // Ignore bitconvert.
4396 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4397 AndOp = AndOp.getOperand(0);
4399 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4401 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4402 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4409 std::swap(Op0, Op1);
4411 // If one of the operands is a constant vector zero, attempt to fold the
4412 // comparison to a specialized compare-against-zero form.
4414 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4416 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4417 if (Opc == ARMISD::VCGE)
4418 Opc = ARMISD::VCLEZ;
4419 else if (Opc == ARMISD::VCGT)
4420 Opc = ARMISD::VCLTZ;
4425 if (SingleOp.getNode()) {
4428 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4430 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4432 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4434 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4436 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4438 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4441 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4445 Result = DAG.getNOT(dl, Result, VT);
4450 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4451 /// valid vector constant for a NEON instruction with a "modified immediate"
4452 /// operand (e.g., VMOV). If so, return the encoded value.
4453 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4454 unsigned SplatBitSize, SelectionDAG &DAG,
4455 EVT &VT, bool is128Bits, NEONModImmType type) {
4456 unsigned OpCmode, Imm;
4458 // SplatBitSize is set to the smallest size that splats the vector, so a
4459 // zero vector will always have SplatBitSize == 8. However, NEON modified
4460 // immediate instructions others than VMOV do not support the 8-bit encoding
4461 // of a zero vector, and the default encoding of zero is supposed to be the
4466 switch (SplatBitSize) {
4468 if (type != VMOVModImm)
4470 // Any 1-byte value is OK. Op=0, Cmode=1110.
4471 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4474 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4478 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4479 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4480 if ((SplatBits & ~0xff) == 0) {
4481 // Value = 0x00nn: Op=x, Cmode=100x.
4486 if ((SplatBits & ~0xff00) == 0) {
4487 // Value = 0xnn00: Op=x, Cmode=101x.
4489 Imm = SplatBits >> 8;
4495 // NEON's 32-bit VMOV supports splat values where:
4496 // * only one byte is nonzero, or
4497 // * the least significant byte is 0xff and the second byte is nonzero, or
4498 // * the least significant 2 bytes are 0xff and the third is nonzero.
4499 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4500 if ((SplatBits & ~0xff) == 0) {
4501 // Value = 0x000000nn: Op=x, Cmode=000x.
4506 if ((SplatBits & ~0xff00) == 0) {
4507 // Value = 0x0000nn00: Op=x, Cmode=001x.
4509 Imm = SplatBits >> 8;
4512 if ((SplatBits & ~0xff0000) == 0) {
4513 // Value = 0x00nn0000: Op=x, Cmode=010x.
4515 Imm = SplatBits >> 16;
4518 if ((SplatBits & ~0xff000000) == 0) {
4519 // Value = 0xnn000000: Op=x, Cmode=011x.
4521 Imm = SplatBits >> 24;
4525 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4526 if (type == OtherModImm) return SDValue();
4528 if ((SplatBits & ~0xffff) == 0 &&
4529 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4530 // Value = 0x0000nnff: Op=x, Cmode=1100.
4532 Imm = SplatBits >> 8;
4536 if ((SplatBits & ~0xffffff) == 0 &&
4537 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4538 // Value = 0x00nnffff: Op=x, Cmode=1101.
4540 Imm = SplatBits >> 16;
4544 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4545 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4546 // VMOV.I32. A (very) minor optimization would be to replicate the value
4547 // and fall through here to test for a valid 64-bit splat. But, then the
4548 // caller would also need to check and handle the change in size.
4552 if (type != VMOVModImm)
4554 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4555 uint64_t BitMask = 0xff;
4557 unsigned ImmMask = 1;
4559 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4560 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4563 } else if ((SplatBits & BitMask) != 0) {
4570 if (DAG.getTargetLoweringInfo().isBigEndian())
4571 // swap higher and lower 32 bit word
4572 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4574 // Op=1, Cmode=1110.
4576 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4581 llvm_unreachable("unexpected size for isNEONModifiedImm");
4584 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4585 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4588 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4589 const ARMSubtarget *ST) const {
4593 bool IsDouble = Op.getValueType() == MVT::f64;
4594 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4596 // Try splatting with a VMOV.f32...
4597 APFloat FPVal = CFP->getValueAPF();
4598 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4601 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4602 // We have code in place to select a valid ConstantFP already, no need to
4607 // It's a float and we are trying to use NEON operations where
4608 // possible. Lower it to a splat followed by an extract.
4610 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4611 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4613 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4614 DAG.getConstant(0, MVT::i32));
4617 // The rest of our options are NEON only, make sure that's allowed before
4619 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4623 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4625 // It wouldn't really be worth bothering for doubles except for one very
4626 // important value, which does happen to match: 0.0. So make sure we don't do
4628 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4631 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4632 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4634 if (NewVal != SDValue()) {
4636 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4639 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4641 // It's a float: cast and extract a vector element.
4642 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4644 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4645 DAG.getConstant(0, MVT::i32));
4648 // Finally, try a VMVN.i32
4649 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4651 if (NewVal != SDValue()) {
4653 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4656 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4658 // It's a float: cast and extract a vector element.
4659 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4661 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4662 DAG.getConstant(0, MVT::i32));
4668 // check if an VEXT instruction can handle the shuffle mask when the
4669 // vector sources of the shuffle are the same.
4670 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4671 unsigned NumElts = VT.getVectorNumElements();
4673 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4679 // If this is a VEXT shuffle, the immediate value is the index of the first
4680 // element. The other shuffle indices must be the successive elements after
4682 unsigned ExpectedElt = Imm;
4683 for (unsigned i = 1; i < NumElts; ++i) {
4684 // Increment the expected index. If it wraps around, just follow it
4685 // back to index zero and keep going.
4687 if (ExpectedElt == NumElts)
4690 if (M[i] < 0) continue; // ignore UNDEF indices
4691 if (ExpectedElt != static_cast<unsigned>(M[i]))
4699 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4700 bool &ReverseVEXT, unsigned &Imm) {
4701 unsigned NumElts = VT.getVectorNumElements();
4702 ReverseVEXT = false;
4704 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4710 // If this is a VEXT shuffle, the immediate value is the index of the first
4711 // element. The other shuffle indices must be the successive elements after
4713 unsigned ExpectedElt = Imm;
4714 for (unsigned i = 1; i < NumElts; ++i) {
4715 // Increment the expected index. If it wraps around, it may still be
4716 // a VEXT but the source vectors must be swapped.
4718 if (ExpectedElt == NumElts * 2) {
4723 if (M[i] < 0) continue; // ignore UNDEF indices
4724 if (ExpectedElt != static_cast<unsigned>(M[i]))
4728 // Adjust the index value if the source operands will be swapped.
4735 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4736 /// instruction with the specified blocksize. (The order of the elements
4737 /// within each block of the vector is reversed.)
4738 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4739 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4740 "Only possible block sizes for VREV are: 16, 32, 64");
4742 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4746 unsigned NumElts = VT.getVectorNumElements();
4747 unsigned BlockElts = M[0] + 1;
4748 // If the first shuffle index is UNDEF, be optimistic.
4750 BlockElts = BlockSize / EltSz;
4752 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4755 for (unsigned i = 0; i < NumElts; ++i) {
4756 if (M[i] < 0) continue; // ignore UNDEF indices
4757 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4764 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4765 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4766 // range, then 0 is placed into the resulting vector. So pretty much any mask
4767 // of 8 elements can work here.
4768 return VT == MVT::v8i8 && M.size() == 8;
4771 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4772 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4776 unsigned NumElts = VT.getVectorNumElements();
4777 WhichResult = (M[0] == 0 ? 0 : 1);
4778 for (unsigned i = 0; i < NumElts; i += 2) {
4779 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4780 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4786 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4787 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4788 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4789 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4790 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4794 unsigned NumElts = VT.getVectorNumElements();
4795 WhichResult = (M[0] == 0 ? 0 : 1);
4796 for (unsigned i = 0; i < NumElts; i += 2) {
4797 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4798 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4804 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4805 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4809 unsigned NumElts = VT.getVectorNumElements();
4810 WhichResult = (M[0] == 0 ? 0 : 1);
4811 for (unsigned i = 0; i != NumElts; ++i) {
4812 if (M[i] < 0) continue; // ignore UNDEF indices
4813 if ((unsigned) M[i] != 2 * i + WhichResult)
4817 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4818 if (VT.is64BitVector() && EltSz == 32)
4824 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4825 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4826 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4827 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4828 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4832 unsigned Half = VT.getVectorNumElements() / 2;
4833 WhichResult = (M[0] == 0 ? 0 : 1);
4834 for (unsigned j = 0; j != 2; ++j) {
4835 unsigned Idx = WhichResult;
4836 for (unsigned i = 0; i != Half; ++i) {
4837 int MIdx = M[i + j * Half];
4838 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4844 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4845 if (VT.is64BitVector() && EltSz == 32)
4851 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4852 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4856 unsigned NumElts = VT.getVectorNumElements();
4857 WhichResult = (M[0] == 0 ? 0 : 1);
4858 unsigned Idx = WhichResult * NumElts / 2;
4859 for (unsigned i = 0; i != NumElts; i += 2) {
4860 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4861 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4866 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4867 if (VT.is64BitVector() && EltSz == 32)
4873 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4874 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4875 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4876 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4877 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4881 unsigned NumElts = VT.getVectorNumElements();
4882 WhichResult = (M[0] == 0 ? 0 : 1);
4883 unsigned Idx = WhichResult * NumElts / 2;
4884 for (unsigned i = 0; i != NumElts; i += 2) {
4885 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4886 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4891 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4892 if (VT.is64BitVector() && EltSz == 32)
4898 /// \return true if this is a reverse operation on an vector.
4899 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4900 unsigned NumElts = VT.getVectorNumElements();
4901 // Make sure the mask has the right size.
4902 if (NumElts != M.size())
4905 // Look for <15, ..., 3, -1, 1, 0>.
4906 for (unsigned i = 0; i != NumElts; ++i)
4907 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4913 // If N is an integer constant that can be moved into a register in one
4914 // instruction, return an SDValue of such a constant (will become a MOV
4915 // instruction). Otherwise return null.
4916 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4917 const ARMSubtarget *ST, SDLoc dl) {
4919 if (!isa<ConstantSDNode>(N))
4921 Val = cast<ConstantSDNode>(N)->getZExtValue();
4923 if (ST->isThumb1Only()) {
4924 if (Val <= 255 || ~Val <= 255)
4925 return DAG.getConstant(Val, MVT::i32);
4927 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4928 return DAG.getConstant(Val, MVT::i32);
4933 // If this is a case we can't handle, return null and let the default
4934 // expansion code take care of it.
4935 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4936 const ARMSubtarget *ST) const {
4937 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4939 EVT VT = Op.getValueType();
4941 APInt SplatBits, SplatUndef;
4942 unsigned SplatBitSize;
4944 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4945 if (SplatBitSize <= 64) {
4946 // Check if an immediate VMOV works.
4948 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4949 SplatUndef.getZExtValue(), SplatBitSize,
4950 DAG, VmovVT, VT.is128BitVector(),
4952 if (Val.getNode()) {
4953 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4954 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4957 // Try an immediate VMVN.
4958 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4959 Val = isNEONModifiedImm(NegatedImm,
4960 SplatUndef.getZExtValue(), SplatBitSize,
4961 DAG, VmovVT, VT.is128BitVector(),
4963 if (Val.getNode()) {
4964 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4965 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4968 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4969 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4970 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4972 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4973 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4979 // Scan through the operands to see if only one value is used.
4981 // As an optimisation, even if more than one value is used it may be more
4982 // profitable to splat with one value then change some lanes.
4984 // Heuristically we decide to do this if the vector has a "dominant" value,
4985 // defined as splatted to more than half of the lanes.
4986 unsigned NumElts = VT.getVectorNumElements();
4987 bool isOnlyLowElement = true;
4988 bool usesOnlyOneValue = true;
4989 bool hasDominantValue = false;
4990 bool isConstant = true;
4992 // Map of the number of times a particular SDValue appears in the
4994 DenseMap<SDValue, unsigned> ValueCounts;
4996 for (unsigned i = 0; i < NumElts; ++i) {
4997 SDValue V = Op.getOperand(i);
4998 if (V.getOpcode() == ISD::UNDEF)
5001 isOnlyLowElement = false;
5002 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5005 ValueCounts.insert(std::make_pair(V, 0));
5006 unsigned &Count = ValueCounts[V];
5008 // Is this value dominant? (takes up more than half of the lanes)
5009 if (++Count > (NumElts / 2)) {
5010 hasDominantValue = true;
5014 if (ValueCounts.size() != 1)
5015 usesOnlyOneValue = false;
5016 if (!Value.getNode() && ValueCounts.size() > 0)
5017 Value = ValueCounts.begin()->first;
5019 if (ValueCounts.size() == 0)
5020 return DAG.getUNDEF(VT);
5022 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5023 // Keep going if we are hitting this case.
5024 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5025 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5027 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5029 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5030 // i32 and try again.
5031 if (hasDominantValue && EltSize <= 32) {
5035 // If we are VDUPing a value that comes directly from a vector, that will
5036 // cause an unnecessary move to and from a GPR, where instead we could
5037 // just use VDUPLANE. We can only do this if the lane being extracted
5038 // is at a constant index, as the VDUP from lane instructions only have
5039 // constant-index forms.
5040 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5041 isa<ConstantSDNode>(Value->getOperand(1))) {
5042 // We need to create a new undef vector to use for the VDUPLANE if the
5043 // size of the vector from which we get the value is different than the
5044 // size of the vector that we need to create. We will insert the element
5045 // such that the register coalescer will remove unnecessary copies.
5046 if (VT != Value->getOperand(0).getValueType()) {
5047 ConstantSDNode *constIndex;
5048 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5049 assert(constIndex && "The index is not a constant!");
5050 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5051 VT.getVectorNumElements();
5052 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5053 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5054 Value, DAG.getConstant(index, MVT::i32)),
5055 DAG.getConstant(index, MVT::i32));
5057 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5058 Value->getOperand(0), Value->getOperand(1));
5060 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5062 if (!usesOnlyOneValue) {
5063 // The dominant value was splatted as 'N', but we now have to insert
5064 // all differing elements.
5065 for (unsigned I = 0; I < NumElts; ++I) {
5066 if (Op.getOperand(I) == Value)
5068 SmallVector<SDValue, 3> Ops;
5070 Ops.push_back(Op.getOperand(I));
5071 Ops.push_back(DAG.getConstant(I, MVT::i32));
5072 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5077 if (VT.getVectorElementType().isFloatingPoint()) {
5078 SmallVector<SDValue, 8> Ops;
5079 for (unsigned i = 0; i < NumElts; ++i)
5080 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5082 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5083 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5084 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5086 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5088 if (usesOnlyOneValue) {
5089 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5090 if (isConstant && Val.getNode())
5091 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5095 // If all elements are constants and the case above didn't get hit, fall back
5096 // to the default expansion, which will generate a load from the constant
5101 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5103 SDValue shuffle = ReconstructShuffle(Op, DAG);
5104 if (shuffle != SDValue())
5108 // Vectors with 32- or 64-bit elements can be built by directly assigning
5109 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5110 // will be legalized.
5111 if (EltSize >= 32) {
5112 // Do the expansion with floating-point types, since that is what the VFP
5113 // registers are defined to use, and since i64 is not legal.
5114 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5115 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5116 SmallVector<SDValue, 8> Ops;
5117 for (unsigned i = 0; i < NumElts; ++i)
5118 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5119 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5120 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5123 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5124 // know the default expansion would otherwise fall back on something even
5125 // worse. For a vector with one or two non-undef values, that's
5126 // scalar_to_vector for the elements followed by a shuffle (provided the
5127 // shuffle is valid for the target) and materialization element by element
5128 // on the stack followed by a load for everything else.
5129 if (!isConstant && !usesOnlyOneValue) {
5130 SDValue Vec = DAG.getUNDEF(VT);
5131 for (unsigned i = 0 ; i < NumElts; ++i) {
5132 SDValue V = Op.getOperand(i);
5133 if (V.getOpcode() == ISD::UNDEF)
5135 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5136 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5144 // Gather data to see if the operation can be modelled as a
5145 // shuffle in combination with VEXTs.
5146 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5147 SelectionDAG &DAG) const {
5149 EVT VT = Op.getValueType();
5150 unsigned NumElts = VT.getVectorNumElements();
5152 SmallVector<SDValue, 2> SourceVecs;
5153 SmallVector<unsigned, 2> MinElts;
5154 SmallVector<unsigned, 2> MaxElts;
5156 for (unsigned i = 0; i < NumElts; ++i) {
5157 SDValue V = Op.getOperand(i);
5158 if (V.getOpcode() == ISD::UNDEF)
5160 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5161 // A shuffle can only come from building a vector from various
5162 // elements of other vectors.
5164 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5165 VT.getVectorElementType()) {
5166 // This code doesn't know how to handle shuffles where the vector
5167 // element types do not match (this happens because type legalization
5168 // promotes the return type of EXTRACT_VECTOR_ELT).
5169 // FIXME: It might be appropriate to extend this code to handle
5170 // mismatched types.
5174 // Record this extraction against the appropriate vector if possible...
5175 SDValue SourceVec = V.getOperand(0);
5176 // If the element number isn't a constant, we can't effectively
5177 // analyze what's going on.
5178 if (!isa<ConstantSDNode>(V.getOperand(1)))
5180 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5181 bool FoundSource = false;
5182 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5183 if (SourceVecs[j] == SourceVec) {
5184 if (MinElts[j] > EltNo)
5186 if (MaxElts[j] < EltNo)
5193 // Or record a new source if not...
5195 SourceVecs.push_back(SourceVec);
5196 MinElts.push_back(EltNo);
5197 MaxElts.push_back(EltNo);
5201 // Currently only do something sane when at most two source vectors
5203 if (SourceVecs.size() > 2)
5206 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5207 int VEXTOffsets[2] = {0, 0};
5209 // This loop extracts the usage patterns of the source vectors
5210 // and prepares appropriate SDValues for a shuffle if possible.
5211 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5212 if (SourceVecs[i].getValueType() == VT) {
5213 // No VEXT necessary
5214 ShuffleSrcs[i] = SourceVecs[i];
5217 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5218 // It probably isn't worth padding out a smaller vector just to
5219 // break it down again in a shuffle.
5223 // Since only 64-bit and 128-bit vectors are legal on ARM and
5224 // we've eliminated the other cases...
5225 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5226 "unexpected vector sizes in ReconstructShuffle");
5228 if (MaxElts[i] - MinElts[i] >= NumElts) {
5229 // Span too large for a VEXT to cope
5233 if (MinElts[i] >= NumElts) {
5234 // The extraction can just take the second half
5235 VEXTOffsets[i] = NumElts;
5236 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5238 DAG.getIntPtrConstant(NumElts));
5239 } else if (MaxElts[i] < NumElts) {
5240 // The extraction can just take the first half
5242 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5244 DAG.getIntPtrConstant(0));
5246 // An actual VEXT is needed
5247 VEXTOffsets[i] = MinElts[i];
5248 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5250 DAG.getIntPtrConstant(0));
5251 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5253 DAG.getIntPtrConstant(NumElts));
5254 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5255 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5259 SmallVector<int, 8> Mask;
5261 for (unsigned i = 0; i < NumElts; ++i) {
5262 SDValue Entry = Op.getOperand(i);
5263 if (Entry.getOpcode() == ISD::UNDEF) {
5268 SDValue ExtractVec = Entry.getOperand(0);
5269 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5270 .getOperand(1))->getSExtValue();
5271 if (ExtractVec == SourceVecs[0]) {
5272 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5274 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5278 // Final check before we try to produce nonsense...
5279 if (isShuffleMaskLegal(Mask, VT))
5280 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5286 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5287 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5288 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5289 /// are assumed to be legal.
5291 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5293 if (VT.getVectorNumElements() == 4 &&
5294 (VT.is128BitVector() || VT.is64BitVector())) {
5295 unsigned PFIndexes[4];
5296 for (unsigned i = 0; i != 4; ++i) {
5300 PFIndexes[i] = M[i];
5303 // Compute the index in the perfect shuffle table.
5304 unsigned PFTableIndex =
5305 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5306 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5307 unsigned Cost = (PFEntry >> 30);
5314 unsigned Imm, WhichResult;
5316 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5317 return (EltSize >= 32 ||
5318 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5319 isVREVMask(M, VT, 64) ||
5320 isVREVMask(M, VT, 32) ||
5321 isVREVMask(M, VT, 16) ||
5322 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5323 isVTBLMask(M, VT) ||
5324 isVTRNMask(M, VT, WhichResult) ||
5325 isVUZPMask(M, VT, WhichResult) ||
5326 isVZIPMask(M, VT, WhichResult) ||
5327 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5328 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5329 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5330 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5333 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5334 /// the specified operations to build the shuffle.
5335 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5336 SDValue RHS, SelectionDAG &DAG,
5338 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5339 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5340 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5343 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5352 OP_VUZPL, // VUZP, left result
5353 OP_VUZPR, // VUZP, right result
5354 OP_VZIPL, // VZIP, left result
5355 OP_VZIPR, // VZIP, right result
5356 OP_VTRNL, // VTRN, left result
5357 OP_VTRNR // VTRN, right result
5360 if (OpNum == OP_COPY) {
5361 if (LHSID == (1*9+2)*9+3) return LHS;
5362 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5366 SDValue OpLHS, OpRHS;
5367 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5368 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5369 EVT VT = OpLHS.getValueType();
5372 default: llvm_unreachable("Unknown shuffle opcode!");
5374 // VREV divides the vector in half and swaps within the half.
5375 if (VT.getVectorElementType() == MVT::i32 ||
5376 VT.getVectorElementType() == MVT::f32)
5377 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5378 // vrev <4 x i16> -> VREV32
5379 if (VT.getVectorElementType() == MVT::i16)
5380 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5381 // vrev <4 x i8> -> VREV16
5382 assert(VT.getVectorElementType() == MVT::i8);
5383 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5388 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5389 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5393 return DAG.getNode(ARMISD::VEXT, dl, VT,
5395 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5398 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5399 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5402 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5403 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5406 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5407 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5411 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5412 ArrayRef<int> ShuffleMask,
5413 SelectionDAG &DAG) {
5414 // Check to see if we can use the VTBL instruction.
5415 SDValue V1 = Op.getOperand(0);
5416 SDValue V2 = Op.getOperand(1);
5419 SmallVector<SDValue, 8> VTBLMask;
5420 for (ArrayRef<int>::iterator
5421 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5422 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5424 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5425 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5426 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5428 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5429 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5432 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5433 SelectionDAG &DAG) {
5435 SDValue OpLHS = Op.getOperand(0);
5436 EVT VT = OpLHS.getValueType();
5438 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5439 "Expect an v8i16/v16i8 type");
5440 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5441 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5442 // extract the first 8 bytes into the top double word and the last 8 bytes
5443 // into the bottom double word. The v8i16 case is similar.
5444 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5445 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5446 DAG.getConstant(ExtractNum, MVT::i32));
5449 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5450 SDValue V1 = Op.getOperand(0);
5451 SDValue V2 = Op.getOperand(1);
5453 EVT VT = Op.getValueType();
5454 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5456 // Convert shuffles that are directly supported on NEON to target-specific
5457 // DAG nodes, instead of keeping them as shuffles and matching them again
5458 // during code selection. This is more efficient and avoids the possibility
5459 // of inconsistencies between legalization and selection.
5460 // FIXME: floating-point vectors should be canonicalized to integer vectors
5461 // of the same time so that they get CSEd properly.
5462 ArrayRef<int> ShuffleMask = SVN->getMask();
5464 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5465 if (EltSize <= 32) {
5466 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5467 int Lane = SVN->getSplatIndex();
5468 // If this is undef splat, generate it via "just" vdup, if possible.
5469 if (Lane == -1) Lane = 0;
5471 // Test if V1 is a SCALAR_TO_VECTOR.
5472 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5473 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5475 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5476 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5478 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5479 !isa<ConstantSDNode>(V1.getOperand(0))) {
5480 bool IsScalarToVector = true;
5481 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5482 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5483 IsScalarToVector = false;
5486 if (IsScalarToVector)
5487 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5489 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5490 DAG.getConstant(Lane, MVT::i32));
5495 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5498 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5499 DAG.getConstant(Imm, MVT::i32));
5502 if (isVREVMask(ShuffleMask, VT, 64))
5503 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5504 if (isVREVMask(ShuffleMask, VT, 32))
5505 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5506 if (isVREVMask(ShuffleMask, VT, 16))
5507 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5509 if (V2->getOpcode() == ISD::UNDEF &&
5510 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5511 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5512 DAG.getConstant(Imm, MVT::i32));
5515 // Check for Neon shuffles that modify both input vectors in place.
5516 // If both results are used, i.e., if there are two shuffles with the same
5517 // source operands and with masks corresponding to both results of one of
5518 // these operations, DAG memoization will ensure that a single node is
5519 // used for both shuffles.
5520 unsigned WhichResult;
5521 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5522 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5523 V1, V2).getValue(WhichResult);
5524 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5525 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5526 V1, V2).getValue(WhichResult);
5527 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5528 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5529 V1, V2).getValue(WhichResult);
5531 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5532 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5533 V1, V1).getValue(WhichResult);
5534 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5535 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5536 V1, V1).getValue(WhichResult);
5537 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5538 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5539 V1, V1).getValue(WhichResult);
5542 // If the shuffle is not directly supported and it has 4 elements, use
5543 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5544 unsigned NumElts = VT.getVectorNumElements();
5546 unsigned PFIndexes[4];
5547 for (unsigned i = 0; i != 4; ++i) {
5548 if (ShuffleMask[i] < 0)
5551 PFIndexes[i] = ShuffleMask[i];
5554 // Compute the index in the perfect shuffle table.
5555 unsigned PFTableIndex =
5556 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5557 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5558 unsigned Cost = (PFEntry >> 30);
5561 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5564 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5565 if (EltSize >= 32) {
5566 // Do the expansion with floating-point types, since that is what the VFP
5567 // registers are defined to use, and since i64 is not legal.
5568 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5569 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5570 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5571 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5572 SmallVector<SDValue, 8> Ops;
5573 for (unsigned i = 0; i < NumElts; ++i) {
5574 if (ShuffleMask[i] < 0)
5575 Ops.push_back(DAG.getUNDEF(EltVT));
5577 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5578 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5579 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5582 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5583 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5586 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5587 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5589 if (VT == MVT::v8i8) {
5590 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5591 if (NewOp.getNode())
5598 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5599 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5600 SDValue Lane = Op.getOperand(2);
5601 if (!isa<ConstantSDNode>(Lane))
5607 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5608 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5609 SDValue Lane = Op.getOperand(1);
5610 if (!isa<ConstantSDNode>(Lane))
5613 SDValue Vec = Op.getOperand(0);
5614 if (Op.getValueType() == MVT::i32 &&
5615 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5617 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5623 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5624 // The only time a CONCAT_VECTORS operation can have legal types is when
5625 // two 64-bit vectors are concatenated to a 128-bit vector.
5626 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5627 "unexpected CONCAT_VECTORS");
5629 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5630 SDValue Op0 = Op.getOperand(0);
5631 SDValue Op1 = Op.getOperand(1);
5632 if (Op0.getOpcode() != ISD::UNDEF)
5633 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5634 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5635 DAG.getIntPtrConstant(0));
5636 if (Op1.getOpcode() != ISD::UNDEF)
5637 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5638 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5639 DAG.getIntPtrConstant(1));
5640 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5643 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5644 /// element has been zero/sign-extended, depending on the isSigned parameter,
5645 /// from an integer type half its size.
5646 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5648 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5649 EVT VT = N->getValueType(0);
5650 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5651 SDNode *BVN = N->getOperand(0).getNode();
5652 if (BVN->getValueType(0) != MVT::v4i32 ||
5653 BVN->getOpcode() != ISD::BUILD_VECTOR)
5655 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5656 unsigned HiElt = 1 - LoElt;
5657 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5658 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5659 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5660 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5661 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5664 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5665 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5668 if (Hi0->isNullValue() && Hi1->isNullValue())
5674 if (N->getOpcode() != ISD::BUILD_VECTOR)
5677 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5678 SDNode *Elt = N->getOperand(i).getNode();
5679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5680 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5681 unsigned HalfSize = EltSize / 2;
5683 if (!isIntN(HalfSize, C->getSExtValue()))
5686 if (!isUIntN(HalfSize, C->getZExtValue()))
5697 /// isSignExtended - Check if a node is a vector value that is sign-extended
5698 /// or a constant BUILD_VECTOR with sign-extended elements.
5699 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5700 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5702 if (isExtendedBUILD_VECTOR(N, DAG, true))
5707 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5708 /// or a constant BUILD_VECTOR with zero-extended elements.
5709 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5710 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5712 if (isExtendedBUILD_VECTOR(N, DAG, false))
5717 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5718 if (OrigVT.getSizeInBits() >= 64)
5721 assert(OrigVT.isSimple() && "Expecting a simple value type");
5723 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5724 switch (OrigSimpleTy) {
5725 default: llvm_unreachable("Unexpected Vector Type");
5734 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5735 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5736 /// We insert the required extension here to get the vector to fill a D register.
5737 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5740 unsigned ExtOpcode) {
5741 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5742 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5743 // 64-bits we need to insert a new extension so that it will be 64-bits.
5744 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5745 if (OrigTy.getSizeInBits() >= 64)
5748 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5749 EVT NewVT = getExtensionTo64Bits(OrigTy);
5751 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5754 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5755 /// does not do any sign/zero extension. If the original vector is less
5756 /// than 64 bits, an appropriate extension will be added after the load to
5757 /// reach a total size of 64 bits. We have to add the extension separately
5758 /// because ARM does not have a sign/zero extending load for vectors.
5759 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5760 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5762 // The load already has the right type.
5763 if (ExtendedTy == LD->getMemoryVT())
5764 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5765 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5766 LD->isNonTemporal(), LD->isInvariant(),
5767 LD->getAlignment());
5769 // We need to create a zextload/sextload. We cannot just create a load
5770 // followed by a zext/zext node because LowerMUL is also run during normal
5771 // operation legalization where we can't create illegal types.
5772 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5773 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5774 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5775 LD->isNonTemporal(), LD->getAlignment());
5778 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5779 /// extending load, or BUILD_VECTOR with extended elements, return the
5780 /// unextended value. The unextended vector should be 64 bits so that it can
5781 /// be used as an operand to a VMULL instruction. If the original vector size
5782 /// before extension is less than 64 bits we add a an extension to resize
5783 /// the vector to 64 bits.
5784 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5785 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5786 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5787 N->getOperand(0)->getValueType(0),
5791 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5792 return SkipLoadExtensionForVMULL(LD, DAG);
5794 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5795 // have been legalized as a BITCAST from v4i32.
5796 if (N->getOpcode() == ISD::BITCAST) {
5797 SDNode *BVN = N->getOperand(0).getNode();
5798 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5799 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5800 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5801 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5802 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5804 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5805 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5806 EVT VT = N->getValueType(0);
5807 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5808 unsigned NumElts = VT.getVectorNumElements();
5809 MVT TruncVT = MVT::getIntegerVT(EltSize);
5810 SmallVector<SDValue, 8> Ops;
5811 for (unsigned i = 0; i != NumElts; ++i) {
5812 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5813 const APInt &CInt = C->getAPIntValue();
5814 // Element types smaller than 32 bits are not legal, so use i32 elements.
5815 // The values are implicitly truncated so sext vs. zext doesn't matter.
5816 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5818 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5819 MVT::getVectorVT(TruncVT, NumElts), Ops);
5822 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5823 unsigned Opcode = N->getOpcode();
5824 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5825 SDNode *N0 = N->getOperand(0).getNode();
5826 SDNode *N1 = N->getOperand(1).getNode();
5827 return N0->hasOneUse() && N1->hasOneUse() &&
5828 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5833 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5834 unsigned Opcode = N->getOpcode();
5835 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5836 SDNode *N0 = N->getOperand(0).getNode();
5837 SDNode *N1 = N->getOperand(1).getNode();
5838 return N0->hasOneUse() && N1->hasOneUse() &&
5839 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5844 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5845 // Multiplications are only custom-lowered for 128-bit vectors so that
5846 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5847 EVT VT = Op.getValueType();
5848 assert(VT.is128BitVector() && VT.isInteger() &&
5849 "unexpected type for custom-lowering ISD::MUL");
5850 SDNode *N0 = Op.getOperand(0).getNode();
5851 SDNode *N1 = Op.getOperand(1).getNode();
5852 unsigned NewOpc = 0;
5854 bool isN0SExt = isSignExtended(N0, DAG);
5855 bool isN1SExt = isSignExtended(N1, DAG);
5856 if (isN0SExt && isN1SExt)
5857 NewOpc = ARMISD::VMULLs;
5859 bool isN0ZExt = isZeroExtended(N0, DAG);
5860 bool isN1ZExt = isZeroExtended(N1, DAG);
5861 if (isN0ZExt && isN1ZExt)
5862 NewOpc = ARMISD::VMULLu;
5863 else if (isN1SExt || isN1ZExt) {
5864 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5865 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5866 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5867 NewOpc = ARMISD::VMULLs;
5869 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5870 NewOpc = ARMISD::VMULLu;
5872 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5874 NewOpc = ARMISD::VMULLu;
5880 if (VT == MVT::v2i64)
5881 // Fall through to expand this. It is not legal.
5884 // Other vector multiplications are legal.
5889 // Legalize to a VMULL instruction.
5892 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5894 Op0 = SkipExtensionForVMULL(N0, DAG);
5895 assert(Op0.getValueType().is64BitVector() &&
5896 Op1.getValueType().is64BitVector() &&
5897 "unexpected types for extended operands to VMULL");
5898 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5901 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5902 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5909 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5910 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5911 EVT Op1VT = Op1.getValueType();
5912 return DAG.getNode(N0->getOpcode(), DL, VT,
5913 DAG.getNode(NewOpc, DL, VT,
5914 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5915 DAG.getNode(NewOpc, DL, VT,
5916 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5920 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5922 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5923 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5924 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5925 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5926 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5927 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5928 // Get reciprocal estimate.
5929 // float4 recip = vrecpeq_f32(yf);
5930 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5931 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5932 // Because char has a smaller range than uchar, we can actually get away
5933 // without any newton steps. This requires that we use a weird bias
5934 // of 0xb000, however (again, this has been exhaustively tested).
5935 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5936 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5937 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5938 Y = DAG.getConstant(0xb000, MVT::i32);
5939 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5940 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5941 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5942 // Convert back to short.
5943 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5944 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5949 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5951 // Convert to float.
5952 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5953 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5954 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5955 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5956 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5957 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5959 // Use reciprocal estimate and one refinement step.
5960 // float4 recip = vrecpeq_f32(yf);
5961 // recip *= vrecpsq_f32(yf, recip);
5962 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5963 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5964 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5965 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5967 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5968 // Because short has a smaller range than ushort, we can actually get away
5969 // with only a single newton step. This requires that we use a weird bias
5970 // of 89, however (again, this has been exhaustively tested).
5971 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5972 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5973 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5974 N1 = DAG.getConstant(0x89, MVT::i32);
5975 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5976 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5977 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5978 // Convert back to integer and return.
5979 // return vmovn_s32(vcvt_s32_f32(result));
5980 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5981 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5985 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5986 EVT VT = Op.getValueType();
5987 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5988 "unexpected type for custom-lowering ISD::SDIV");
5991 SDValue N0 = Op.getOperand(0);
5992 SDValue N1 = Op.getOperand(1);
5995 if (VT == MVT::v8i8) {
5996 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5997 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5999 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6000 DAG.getIntPtrConstant(4));
6001 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6002 DAG.getIntPtrConstant(4));
6003 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6004 DAG.getIntPtrConstant(0));
6005 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6006 DAG.getIntPtrConstant(0));
6008 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6009 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6011 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6012 N0 = LowerCONCAT_VECTORS(N0, DAG);
6014 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6017 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6020 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6021 EVT VT = Op.getValueType();
6022 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6023 "unexpected type for custom-lowering ISD::UDIV");
6026 SDValue N0 = Op.getOperand(0);
6027 SDValue N1 = Op.getOperand(1);
6030 if (VT == MVT::v8i8) {
6031 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6032 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6034 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6035 DAG.getIntPtrConstant(4));
6036 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6037 DAG.getIntPtrConstant(4));
6038 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6039 DAG.getIntPtrConstant(0));
6040 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6041 DAG.getIntPtrConstant(0));
6043 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6044 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6046 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6047 N0 = LowerCONCAT_VECTORS(N0, DAG);
6049 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6050 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6055 // v4i16 sdiv ... Convert to float.
6056 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6057 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6058 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6059 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6060 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6061 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6063 // Use reciprocal estimate and two refinement steps.
6064 // float4 recip = vrecpeq_f32(yf);
6065 // recip *= vrecpsq_f32(yf, recip);
6066 // recip *= vrecpsq_f32(yf, recip);
6067 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6068 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6069 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6070 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6072 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6073 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6074 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6076 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6077 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6078 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6079 // and that it will never cause us to return an answer too large).
6080 // float4 result = as_float4(as_int4(xf*recip) + 2);
6081 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6082 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6083 N1 = DAG.getConstant(2, MVT::i32);
6084 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6085 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6086 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6087 // Convert back to integer and return.
6088 // return vmovn_u32(vcvt_s32_f32(result));
6089 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6090 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6094 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6095 EVT VT = Op.getNode()->getValueType(0);
6096 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6099 bool ExtraOp = false;
6100 switch (Op.getOpcode()) {
6101 default: llvm_unreachable("Invalid code");
6102 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6103 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6104 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6105 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6109 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6111 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6112 Op.getOperand(1), Op.getOperand(2));
6115 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6116 assert(Subtarget->isTargetDarwin());
6118 // For iOS, we want to call an alternative entry point: __sincos_stret,
6119 // return values are passed via sret.
6121 SDValue Arg = Op.getOperand(0);
6122 EVT ArgVT = Arg.getValueType();
6123 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6125 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6128 // Pair of floats / doubles used to pass the result.
6129 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6131 // Create stack object for sret.
6132 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6133 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6134 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6135 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6141 Entry.Ty = RetTy->getPointerTo();
6142 Entry.isSExt = false;
6143 Entry.isZExt = false;
6144 Entry.isSRet = true;
6145 Args.push_back(Entry);
6149 Entry.isSExt = false;
6150 Entry.isZExt = false;
6151 Args.push_back(Entry);
6153 const char *LibcallName = (ArgVT == MVT::f64)
6154 ? "__sincos_stret" : "__sincosf_stret";
6155 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6157 TargetLowering::CallLoweringInfo CLI(DAG);
6158 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6159 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6161 .setDiscardResult();
6163 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6165 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6166 MachinePointerInfo(), false, false, false, 0);
6168 // Address of cos field.
6169 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6170 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6171 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6172 MachinePointerInfo(), false, false, false, 0);
6174 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6175 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6176 LoadSin.getValue(0), LoadCos.getValue(0));
6179 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6180 // Monotonic load/store is legal for all targets
6181 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6184 // Acquire/Release load/store is not legal for targets without a
6185 // dmb or equivalent available.
6189 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6190 SmallVectorImpl<SDValue> &Results,
6192 const ARMSubtarget *Subtarget) {
6194 SDValue Cycles32, OutChain;
6196 if (Subtarget->hasPerfMon()) {
6197 // Under Power Management extensions, the cycle-count is:
6198 // mrc p15, #0, <Rt>, c9, c13, #0
6199 SDValue Ops[] = { N->getOperand(0), // Chain
6200 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6201 DAG.getConstant(15, MVT::i32),
6202 DAG.getConstant(0, MVT::i32),
6203 DAG.getConstant(9, MVT::i32),
6204 DAG.getConstant(13, MVT::i32),
6205 DAG.getConstant(0, MVT::i32)
6208 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6209 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6210 OutChain = Cycles32.getValue(1);
6212 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6213 // there are older ARM CPUs that have implementation-specific ways of
6214 // obtaining this information (FIXME!).
6215 Cycles32 = DAG.getConstant(0, MVT::i32);
6216 OutChain = DAG.getEntryNode();
6220 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6221 Cycles32, DAG.getConstant(0, MVT::i32));
6222 Results.push_back(Cycles64);
6223 Results.push_back(OutChain);
6226 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6227 switch (Op.getOpcode()) {
6228 default: llvm_unreachable("Don't know how to custom lower this!");
6229 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6230 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6231 case ISD::GlobalAddress:
6232 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6233 default: llvm_unreachable("unknown object format");
6235 return LowerGlobalAddressWindows(Op, DAG);
6237 return LowerGlobalAddressELF(Op, DAG);
6239 return LowerGlobalAddressDarwin(Op, DAG);
6241 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6242 case ISD::SELECT: return LowerSELECT(Op, DAG);
6243 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6244 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6245 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6246 case ISD::VASTART: return LowerVASTART(Op, DAG);
6247 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6248 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6249 case ISD::SINT_TO_FP:
6250 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6251 case ISD::FP_TO_SINT:
6252 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6253 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6254 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6255 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6256 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6257 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6258 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6259 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6261 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6264 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6265 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6266 case ISD::SRL_PARTS:
6267 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6268 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6269 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6270 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6271 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6272 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6273 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6274 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6275 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6276 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6277 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6278 case ISD::MUL: return LowerMUL(Op, DAG);
6279 case ISD::SDIV: return LowerSDIV(Op, DAG);
6280 case ISD::UDIV: return LowerUDIV(Op, DAG);
6284 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6289 return LowerXALUO(Op, DAG);
6290 case ISD::ATOMIC_LOAD:
6291 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6292 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6294 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6295 case ISD::DYNAMIC_STACKALLOC:
6296 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6297 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6298 llvm_unreachable("Don't know how to custom lower this!");
6302 /// ReplaceNodeResults - Replace the results of node with an illegal result
6303 /// type with new values built out of custom code.
6304 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6305 SmallVectorImpl<SDValue>&Results,
6306 SelectionDAG &DAG) const {
6308 switch (N->getOpcode()) {
6310 llvm_unreachable("Don't know how to custom expand this!");
6312 Res = ExpandBITCAST(N, DAG);
6316 Res = Expand64BitShift(N, DAG, Subtarget);
6318 case ISD::READCYCLECOUNTER:
6319 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6323 Results.push_back(Res);
6326 //===----------------------------------------------------------------------===//
6327 // ARM Scheduler Hooks
6328 //===----------------------------------------------------------------------===//
6330 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6331 /// registers the function context.
6332 void ARMTargetLowering::
6333 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6334 MachineBasicBlock *DispatchBB, int FI) const {
6335 const TargetInstrInfo *TII =
6336 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6337 DebugLoc dl = MI->getDebugLoc();
6338 MachineFunction *MF = MBB->getParent();
6339 MachineRegisterInfo *MRI = &MF->getRegInfo();
6340 MachineConstantPool *MCP = MF->getConstantPool();
6341 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6342 const Function *F = MF->getFunction();
6344 bool isThumb = Subtarget->isThumb();
6345 bool isThumb2 = Subtarget->isThumb2();
6347 unsigned PCLabelId = AFI->createPICLabelUId();
6348 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6349 ARMConstantPoolValue *CPV =
6350 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6351 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6353 const TargetRegisterClass *TRC = isThumb ?
6354 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6355 (const TargetRegisterClass*)&ARM::GPRRegClass;
6357 // Grab constant pool and fixed stack memory operands.
6358 MachineMemOperand *CPMMO =
6359 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6360 MachineMemOperand::MOLoad, 4, 4);
6362 MachineMemOperand *FIMMOSt =
6363 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6364 MachineMemOperand::MOStore, 4, 4);
6366 // Load the address of the dispatch MBB into the jump buffer.
6368 // Incoming value: jbuf
6369 // ldr.n r5, LCPI1_1
6372 // str r5, [$jbuf, #+4] ; &jbuf[1]
6373 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6374 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6375 .addConstantPoolIndex(CPI)
6376 .addMemOperand(CPMMO));
6377 // Set the low bit because of thumb mode.
6378 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6380 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6381 .addReg(NewVReg1, RegState::Kill)
6383 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6384 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6385 .addReg(NewVReg2, RegState::Kill)
6387 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6388 .addReg(NewVReg3, RegState::Kill)
6390 .addImm(36) // &jbuf[1] :: pc
6391 .addMemOperand(FIMMOSt));
6392 } else if (isThumb) {
6393 // Incoming value: jbuf
6394 // ldr.n r1, LCPI1_4
6398 // add r2, $jbuf, #+4 ; &jbuf[1]
6400 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6401 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6402 .addConstantPoolIndex(CPI)
6403 .addMemOperand(CPMMO));
6404 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6405 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6406 .addReg(NewVReg1, RegState::Kill)
6408 // Set the low bit because of thumb mode.
6409 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6410 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6411 .addReg(ARM::CPSR, RegState::Define)
6413 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6414 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6415 .addReg(ARM::CPSR, RegState::Define)
6416 .addReg(NewVReg2, RegState::Kill)
6417 .addReg(NewVReg3, RegState::Kill));
6418 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6419 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6421 .addImm(36)); // &jbuf[1] :: pc
6422 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6423 .addReg(NewVReg4, RegState::Kill)
6424 .addReg(NewVReg5, RegState::Kill)
6426 .addMemOperand(FIMMOSt));
6428 // Incoming value: jbuf
6431 // str r1, [$jbuf, #+4] ; &jbuf[1]
6432 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6433 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6434 .addConstantPoolIndex(CPI)
6436 .addMemOperand(CPMMO));
6437 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6438 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6439 .addReg(NewVReg1, RegState::Kill)
6440 .addImm(PCLabelId));
6441 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6442 .addReg(NewVReg2, RegState::Kill)
6444 .addImm(36) // &jbuf[1] :: pc
6445 .addMemOperand(FIMMOSt));
6449 MachineBasicBlock *ARMTargetLowering::
6450 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6451 const TargetInstrInfo *TII =
6452 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6453 DebugLoc dl = MI->getDebugLoc();
6454 MachineFunction *MF = MBB->getParent();
6455 MachineRegisterInfo *MRI = &MF->getRegInfo();
6456 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6457 MachineFrameInfo *MFI = MF->getFrameInfo();
6458 int FI = MFI->getFunctionContextIndex();
6460 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6461 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6462 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6464 // Get a mapping of the call site numbers to all of the landing pads they're
6466 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6467 unsigned MaxCSNum = 0;
6468 MachineModuleInfo &MMI = MF->getMMI();
6469 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6471 if (!BB->isLandingPad()) continue;
6473 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6475 for (MachineBasicBlock::iterator
6476 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6477 if (!II->isEHLabel()) continue;
6479 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6480 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6482 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6483 for (SmallVectorImpl<unsigned>::iterator
6484 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6485 CSI != CSE; ++CSI) {
6486 CallSiteNumToLPad[*CSI].push_back(BB);
6487 MaxCSNum = std::max(MaxCSNum, *CSI);
6493 // Get an ordered list of the machine basic blocks for the jump table.
6494 std::vector<MachineBasicBlock*> LPadList;
6495 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6496 LPadList.reserve(CallSiteNumToLPad.size());
6497 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6498 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6499 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6500 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6501 LPadList.push_back(*II);
6502 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6506 assert(!LPadList.empty() &&
6507 "No landing pad destinations for the dispatch jump table!");
6509 // Create the jump table and associated information.
6510 MachineJumpTableInfo *JTI =
6511 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6512 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6513 unsigned UId = AFI->createJumpTableUId();
6514 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6516 // Create the MBBs for the dispatch code.
6518 // Shove the dispatch's address into the return slot in the function context.
6519 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6520 DispatchBB->setIsLandingPad();
6522 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6523 unsigned trap_opcode;
6524 if (Subtarget->isThumb())
6525 trap_opcode = ARM::tTRAP;
6527 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6529 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6530 DispatchBB->addSuccessor(TrapBB);
6532 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6533 DispatchBB->addSuccessor(DispContBB);
6536 MF->insert(MF->end(), DispatchBB);
6537 MF->insert(MF->end(), DispContBB);
6538 MF->insert(MF->end(), TrapBB);
6540 // Insert code into the entry block that creates and registers the function
6542 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6544 MachineMemOperand *FIMMOLd =
6545 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6546 MachineMemOperand::MOLoad |
6547 MachineMemOperand::MOVolatile, 4, 4);
6549 MachineInstrBuilder MIB;
6550 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6552 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6553 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6555 // Add a register mask with no preserved registers. This results in all
6556 // registers being marked as clobbered.
6557 MIB.addRegMask(RI.getNoPreservedMask());
6559 unsigned NumLPads = LPadList.size();
6560 if (Subtarget->isThumb2()) {
6561 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6562 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6565 .addMemOperand(FIMMOLd));
6567 if (NumLPads < 256) {
6568 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6570 .addImm(LPadList.size()));
6572 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6573 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6574 .addImm(NumLPads & 0xFFFF));
6576 unsigned VReg2 = VReg1;
6577 if ((NumLPads & 0xFFFF0000) != 0) {
6578 VReg2 = MRI->createVirtualRegister(TRC);
6579 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6581 .addImm(NumLPads >> 16));
6584 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6589 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6594 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6595 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6596 .addJumpTableIndex(MJTI)
6599 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6602 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6603 .addReg(NewVReg3, RegState::Kill)
6605 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6607 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6608 .addReg(NewVReg4, RegState::Kill)
6610 .addJumpTableIndex(MJTI)
6612 } else if (Subtarget->isThumb()) {
6613 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6614 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6617 .addMemOperand(FIMMOLd));
6619 if (NumLPads < 256) {
6620 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6624 MachineConstantPool *ConstantPool = MF->getConstantPool();
6625 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6626 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6628 // MachineConstantPool wants an explicit alignment.
6629 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6631 Align = getDataLayout()->getTypeAllocSize(C->getType());
6632 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6634 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6635 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6636 .addReg(VReg1, RegState::Define)
6637 .addConstantPoolIndex(Idx));
6638 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6643 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6648 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6649 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6650 .addReg(ARM::CPSR, RegState::Define)
6654 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6655 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6656 .addJumpTableIndex(MJTI)
6659 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6660 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6661 .addReg(ARM::CPSR, RegState::Define)
6662 .addReg(NewVReg2, RegState::Kill)
6665 MachineMemOperand *JTMMOLd =
6666 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6667 MachineMemOperand::MOLoad, 4, 4);
6669 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6670 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6671 .addReg(NewVReg4, RegState::Kill)
6673 .addMemOperand(JTMMOLd));
6675 unsigned NewVReg6 = NewVReg5;
6676 if (RelocM == Reloc::PIC_) {
6677 NewVReg6 = MRI->createVirtualRegister(TRC);
6678 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6679 .addReg(ARM::CPSR, RegState::Define)
6680 .addReg(NewVReg5, RegState::Kill)
6684 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6685 .addReg(NewVReg6, RegState::Kill)
6686 .addJumpTableIndex(MJTI)
6689 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6690 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6693 .addMemOperand(FIMMOLd));
6695 if (NumLPads < 256) {
6696 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6699 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6700 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6701 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6702 .addImm(NumLPads & 0xFFFF));
6704 unsigned VReg2 = VReg1;
6705 if ((NumLPads & 0xFFFF0000) != 0) {
6706 VReg2 = MRI->createVirtualRegister(TRC);
6707 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6709 .addImm(NumLPads >> 16));
6712 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6716 MachineConstantPool *ConstantPool = MF->getConstantPool();
6717 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6718 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6720 // MachineConstantPool wants an explicit alignment.
6721 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6723 Align = getDataLayout()->getTypeAllocSize(C->getType());
6724 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6726 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6727 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6728 .addReg(VReg1, RegState::Define)
6729 .addConstantPoolIndex(Idx)
6731 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6733 .addReg(VReg1, RegState::Kill));
6736 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6741 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6743 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6745 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6746 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6747 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6748 .addJumpTableIndex(MJTI)
6751 MachineMemOperand *JTMMOLd =
6752 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6753 MachineMemOperand::MOLoad, 4, 4);
6754 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6756 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6757 .addReg(NewVReg3, RegState::Kill)
6760 .addMemOperand(JTMMOLd));
6762 if (RelocM == Reloc::PIC_) {
6763 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6764 .addReg(NewVReg5, RegState::Kill)
6766 .addJumpTableIndex(MJTI)
6769 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6770 .addReg(NewVReg5, RegState::Kill)
6771 .addJumpTableIndex(MJTI)
6776 // Add the jump table entries as successors to the MBB.
6777 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6778 for (std::vector<MachineBasicBlock*>::iterator
6779 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6780 MachineBasicBlock *CurMBB = *I;
6781 if (SeenMBBs.insert(CurMBB))
6782 DispContBB->addSuccessor(CurMBB);
6785 // N.B. the order the invoke BBs are processed in doesn't matter here.
6786 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6787 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6788 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6789 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6790 MachineBasicBlock *BB = *I;
6792 // Remove the landing pad successor from the invoke block and replace it
6793 // with the new dispatch block.
6794 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6796 while (!Successors.empty()) {
6797 MachineBasicBlock *SMBB = Successors.pop_back_val();
6798 if (SMBB->isLandingPad()) {
6799 BB->removeSuccessor(SMBB);
6800 MBBLPads.push_back(SMBB);
6804 BB->addSuccessor(DispatchBB);
6806 // Find the invoke call and mark all of the callee-saved registers as
6807 // 'implicit defined' so that they're spilled. This prevents code from
6808 // moving instructions to before the EH block, where they will never be
6810 for (MachineBasicBlock::reverse_iterator
6811 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6812 if (!II->isCall()) continue;
6814 DenseMap<unsigned, bool> DefRegs;
6815 for (MachineInstr::mop_iterator
6816 OI = II->operands_begin(), OE = II->operands_end();
6818 if (!OI->isReg()) continue;
6819 DefRegs[OI->getReg()] = true;
6822 MachineInstrBuilder MIB(*MF, &*II);
6824 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6825 unsigned Reg = SavedRegs[i];
6826 if (Subtarget->isThumb2() &&
6827 !ARM::tGPRRegClass.contains(Reg) &&
6828 !ARM::hGPRRegClass.contains(Reg))
6830 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6832 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6835 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6842 // Mark all former landing pads as non-landing pads. The dispatch is the only
6844 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6845 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6846 (*I)->setIsLandingPad(false);
6848 // The instruction is gone now.
6849 MI->eraseFromParent();
6855 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6856 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6857 E = MBB->succ_end(); I != E; ++I)
6860 llvm_unreachable("Expecting a BB with two successors!");
6863 /// Return the load opcode for a given load size. If load size >= 8,
6864 /// neon opcode will be returned.
6865 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6867 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6868 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6870 return LdSize == 4 ? ARM::tLDRi
6871 : LdSize == 2 ? ARM::tLDRHi
6872 : LdSize == 1 ? ARM::tLDRBi : 0;
6874 return LdSize == 4 ? ARM::t2LDR_POST
6875 : LdSize == 2 ? ARM::t2LDRH_POST
6876 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6877 return LdSize == 4 ? ARM::LDR_POST_IMM
6878 : LdSize == 2 ? ARM::LDRH_POST
6879 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6882 /// Return the store opcode for a given store size. If store size >= 8,
6883 /// neon opcode will be returned.
6884 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6886 return StSize == 16 ? ARM::VST1q32wb_fixed
6887 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6889 return StSize == 4 ? ARM::tSTRi
6890 : StSize == 2 ? ARM::tSTRHi
6891 : StSize == 1 ? ARM::tSTRBi : 0;
6893 return StSize == 4 ? ARM::t2STR_POST
6894 : StSize == 2 ? ARM::t2STRH_POST
6895 : StSize == 1 ? ARM::t2STRB_POST : 0;
6896 return StSize == 4 ? ARM::STR_POST_IMM
6897 : StSize == 2 ? ARM::STRH_POST
6898 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6901 /// Emit a post-increment load operation with given size. The instructions
6902 /// will be added to BB at Pos.
6903 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6904 const TargetInstrInfo *TII, DebugLoc dl,
6905 unsigned LdSize, unsigned Data, unsigned AddrIn,
6906 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6907 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6908 assert(LdOpc != 0 && "Should have a load opcode");
6910 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6911 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6913 } else if (IsThumb1) {
6914 // load + update AddrIn
6915 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6916 .addReg(AddrIn).addImm(0));
6917 MachineInstrBuilder MIB =
6918 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6919 MIB = AddDefaultT1CC(MIB);
6920 MIB.addReg(AddrIn).addImm(LdSize);
6921 AddDefaultPred(MIB);
6922 } else if (IsThumb2) {
6923 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6924 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6927 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6928 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6929 .addReg(0).addImm(LdSize));
6933 /// Emit a post-increment store operation with given size. The instructions
6934 /// will be added to BB at Pos.
6935 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6936 const TargetInstrInfo *TII, DebugLoc dl,
6937 unsigned StSize, unsigned Data, unsigned AddrIn,
6938 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6939 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6940 assert(StOpc != 0 && "Should have a store opcode");
6942 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6943 .addReg(AddrIn).addImm(0).addReg(Data));
6944 } else if (IsThumb1) {
6945 // store + update AddrIn
6946 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6947 .addReg(AddrIn).addImm(0));
6948 MachineInstrBuilder MIB =
6949 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6950 MIB = AddDefaultT1CC(MIB);
6951 MIB.addReg(AddrIn).addImm(StSize);
6952 AddDefaultPred(MIB);
6953 } else if (IsThumb2) {
6954 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6955 .addReg(Data).addReg(AddrIn).addImm(StSize));
6957 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6958 .addReg(Data).addReg(AddrIn).addReg(0)
6964 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6965 MachineBasicBlock *BB) const {
6966 // This pseudo instruction has 3 operands: dst, src, size
6967 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6968 // Otherwise, we will generate unrolled scalar copies.
6969 const TargetInstrInfo *TII =
6970 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6971 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6972 MachineFunction::iterator It = BB;
6975 unsigned dest = MI->getOperand(0).getReg();
6976 unsigned src = MI->getOperand(1).getReg();
6977 unsigned SizeVal = MI->getOperand(2).getImm();
6978 unsigned Align = MI->getOperand(3).getImm();
6979 DebugLoc dl = MI->getDebugLoc();
6981 MachineFunction *MF = BB->getParent();
6982 MachineRegisterInfo &MRI = MF->getRegInfo();
6983 unsigned UnitSize = 0;
6984 const TargetRegisterClass *TRC = nullptr;
6985 const TargetRegisterClass *VecTRC = nullptr;
6987 bool IsThumb1 = Subtarget->isThumb1Only();
6988 bool IsThumb2 = Subtarget->isThumb2();
6992 } else if (Align & 2) {
6995 // Check whether we can use NEON instructions.
6996 if (!MF->getFunction()->getAttributes().
6997 hasAttribute(AttributeSet::FunctionIndex,
6998 Attribute::NoImplicitFloat) &&
6999 Subtarget->hasNEON()) {
7000 if ((Align % 16 == 0) && SizeVal >= 16)
7002 else if ((Align % 8 == 0) && SizeVal >= 8)
7005 // Can't use NEON instructions.
7010 // Select the correct opcode and register class for unit size load/store
7011 bool IsNeon = UnitSize >= 8;
7012 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7013 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7015 VecTRC = UnitSize == 16
7016 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7018 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7021 unsigned BytesLeft = SizeVal % UnitSize;
7022 unsigned LoopSize = SizeVal - BytesLeft;
7024 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7025 // Use LDR and STR to copy.
7026 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7027 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7028 unsigned srcIn = src;
7029 unsigned destIn = dest;
7030 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7031 unsigned srcOut = MRI.createVirtualRegister(TRC);
7032 unsigned destOut = MRI.createVirtualRegister(TRC);
7033 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7034 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7035 IsThumb1, IsThumb2);
7036 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7037 IsThumb1, IsThumb2);
7042 // Handle the leftover bytes with LDRB and STRB.
7043 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7044 // [destOut] = STRB_POST(scratch, destIn, 1)
7045 for (unsigned i = 0; i < BytesLeft; i++) {
7046 unsigned srcOut = MRI.createVirtualRegister(TRC);
7047 unsigned destOut = MRI.createVirtualRegister(TRC);
7048 unsigned scratch = MRI.createVirtualRegister(TRC);
7049 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7050 IsThumb1, IsThumb2);
7051 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7052 IsThumb1, IsThumb2);
7056 MI->eraseFromParent(); // The instruction is gone now.
7060 // Expand the pseudo op to a loop.
7063 // movw varEnd, # --> with thumb2
7065 // ldrcp varEnd, idx --> without thumb2
7066 // fallthrough --> loopMBB
7068 // PHI varPhi, varEnd, varLoop
7069 // PHI srcPhi, src, srcLoop
7070 // PHI destPhi, dst, destLoop
7071 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7072 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7073 // subs varLoop, varPhi, #UnitSize
7075 // fallthrough --> exitMBB
7077 // epilogue to handle left-over bytes
7078 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7079 // [destOut] = STRB_POST(scratch, destLoop, 1)
7080 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7081 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7082 MF->insert(It, loopMBB);
7083 MF->insert(It, exitMBB);
7085 // Transfer the remainder of BB and its successor edges to exitMBB.
7086 exitMBB->splice(exitMBB->begin(), BB,
7087 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7088 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7090 // Load an immediate to varEnd.
7091 unsigned varEnd = MRI.createVirtualRegister(TRC);
7093 unsigned Vtmp = varEnd;
7094 if ((LoopSize & 0xFFFF0000) != 0)
7095 Vtmp = MRI.createVirtualRegister(TRC);
7096 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7097 .addImm(LoopSize & 0xFFFF));
7099 if ((LoopSize & 0xFFFF0000) != 0)
7100 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7101 .addReg(Vtmp).addImm(LoopSize >> 16));
7103 MachineConstantPool *ConstantPool = MF->getConstantPool();
7104 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7105 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7107 // MachineConstantPool wants an explicit alignment.
7108 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7110 Align = getDataLayout()->getTypeAllocSize(C->getType());
7111 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7114 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7115 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7117 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7118 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7120 BB->addSuccessor(loopMBB);
7122 // Generate the loop body:
7123 // varPhi = PHI(varLoop, varEnd)
7124 // srcPhi = PHI(srcLoop, src)
7125 // destPhi = PHI(destLoop, dst)
7126 MachineBasicBlock *entryBB = BB;
7128 unsigned varLoop = MRI.createVirtualRegister(TRC);
7129 unsigned varPhi = MRI.createVirtualRegister(TRC);
7130 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7131 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7132 unsigned destLoop = MRI.createVirtualRegister(TRC);
7133 unsigned destPhi = MRI.createVirtualRegister(TRC);
7135 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7136 .addReg(varLoop).addMBB(loopMBB)
7137 .addReg(varEnd).addMBB(entryBB);
7138 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7139 .addReg(srcLoop).addMBB(loopMBB)
7140 .addReg(src).addMBB(entryBB);
7141 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7142 .addReg(destLoop).addMBB(loopMBB)
7143 .addReg(dest).addMBB(entryBB);
7145 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7146 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7147 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7148 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7149 IsThumb1, IsThumb2);
7150 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7151 IsThumb1, IsThumb2);
7153 // Decrement loop variable by UnitSize.
7155 MachineInstrBuilder MIB =
7156 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7157 MIB = AddDefaultT1CC(MIB);
7158 MIB.addReg(varPhi).addImm(UnitSize);
7159 AddDefaultPred(MIB);
7161 MachineInstrBuilder MIB =
7162 BuildMI(*BB, BB->end(), dl,
7163 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7164 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7165 MIB->getOperand(5).setReg(ARM::CPSR);
7166 MIB->getOperand(5).setIsDef(true);
7168 BuildMI(*BB, BB->end(), dl,
7169 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7170 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7172 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7173 BB->addSuccessor(loopMBB);
7174 BB->addSuccessor(exitMBB);
7176 // Add epilogue to handle BytesLeft.
7178 MachineInstr *StartOfExit = exitMBB->begin();
7180 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7181 // [destOut] = STRB_POST(scratch, destLoop, 1)
7182 unsigned srcIn = srcLoop;
7183 unsigned destIn = destLoop;
7184 for (unsigned i = 0; i < BytesLeft; i++) {
7185 unsigned srcOut = MRI.createVirtualRegister(TRC);
7186 unsigned destOut = MRI.createVirtualRegister(TRC);
7187 unsigned scratch = MRI.createVirtualRegister(TRC);
7188 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7189 IsThumb1, IsThumb2);
7190 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7191 IsThumb1, IsThumb2);
7196 MI->eraseFromParent(); // The instruction is gone now.
7201 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7202 MachineBasicBlock *MBB) const {
7203 const TargetMachine &TM = getTargetMachine();
7204 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7205 DebugLoc DL = MI->getDebugLoc();
7207 assert(Subtarget->isTargetWindows() &&
7208 "__chkstk is only supported on Windows");
7209 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7211 // __chkstk takes the number of words to allocate on the stack in R4, and
7212 // returns the stack adjustment in number of bytes in R4. This will not
7213 // clober any other registers (other than the obvious lr).
7215 // Although, technically, IP should be considered a register which may be
7216 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7217 // thumb-2 environment, so there is no interworking required. As a result, we
7218 // do not expect a veneer to be emitted by the linker, clobbering IP.
7220 // Each module receives its own copy of __chkstk, so no import thunk is
7221 // required, again, ensuring that IP is not clobbered.
7223 // Finally, although some linkers may theoretically provide a trampoline for
7224 // out of range calls (which is quite common due to a 32M range limitation of
7225 // branches for Thumb), we can generate the long-call version via
7226 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7229 switch (TM.getCodeModel()) {
7230 case CodeModel::Small:
7231 case CodeModel::Medium:
7232 case CodeModel::Default:
7233 case CodeModel::Kernel:
7234 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7235 .addImm((unsigned)ARMCC::AL).addReg(0)
7236 .addExternalSymbol("__chkstk")
7237 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7238 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7239 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7241 case CodeModel::Large:
7242 case CodeModel::JITDefault: {
7243 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7244 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7246 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7247 .addExternalSymbol("__chkstk");
7248 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7249 .addImm((unsigned)ARMCC::AL).addReg(0)
7250 .addReg(Reg, RegState::Kill)
7251 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7252 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7253 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7258 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7260 .addReg(ARM::SP).addReg(ARM::R4)));
7262 MI->eraseFromParent();
7267 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7268 MachineBasicBlock *BB) const {
7269 const TargetInstrInfo *TII =
7270 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7271 DebugLoc dl = MI->getDebugLoc();
7272 bool isThumb2 = Subtarget->isThumb2();
7273 switch (MI->getOpcode()) {
7276 llvm_unreachable("Unexpected instr type to insert");
7278 // The Thumb2 pre-indexed stores have the same MI operands, they just
7279 // define them differently in the .td files from the isel patterns, so
7280 // they need pseudos.
7281 case ARM::t2STR_preidx:
7282 MI->setDesc(TII->get(ARM::t2STR_PRE));
7284 case ARM::t2STRB_preidx:
7285 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7287 case ARM::t2STRH_preidx:
7288 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7291 case ARM::STRi_preidx:
7292 case ARM::STRBi_preidx: {
7293 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7294 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7295 // Decode the offset.
7296 unsigned Offset = MI->getOperand(4).getImm();
7297 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7298 Offset = ARM_AM::getAM2Offset(Offset);
7302 MachineMemOperand *MMO = *MI->memoperands_begin();
7303 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7304 .addOperand(MI->getOperand(0)) // Rn_wb
7305 .addOperand(MI->getOperand(1)) // Rt
7306 .addOperand(MI->getOperand(2)) // Rn
7307 .addImm(Offset) // offset (skip GPR==zero_reg)
7308 .addOperand(MI->getOperand(5)) // pred
7309 .addOperand(MI->getOperand(6))
7310 .addMemOperand(MMO);
7311 MI->eraseFromParent();
7314 case ARM::STRr_preidx:
7315 case ARM::STRBr_preidx:
7316 case ARM::STRH_preidx: {
7318 switch (MI->getOpcode()) {
7319 default: llvm_unreachable("unexpected opcode!");
7320 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7321 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7322 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7324 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7325 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7326 MIB.addOperand(MI->getOperand(i));
7327 MI->eraseFromParent();
7331 case ARM::tMOVCCr_pseudo: {
7332 // To "insert" a SELECT_CC instruction, we actually have to insert the
7333 // diamond control-flow pattern. The incoming instruction knows the
7334 // destination vreg to set, the condition code register to branch on, the
7335 // true/false values to select between, and a branch opcode to use.
7336 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7337 MachineFunction::iterator It = BB;
7343 // cmpTY ccX, r1, r2
7345 // fallthrough --> copy0MBB
7346 MachineBasicBlock *thisMBB = BB;
7347 MachineFunction *F = BB->getParent();
7348 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7349 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7350 F->insert(It, copy0MBB);
7351 F->insert(It, sinkMBB);
7353 // Transfer the remainder of BB and its successor edges to sinkMBB.
7354 sinkMBB->splice(sinkMBB->begin(), BB,
7355 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7356 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7358 BB->addSuccessor(copy0MBB);
7359 BB->addSuccessor(sinkMBB);
7361 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7362 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7365 // %FalseValue = ...
7366 // # fallthrough to sinkMBB
7369 // Update machine-CFG edges
7370 BB->addSuccessor(sinkMBB);
7373 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7376 BuildMI(*BB, BB->begin(), dl,
7377 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7378 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7379 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7381 MI->eraseFromParent(); // The pseudo instruction is gone now.
7386 case ARM::BCCZi64: {
7387 // If there is an unconditional branch to the other successor, remove it.
7388 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7390 // Compare both parts that make up the double comparison separately for
7392 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7394 unsigned LHS1 = MI->getOperand(1).getReg();
7395 unsigned LHS2 = MI->getOperand(2).getReg();
7397 AddDefaultPred(BuildMI(BB, dl,
7398 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7399 .addReg(LHS1).addImm(0));
7400 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7401 .addReg(LHS2).addImm(0)
7402 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7404 unsigned RHS1 = MI->getOperand(3).getReg();
7405 unsigned RHS2 = MI->getOperand(4).getReg();
7406 AddDefaultPred(BuildMI(BB, dl,
7407 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7408 .addReg(LHS1).addReg(RHS1));
7409 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7410 .addReg(LHS2).addReg(RHS2)
7411 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7414 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7415 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7416 if (MI->getOperand(0).getImm() == ARMCC::NE)
7417 std::swap(destMBB, exitMBB);
7419 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7420 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7422 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7424 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7426 MI->eraseFromParent(); // The pseudo instruction is gone now.
7430 case ARM::Int_eh_sjlj_setjmp:
7431 case ARM::Int_eh_sjlj_setjmp_nofp:
7432 case ARM::tInt_eh_sjlj_setjmp:
7433 case ARM::t2Int_eh_sjlj_setjmp:
7434 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7435 EmitSjLjDispatchBlock(MI, BB);
7440 // To insert an ABS instruction, we have to insert the
7441 // diamond control-flow pattern. The incoming instruction knows the
7442 // source vreg to test against 0, the destination vreg to set,
7443 // the condition code register to branch on, the
7444 // true/false values to select between, and a branch opcode to use.
7449 // BCC (branch to SinkBB if V0 >= 0)
7450 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7451 // SinkBB: V1 = PHI(V2, V3)
7452 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7453 MachineFunction::iterator BBI = BB;
7455 MachineFunction *Fn = BB->getParent();
7456 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7457 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7458 Fn->insert(BBI, RSBBB);
7459 Fn->insert(BBI, SinkBB);
7461 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7462 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7463 bool isThumb2 = Subtarget->isThumb2();
7464 MachineRegisterInfo &MRI = Fn->getRegInfo();
7465 // In Thumb mode S must not be specified if source register is the SP or
7466 // PC and if destination register is the SP, so restrict register class
7467 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7468 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7469 (const TargetRegisterClass*)&ARM::GPRRegClass);
7471 // Transfer the remainder of BB and its successor edges to sinkMBB.
7472 SinkBB->splice(SinkBB->begin(), BB,
7473 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7474 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7476 BB->addSuccessor(RSBBB);
7477 BB->addSuccessor(SinkBB);
7479 // fall through to SinkMBB
7480 RSBBB->addSuccessor(SinkBB);
7482 // insert a cmp at the end of BB
7483 AddDefaultPred(BuildMI(BB, dl,
7484 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7485 .addReg(ABSSrcReg).addImm(0));
7487 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7489 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7490 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7492 // insert rsbri in RSBBB
7493 // Note: BCC and rsbri will be converted into predicated rsbmi
7494 // by if-conversion pass
7495 BuildMI(*RSBBB, RSBBB->begin(), dl,
7496 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7497 .addReg(ABSSrcReg, RegState::Kill)
7498 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7500 // insert PHI in SinkBB,
7501 // reuse ABSDstReg to not change uses of ABS instruction
7502 BuildMI(*SinkBB, SinkBB->begin(), dl,
7503 TII->get(ARM::PHI), ABSDstReg)
7504 .addReg(NewRsbDstReg).addMBB(RSBBB)
7505 .addReg(ABSSrcReg).addMBB(BB);
7507 // remove ABS instruction
7508 MI->eraseFromParent();
7510 // return last added BB
7513 case ARM::COPY_STRUCT_BYVAL_I32:
7515 return EmitStructByval(MI, BB);
7516 case ARM::WIN__CHKSTK:
7517 return EmitLowered__chkstk(MI, BB);
7521 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7522 SDNode *Node) const {
7523 if (!MI->hasPostISelHook()) {
7524 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7525 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7529 const MCInstrDesc *MCID = &MI->getDesc();
7530 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7531 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7532 // operand is still set to noreg. If needed, set the optional operand's
7533 // register to CPSR, and remove the redundant implicit def.
7535 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7537 // Rename pseudo opcodes.
7538 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7540 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7541 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7542 MCID = &TII->get(NewOpc);
7544 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7545 "converted opcode should be the same except for cc_out");
7549 // Add the optional cc_out operand
7550 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7552 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7554 // Any ARM instruction that sets the 's' bit should specify an optional
7555 // "cc_out" operand in the last operand position.
7556 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7557 assert(!NewOpc && "Optional cc_out operand required");
7560 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7561 // since we already have an optional CPSR def.
7562 bool definesCPSR = false;
7563 bool deadCPSR = false;
7564 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7566 const MachineOperand &MO = MI->getOperand(i);
7567 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7571 MI->RemoveOperand(i);
7576 assert(!NewOpc && "Optional cc_out operand required");
7579 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7581 assert(!MI->getOperand(ccOutIdx).getReg() &&
7582 "expect uninitialized optional cc_out operand");
7586 // If this instruction was defined with an optional CPSR def and its dag node
7587 // had a live implicit CPSR def, then activate the optional CPSR def.
7588 MachineOperand &MO = MI->getOperand(ccOutIdx);
7589 MO.setReg(ARM::CPSR);
7593 //===----------------------------------------------------------------------===//
7594 // ARM Optimization Hooks
7595 //===----------------------------------------------------------------------===//
7597 // Helper function that checks if N is a null or all ones constant.
7598 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7599 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7602 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7605 // Return true if N is conditionally 0 or all ones.
7606 // Detects these expressions where cc is an i1 value:
7608 // (select cc 0, y) [AllOnes=0]
7609 // (select cc y, 0) [AllOnes=0]
7610 // (zext cc) [AllOnes=0]
7611 // (sext cc) [AllOnes=0/1]
7612 // (select cc -1, y) [AllOnes=1]
7613 // (select cc y, -1) [AllOnes=1]
7615 // Invert is set when N is the null/all ones constant when CC is false.
7616 // OtherOp is set to the alternative value of N.
7617 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7618 SDValue &CC, bool &Invert,
7620 SelectionDAG &DAG) {
7621 switch (N->getOpcode()) {
7622 default: return false;
7624 CC = N->getOperand(0);
7625 SDValue N1 = N->getOperand(1);
7626 SDValue N2 = N->getOperand(2);
7627 if (isZeroOrAllOnes(N1, AllOnes)) {
7632 if (isZeroOrAllOnes(N2, AllOnes)) {
7639 case ISD::ZERO_EXTEND:
7640 // (zext cc) can never be the all ones value.
7644 case ISD::SIGN_EXTEND: {
7645 EVT VT = N->getValueType(0);
7646 CC = N->getOperand(0);
7647 if (CC.getValueType() != MVT::i1)
7651 // When looking for an AllOnes constant, N is an sext, and the 'other'
7653 OtherOp = DAG.getConstant(0, VT);
7654 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7655 // When looking for a 0 constant, N can be zext or sext.
7656 OtherOp = DAG.getConstant(1, VT);
7658 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7664 // Combine a constant select operand into its use:
7666 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7667 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7668 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7669 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7670 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7672 // The transform is rejected if the select doesn't have a constant operand that
7673 // is null, or all ones when AllOnes is set.
7675 // Also recognize sext/zext from i1:
7677 // (add (zext cc), x) -> (select cc (add x, 1), x)
7678 // (add (sext cc), x) -> (select cc (add x, -1), x)
7680 // These transformations eventually create predicated instructions.
7682 // @param N The node to transform.
7683 // @param Slct The N operand that is a select.
7684 // @param OtherOp The other N operand (x above).
7685 // @param DCI Context.
7686 // @param AllOnes Require the select constant to be all ones instead of null.
7687 // @returns The new node, or SDValue() on failure.
7689 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7690 TargetLowering::DAGCombinerInfo &DCI,
7691 bool AllOnes = false) {
7692 SelectionDAG &DAG = DCI.DAG;
7693 EVT VT = N->getValueType(0);
7694 SDValue NonConstantVal;
7697 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7698 NonConstantVal, DAG))
7701 // Slct is now know to be the desired identity constant when CC is true.
7702 SDValue TrueVal = OtherOp;
7703 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7704 OtherOp, NonConstantVal);
7705 // Unless SwapSelectOps says CC should be false.
7707 std::swap(TrueVal, FalseVal);
7709 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7710 CCOp, TrueVal, FalseVal);
7713 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7715 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7716 TargetLowering::DAGCombinerInfo &DCI) {
7717 SDValue N0 = N->getOperand(0);
7718 SDValue N1 = N->getOperand(1);
7719 if (N0.getNode()->hasOneUse()) {
7720 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7721 if (Result.getNode())
7724 if (N1.getNode()->hasOneUse()) {
7725 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7726 if (Result.getNode())
7732 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7733 // (only after legalization).
7734 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7735 TargetLowering::DAGCombinerInfo &DCI,
7736 const ARMSubtarget *Subtarget) {
7738 // Only perform optimization if after legalize, and if NEON is available. We
7739 // also expected both operands to be BUILD_VECTORs.
7740 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7741 || N0.getOpcode() != ISD::BUILD_VECTOR
7742 || N1.getOpcode() != ISD::BUILD_VECTOR)
7745 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7746 EVT VT = N->getValueType(0);
7747 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7750 // Check that the vector operands are of the right form.
7751 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7752 // operands, where N is the size of the formed vector.
7753 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7754 // index such that we have a pair wise add pattern.
7756 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7757 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7759 SDValue Vec = N0->getOperand(0)->getOperand(0);
7760 SDNode *V = Vec.getNode();
7761 unsigned nextIndex = 0;
7763 // For each operands to the ADD which are BUILD_VECTORs,
7764 // check to see if each of their operands are an EXTRACT_VECTOR with
7765 // the same vector and appropriate index.
7766 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7767 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7768 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7770 SDValue ExtVec0 = N0->getOperand(i);
7771 SDValue ExtVec1 = N1->getOperand(i);
7773 // First operand is the vector, verify its the same.
7774 if (V != ExtVec0->getOperand(0).getNode() ||
7775 V != ExtVec1->getOperand(0).getNode())
7778 // Second is the constant, verify its correct.
7779 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7780 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7782 // For the constant, we want to see all the even or all the odd.
7783 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7784 || C1->getZExtValue() != nextIndex+1)
7793 // Create VPADDL node.
7794 SelectionDAG &DAG = DCI.DAG;
7795 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7797 // Build operand list.
7798 SmallVector<SDValue, 8> Ops;
7799 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7800 TLI.getPointerTy()));
7802 // Input is the vector.
7805 // Get widened type and narrowed type.
7807 unsigned numElem = VT.getVectorNumElements();
7809 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7810 switch (inputLaneType.getSimpleVT().SimpleTy) {
7811 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7812 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7813 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7815 llvm_unreachable("Invalid vector element type for padd optimization.");
7818 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7819 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7820 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7823 static SDValue findMUL_LOHI(SDValue V) {
7824 if (V->getOpcode() == ISD::UMUL_LOHI ||
7825 V->getOpcode() == ISD::SMUL_LOHI)
7830 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7831 TargetLowering::DAGCombinerInfo &DCI,
7832 const ARMSubtarget *Subtarget) {
7834 if (Subtarget->isThumb1Only()) return SDValue();
7836 // Only perform the checks after legalize when the pattern is available.
7837 if (DCI.isBeforeLegalize()) return SDValue();
7839 // Look for multiply add opportunities.
7840 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7841 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7842 // a glue link from the first add to the second add.
7843 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7844 // a S/UMLAL instruction.
7847 // \ / \ [no multiline comment]
7853 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7854 SDValue AddcOp0 = AddcNode->getOperand(0);
7855 SDValue AddcOp1 = AddcNode->getOperand(1);
7857 // Check if the two operands are from the same mul_lohi node.
7858 if (AddcOp0.getNode() == AddcOp1.getNode())
7861 assert(AddcNode->getNumValues() == 2 &&
7862 AddcNode->getValueType(0) == MVT::i32 &&
7863 "Expect ADDC with two result values. First: i32");
7865 // Check that we have a glued ADDC node.
7866 if (AddcNode->getValueType(1) != MVT::Glue)
7869 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7870 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7871 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7872 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7873 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7876 // Look for the glued ADDE.
7877 SDNode* AddeNode = AddcNode->getGluedUser();
7881 // Make sure it is really an ADDE.
7882 if (AddeNode->getOpcode() != ISD::ADDE)
7885 assert(AddeNode->getNumOperands() == 3 &&
7886 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7887 "ADDE node has the wrong inputs");
7889 // Check for the triangle shape.
7890 SDValue AddeOp0 = AddeNode->getOperand(0);
7891 SDValue AddeOp1 = AddeNode->getOperand(1);
7893 // Make sure that the ADDE operands are not coming from the same node.
7894 if (AddeOp0.getNode() == AddeOp1.getNode())
7897 // Find the MUL_LOHI node walking up ADDE's operands.
7898 bool IsLeftOperandMUL = false;
7899 SDValue MULOp = findMUL_LOHI(AddeOp0);
7900 if (MULOp == SDValue())
7901 MULOp = findMUL_LOHI(AddeOp1);
7903 IsLeftOperandMUL = true;
7904 if (MULOp == SDValue())
7907 // Figure out the right opcode.
7908 unsigned Opc = MULOp->getOpcode();
7909 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7911 // Figure out the high and low input values to the MLAL node.
7912 SDValue* HiMul = &MULOp;
7913 SDValue* HiAdd = nullptr;
7914 SDValue* LoMul = nullptr;
7915 SDValue* LowAdd = nullptr;
7917 if (IsLeftOperandMUL)
7923 if (AddcOp0->getOpcode() == Opc) {
7927 if (AddcOp1->getOpcode() == Opc) {
7935 if (LoMul->getNode() != HiMul->getNode())
7938 // Create the merged node.
7939 SelectionDAG &DAG = DCI.DAG;
7941 // Build operand list.
7942 SmallVector<SDValue, 8> Ops;
7943 Ops.push_back(LoMul->getOperand(0));
7944 Ops.push_back(LoMul->getOperand(1));
7945 Ops.push_back(*LowAdd);
7946 Ops.push_back(*HiAdd);
7948 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7949 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7951 // Replace the ADDs' nodes uses by the MLA node's values.
7952 SDValue HiMLALResult(MLALNode.getNode(), 1);
7953 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7955 SDValue LoMLALResult(MLALNode.getNode(), 0);
7956 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7958 // Return original node to notify the driver to stop replacing.
7959 SDValue resNode(AddcNode, 0);
7963 /// PerformADDCCombine - Target-specific dag combine transform from
7964 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7965 static SDValue PerformADDCCombine(SDNode *N,
7966 TargetLowering::DAGCombinerInfo &DCI,
7967 const ARMSubtarget *Subtarget) {
7969 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7973 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7974 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7975 /// called with the default operands, and if that fails, with commuted
7977 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7978 TargetLowering::DAGCombinerInfo &DCI,
7979 const ARMSubtarget *Subtarget){
7981 // Attempt to create vpaddl for this add.
7982 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7983 if (Result.getNode())
7986 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7987 if (N0.getNode()->hasOneUse()) {
7988 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7989 if (Result.getNode()) return Result;
7994 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7996 static SDValue PerformADDCombine(SDNode *N,
7997 TargetLowering::DAGCombinerInfo &DCI,
7998 const ARMSubtarget *Subtarget) {
7999 SDValue N0 = N->getOperand(0);
8000 SDValue N1 = N->getOperand(1);
8002 // First try with the default operand order.
8003 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8004 if (Result.getNode())
8007 // If that didn't work, try again with the operands commuted.
8008 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8011 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8013 static SDValue PerformSUBCombine(SDNode *N,
8014 TargetLowering::DAGCombinerInfo &DCI) {
8015 SDValue N0 = N->getOperand(0);
8016 SDValue N1 = N->getOperand(1);
8018 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8019 if (N1.getNode()->hasOneUse()) {
8020 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8021 if (Result.getNode()) return Result;
8027 /// PerformVMULCombine
8028 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8029 /// special multiplier accumulator forwarding.
8035 // However, for (A + B) * (A + B),
8042 static SDValue PerformVMULCombine(SDNode *N,
8043 TargetLowering::DAGCombinerInfo &DCI,
8044 const ARMSubtarget *Subtarget) {
8045 if (!Subtarget->hasVMLxForwarding())
8048 SelectionDAG &DAG = DCI.DAG;
8049 SDValue N0 = N->getOperand(0);
8050 SDValue N1 = N->getOperand(1);
8051 unsigned Opcode = N0.getOpcode();
8052 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8053 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8054 Opcode = N1.getOpcode();
8055 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8056 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8064 EVT VT = N->getValueType(0);
8066 SDValue N00 = N0->getOperand(0);
8067 SDValue N01 = N0->getOperand(1);
8068 return DAG.getNode(Opcode, DL, VT,
8069 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8070 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8073 static SDValue PerformMULCombine(SDNode *N,
8074 TargetLowering::DAGCombinerInfo &DCI,
8075 const ARMSubtarget *Subtarget) {
8076 SelectionDAG &DAG = DCI.DAG;
8078 if (Subtarget->isThumb1Only())
8081 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8084 EVT VT = N->getValueType(0);
8085 if (VT.is64BitVector() || VT.is128BitVector())
8086 return PerformVMULCombine(N, DCI, Subtarget);
8090 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8094 int64_t MulAmt = C->getSExtValue();
8095 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8097 ShiftAmt = ShiftAmt & (32 - 1);
8098 SDValue V = N->getOperand(0);
8102 MulAmt >>= ShiftAmt;
8105 if (isPowerOf2_32(MulAmt - 1)) {
8106 // (mul x, 2^N + 1) => (add (shl x, N), x)
8107 Res = DAG.getNode(ISD::ADD, DL, VT,
8109 DAG.getNode(ISD::SHL, DL, VT,
8111 DAG.getConstant(Log2_32(MulAmt - 1),
8113 } else if (isPowerOf2_32(MulAmt + 1)) {
8114 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8115 Res = DAG.getNode(ISD::SUB, DL, VT,
8116 DAG.getNode(ISD::SHL, DL, VT,
8118 DAG.getConstant(Log2_32(MulAmt + 1),
8124 uint64_t MulAmtAbs = -MulAmt;
8125 if (isPowerOf2_32(MulAmtAbs + 1)) {
8126 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8127 Res = DAG.getNode(ISD::SUB, DL, VT,
8129 DAG.getNode(ISD::SHL, DL, VT,
8131 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8133 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8134 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8135 Res = DAG.getNode(ISD::ADD, DL, VT,
8137 DAG.getNode(ISD::SHL, DL, VT,
8139 DAG.getConstant(Log2_32(MulAmtAbs-1),
8141 Res = DAG.getNode(ISD::SUB, DL, VT,
8142 DAG.getConstant(0, MVT::i32),Res);
8149 Res = DAG.getNode(ISD::SHL, DL, VT,
8150 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8152 // Do not add new nodes to DAG combiner worklist.
8153 DCI.CombineTo(N, Res, false);
8157 static SDValue PerformANDCombine(SDNode *N,
8158 TargetLowering::DAGCombinerInfo &DCI,
8159 const ARMSubtarget *Subtarget) {
8161 // Attempt to use immediate-form VBIC
8162 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8164 EVT VT = N->getValueType(0);
8165 SelectionDAG &DAG = DCI.DAG;
8167 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8170 APInt SplatBits, SplatUndef;
8171 unsigned SplatBitSize;
8174 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8175 if (SplatBitSize <= 64) {
8177 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8178 SplatUndef.getZExtValue(), SplatBitSize,
8179 DAG, VbicVT, VT.is128BitVector(),
8181 if (Val.getNode()) {
8183 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8184 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8185 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8190 if (!Subtarget->isThumb1Only()) {
8191 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8192 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8193 if (Result.getNode())
8200 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8201 static SDValue PerformORCombine(SDNode *N,
8202 TargetLowering::DAGCombinerInfo &DCI,
8203 const ARMSubtarget *Subtarget) {
8204 // Attempt to use immediate-form VORR
8205 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8207 EVT VT = N->getValueType(0);
8208 SelectionDAG &DAG = DCI.DAG;
8210 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8213 APInt SplatBits, SplatUndef;
8214 unsigned SplatBitSize;
8216 if (BVN && Subtarget->hasNEON() &&
8217 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8218 if (SplatBitSize <= 64) {
8220 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8221 SplatUndef.getZExtValue(), SplatBitSize,
8222 DAG, VorrVT, VT.is128BitVector(),
8224 if (Val.getNode()) {
8226 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8227 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8228 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8233 if (!Subtarget->isThumb1Only()) {
8234 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8235 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8236 if (Result.getNode())
8240 // The code below optimizes (or (and X, Y), Z).
8241 // The AND operand needs to have a single user to make these optimizations
8243 SDValue N0 = N->getOperand(0);
8244 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8246 SDValue N1 = N->getOperand(1);
8248 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8249 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8250 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8252 unsigned SplatBitSize;
8255 APInt SplatBits0, SplatBits1;
8256 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8257 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8258 // Ensure that the second operand of both ands are constants
8259 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8260 HasAnyUndefs) && !HasAnyUndefs) {
8261 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8262 HasAnyUndefs) && !HasAnyUndefs) {
8263 // Ensure that the bit width of the constants are the same and that
8264 // the splat arguments are logical inverses as per the pattern we
8265 // are trying to simplify.
8266 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8267 SplatBits0 == ~SplatBits1) {
8268 // Canonicalize the vector type to make instruction selection
8270 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8271 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8275 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8281 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8284 // BFI is only available on V6T2+
8285 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8289 // 1) or (and A, mask), val => ARMbfi A, val, mask
8290 // iff (val & mask) == val
8292 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8293 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8294 // && mask == ~mask2
8295 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8296 // && ~mask == mask2
8297 // (i.e., copy a bitfield value into another bitfield of the same width)
8302 SDValue N00 = N0.getOperand(0);
8304 // The value and the mask need to be constants so we can verify this is
8305 // actually a bitfield set. If the mask is 0xffff, we can do better
8306 // via a movt instruction, so don't use BFI in that case.
8307 SDValue MaskOp = N0.getOperand(1);
8308 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8311 unsigned Mask = MaskC->getZExtValue();
8315 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8316 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8318 unsigned Val = N1C->getZExtValue();
8319 if ((Val & ~Mask) != Val)
8322 if (ARM::isBitFieldInvertedMask(Mask)) {
8323 Val >>= countTrailingZeros(~Mask);
8325 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8326 DAG.getConstant(Val, MVT::i32),
8327 DAG.getConstant(Mask, MVT::i32));
8329 // Do not add new nodes to DAG combiner worklist.
8330 DCI.CombineTo(N, Res, false);
8333 } else if (N1.getOpcode() == ISD::AND) {
8334 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8335 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8338 unsigned Mask2 = N11C->getZExtValue();
8340 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8342 if (ARM::isBitFieldInvertedMask(Mask) &&
8344 // The pack halfword instruction works better for masks that fit it,
8345 // so use that when it's available.
8346 if (Subtarget->hasT2ExtractPack() &&
8347 (Mask == 0xffff || Mask == 0xffff0000))
8350 unsigned amt = countTrailingZeros(Mask2);
8351 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8352 DAG.getConstant(amt, MVT::i32));
8353 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8354 DAG.getConstant(Mask, MVT::i32));
8355 // Do not add new nodes to DAG combiner worklist.
8356 DCI.CombineTo(N, Res, false);
8358 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8360 // The pack halfword instruction works better for masks that fit it,
8361 // so use that when it's available.
8362 if (Subtarget->hasT2ExtractPack() &&
8363 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8366 unsigned lsb = countTrailingZeros(Mask);
8367 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8368 DAG.getConstant(lsb, MVT::i32));
8369 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8370 DAG.getConstant(Mask2, MVT::i32));
8371 // Do not add new nodes to DAG combiner worklist.
8372 DCI.CombineTo(N, Res, false);
8377 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8378 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8379 ARM::isBitFieldInvertedMask(~Mask)) {
8380 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8381 // where lsb(mask) == #shamt and masked bits of B are known zero.
8382 SDValue ShAmt = N00.getOperand(1);
8383 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8384 unsigned LSB = countTrailingZeros(Mask);
8388 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8389 DAG.getConstant(~Mask, MVT::i32));
8391 // Do not add new nodes to DAG combiner worklist.
8392 DCI.CombineTo(N, Res, false);
8398 static SDValue PerformXORCombine(SDNode *N,
8399 TargetLowering::DAGCombinerInfo &DCI,
8400 const ARMSubtarget *Subtarget) {
8401 EVT VT = N->getValueType(0);
8402 SelectionDAG &DAG = DCI.DAG;
8404 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8407 if (!Subtarget->isThumb1Only()) {
8408 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8409 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8410 if (Result.getNode())
8417 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8418 /// the bits being cleared by the AND are not demanded by the BFI.
8419 static SDValue PerformBFICombine(SDNode *N,
8420 TargetLowering::DAGCombinerInfo &DCI) {
8421 SDValue N1 = N->getOperand(1);
8422 if (N1.getOpcode() == ISD::AND) {
8423 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8426 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8427 unsigned LSB = countTrailingZeros(~InvMask);
8428 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8429 unsigned Mask = (1 << Width)-1;
8430 unsigned Mask2 = N11C->getZExtValue();
8431 if ((Mask & (~Mask2)) == 0)
8432 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8433 N->getOperand(0), N1.getOperand(0),
8439 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8440 /// ARMISD::VMOVRRD.
8441 static SDValue PerformVMOVRRDCombine(SDNode *N,
8442 TargetLowering::DAGCombinerInfo &DCI) {
8443 // vmovrrd(vmovdrr x, y) -> x,y
8444 SDValue InDouble = N->getOperand(0);
8445 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8446 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8448 // vmovrrd(load f64) -> (load i32), (load i32)
8449 SDNode *InNode = InDouble.getNode();
8450 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8451 InNode->getValueType(0) == MVT::f64 &&
8452 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8453 !cast<LoadSDNode>(InNode)->isVolatile()) {
8454 // TODO: Should this be done for non-FrameIndex operands?
8455 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8457 SelectionDAG &DAG = DCI.DAG;
8459 SDValue BasePtr = LD->getBasePtr();
8460 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8461 LD->getPointerInfo(), LD->isVolatile(),
8462 LD->isNonTemporal(), LD->isInvariant(),
8463 LD->getAlignment());
8465 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8466 DAG.getConstant(4, MVT::i32));
8467 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8468 LD->getPointerInfo(), LD->isVolatile(),
8469 LD->isNonTemporal(), LD->isInvariant(),
8470 std::min(4U, LD->getAlignment() / 2));
8472 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8473 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8474 std::swap (NewLD1, NewLD2);
8475 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8482 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8483 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8484 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8485 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8486 SDValue Op0 = N->getOperand(0);
8487 SDValue Op1 = N->getOperand(1);
8488 if (Op0.getOpcode() == ISD::BITCAST)
8489 Op0 = Op0.getOperand(0);
8490 if (Op1.getOpcode() == ISD::BITCAST)
8491 Op1 = Op1.getOperand(0);
8492 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8493 Op0.getNode() == Op1.getNode() &&
8494 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8495 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8496 N->getValueType(0), Op0.getOperand(0));
8500 /// PerformSTORECombine - Target-specific dag combine xforms for
8502 static SDValue PerformSTORECombine(SDNode *N,
8503 TargetLowering::DAGCombinerInfo &DCI) {
8504 StoreSDNode *St = cast<StoreSDNode>(N);
8505 if (St->isVolatile())
8508 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8509 // pack all of the elements in one place. Next, store to memory in fewer
8511 SDValue StVal = St->getValue();
8512 EVT VT = StVal.getValueType();
8513 if (St->isTruncatingStore() && VT.isVector()) {
8514 SelectionDAG &DAG = DCI.DAG;
8515 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8516 EVT StVT = St->getMemoryVT();
8517 unsigned NumElems = VT.getVectorNumElements();
8518 assert(StVT != VT && "Cannot truncate to the same type");
8519 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8520 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8522 // From, To sizes and ElemCount must be pow of two
8523 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8525 // We are going to use the original vector elt for storing.
8526 // Accumulated smaller vector elements must be a multiple of the store size.
8527 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8529 unsigned SizeRatio = FromEltSz / ToEltSz;
8530 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8532 // Create a type on which we perform the shuffle.
8533 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8534 NumElems*SizeRatio);
8535 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8538 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8539 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8540 for (unsigned i = 0; i < NumElems; ++i)
8541 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8543 // Can't shuffle using an illegal type.
8544 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8546 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8547 DAG.getUNDEF(WideVec.getValueType()),
8549 // At this point all of the data is stored at the bottom of the
8550 // register. We now need to save it to mem.
8552 // Find the largest store unit
8553 MVT StoreType = MVT::i8;
8554 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8555 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8556 MVT Tp = (MVT::SimpleValueType)tp;
8557 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8560 // Didn't find a legal store type.
8561 if (!TLI.isTypeLegal(StoreType))
8564 // Bitcast the original vector into a vector of store-size units
8565 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8566 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8567 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8568 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8569 SmallVector<SDValue, 8> Chains;
8570 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8571 TLI.getPointerTy());
8572 SDValue BasePtr = St->getBasePtr();
8574 // Perform one or more big stores into memory.
8575 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8576 for (unsigned I = 0; I < E; I++) {
8577 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8578 StoreType, ShuffWide,
8579 DAG.getIntPtrConstant(I));
8580 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8581 St->getPointerInfo(), St->isVolatile(),
8582 St->isNonTemporal(), St->getAlignment());
8583 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8585 Chains.push_back(Ch);
8587 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8590 if (!ISD::isNormalStore(St))
8593 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8594 // ARM stores of arguments in the same cache line.
8595 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8596 StVal.getNode()->hasOneUse()) {
8597 SelectionDAG &DAG = DCI.DAG;
8598 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8600 SDValue BasePtr = St->getBasePtr();
8601 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8602 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8603 BasePtr, St->getPointerInfo(), St->isVolatile(),
8604 St->isNonTemporal(), St->getAlignment());
8606 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8607 DAG.getConstant(4, MVT::i32));
8608 return DAG.getStore(NewST1.getValue(0), DL,
8609 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8610 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8611 St->isNonTemporal(),
8612 std::min(4U, St->getAlignment() / 2));
8615 if (StVal.getValueType() != MVT::i64 ||
8616 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8619 // Bitcast an i64 store extracted from a vector to f64.
8620 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8621 SelectionDAG &DAG = DCI.DAG;
8623 SDValue IntVec = StVal.getOperand(0);
8624 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8625 IntVec.getValueType().getVectorNumElements());
8626 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8627 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8628 Vec, StVal.getOperand(1));
8630 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8631 // Make the DAGCombiner fold the bitcasts.
8632 DCI.AddToWorklist(Vec.getNode());
8633 DCI.AddToWorklist(ExtElt.getNode());
8634 DCI.AddToWorklist(V.getNode());
8635 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8636 St->getPointerInfo(), St->isVolatile(),
8637 St->isNonTemporal(), St->getAlignment(),
8641 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8642 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8643 /// i64 vector to have f64 elements, since the value can then be loaded
8644 /// directly into a VFP register.
8645 static bool hasNormalLoadOperand(SDNode *N) {
8646 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8647 for (unsigned i = 0; i < NumElts; ++i) {
8648 SDNode *Elt = N->getOperand(i).getNode();
8649 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8655 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8656 /// ISD::BUILD_VECTOR.
8657 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8658 TargetLowering::DAGCombinerInfo &DCI){
8659 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8660 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8661 // into a pair of GPRs, which is fine when the value is used as a scalar,
8662 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8663 SelectionDAG &DAG = DCI.DAG;
8664 if (N->getNumOperands() == 2) {
8665 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8670 // Load i64 elements as f64 values so that type legalization does not split
8671 // them up into i32 values.
8672 EVT VT = N->getValueType(0);
8673 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8676 SmallVector<SDValue, 8> Ops;
8677 unsigned NumElts = VT.getVectorNumElements();
8678 for (unsigned i = 0; i < NumElts; ++i) {
8679 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8681 // Make the DAGCombiner fold the bitcast.
8682 DCI.AddToWorklist(V.getNode());
8684 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8685 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8686 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8689 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8691 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8692 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8693 // At that time, we may have inserted bitcasts from integer to float.
8694 // If these bitcasts have survived DAGCombine, change the lowering of this
8695 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8696 // force to use floating point types.
8698 // Make sure we can change the type of the vector.
8699 // This is possible iff:
8700 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8701 // 1.1. Vector is used only once.
8702 // 1.2. Use is a bit convert to an integer type.
8703 // 2. The size of its operands are 32-bits (64-bits are not legal).
8704 EVT VT = N->getValueType(0);
8705 EVT EltVT = VT.getVectorElementType();
8707 // Check 1.1. and 2.
8708 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8711 // By construction, the input type must be float.
8712 assert(EltVT == MVT::f32 && "Unexpected type!");
8715 SDNode *Use = *N->use_begin();
8716 if (Use->getOpcode() != ISD::BITCAST ||
8717 Use->getValueType(0).isFloatingPoint())
8720 // Check profitability.
8721 // Model is, if more than half of the relevant operands are bitcast from
8722 // i32, turn the build_vector into a sequence of insert_vector_elt.
8723 // Relevant operands are everything that is not statically
8724 // (i.e., at compile time) bitcasted.
8725 unsigned NumOfBitCastedElts = 0;
8726 unsigned NumElts = VT.getVectorNumElements();
8727 unsigned NumOfRelevantElts = NumElts;
8728 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8729 SDValue Elt = N->getOperand(Idx);
8730 if (Elt->getOpcode() == ISD::BITCAST) {
8731 // Assume only bit cast to i32 will go away.
8732 if (Elt->getOperand(0).getValueType() == MVT::i32)
8733 ++NumOfBitCastedElts;
8734 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8735 // Constants are statically casted, thus do not count them as
8736 // relevant operands.
8737 --NumOfRelevantElts;
8740 // Check if more than half of the elements require a non-free bitcast.
8741 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8744 SelectionDAG &DAG = DCI.DAG;
8745 // Create the new vector type.
8746 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8747 // Check if the type is legal.
8748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8749 if (!TLI.isTypeLegal(VecVT))
8753 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8754 // => BITCAST INSERT_VECTOR_ELT
8755 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8757 SDValue Vec = DAG.getUNDEF(VecVT);
8759 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8760 SDValue V = N->getOperand(Idx);
8761 if (V.getOpcode() == ISD::UNDEF)
8763 if (V.getOpcode() == ISD::BITCAST &&
8764 V->getOperand(0).getValueType() == MVT::i32)
8765 // Fold obvious case.
8766 V = V.getOperand(0);
8768 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8769 // Make the DAGCombiner fold the bitcasts.
8770 DCI.AddToWorklist(V.getNode());
8772 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8773 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8775 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8776 // Make the DAGCombiner fold the bitcasts.
8777 DCI.AddToWorklist(Vec.getNode());
8781 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8782 /// ISD::INSERT_VECTOR_ELT.
8783 static SDValue PerformInsertEltCombine(SDNode *N,
8784 TargetLowering::DAGCombinerInfo &DCI) {
8785 // Bitcast an i64 load inserted into a vector to f64.
8786 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8787 EVT VT = N->getValueType(0);
8788 SDNode *Elt = N->getOperand(1).getNode();
8789 if (VT.getVectorElementType() != MVT::i64 ||
8790 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8793 SelectionDAG &DAG = DCI.DAG;
8795 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8796 VT.getVectorNumElements());
8797 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8798 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8799 // Make the DAGCombiner fold the bitcasts.
8800 DCI.AddToWorklist(Vec.getNode());
8801 DCI.AddToWorklist(V.getNode());
8802 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8803 Vec, V, N->getOperand(2));
8804 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8807 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8808 /// ISD::VECTOR_SHUFFLE.
8809 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8810 // The LLVM shufflevector instruction does not require the shuffle mask
8811 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8812 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8813 // operands do not match the mask length, they are extended by concatenating
8814 // them with undef vectors. That is probably the right thing for other
8815 // targets, but for NEON it is better to concatenate two double-register
8816 // size vector operands into a single quad-register size vector. Do that
8817 // transformation here:
8818 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8819 // shuffle(concat(v1, v2), undef)
8820 SDValue Op0 = N->getOperand(0);
8821 SDValue Op1 = N->getOperand(1);
8822 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8823 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8824 Op0.getNumOperands() != 2 ||
8825 Op1.getNumOperands() != 2)
8827 SDValue Concat0Op1 = Op0.getOperand(1);
8828 SDValue Concat1Op1 = Op1.getOperand(1);
8829 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8830 Concat1Op1.getOpcode() != ISD::UNDEF)
8832 // Skip the transformation if any of the types are illegal.
8833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8834 EVT VT = N->getValueType(0);
8835 if (!TLI.isTypeLegal(VT) ||
8836 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8837 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8840 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8841 Op0.getOperand(0), Op1.getOperand(0));
8842 // Translate the shuffle mask.
8843 SmallVector<int, 16> NewMask;
8844 unsigned NumElts = VT.getVectorNumElements();
8845 unsigned HalfElts = NumElts/2;
8846 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8847 for (unsigned n = 0; n < NumElts; ++n) {
8848 int MaskElt = SVN->getMaskElt(n);
8850 if (MaskElt < (int)HalfElts)
8852 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8853 NewElt = HalfElts + MaskElt - NumElts;
8854 NewMask.push_back(NewElt);
8856 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8857 DAG.getUNDEF(VT), NewMask.data());
8860 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8861 /// NEON load/store intrinsics to merge base address updates.
8862 static SDValue CombineBaseUpdate(SDNode *N,
8863 TargetLowering::DAGCombinerInfo &DCI) {
8864 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8867 SelectionDAG &DAG = DCI.DAG;
8868 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8869 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8870 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8871 SDValue Addr = N->getOperand(AddrOpIdx);
8873 // Search for a use of the address operand that is an increment.
8874 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8875 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8877 if (User->getOpcode() != ISD::ADD ||
8878 UI.getUse().getResNo() != Addr.getResNo())
8881 // Check that the add is independent of the load/store. Otherwise, folding
8882 // it would create a cycle.
8883 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8886 // Find the new opcode for the updating load/store.
8888 bool isLaneOp = false;
8889 unsigned NewOpc = 0;
8890 unsigned NumVecs = 0;
8892 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8894 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8895 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8897 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8899 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8901 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8903 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8904 NumVecs = 2; isLaneOp = true; break;
8905 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8906 NumVecs = 3; isLaneOp = true; break;
8907 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8908 NumVecs = 4; isLaneOp = true; break;
8909 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8910 NumVecs = 1; isLoad = false; break;
8911 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8912 NumVecs = 2; isLoad = false; break;
8913 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8914 NumVecs = 3; isLoad = false; break;
8915 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8916 NumVecs = 4; isLoad = false; break;
8917 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8918 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8919 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8920 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8921 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8922 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8926 switch (N->getOpcode()) {
8927 default: llvm_unreachable("unexpected opcode for Neon base update");
8928 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8929 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8930 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8934 // Find the size of memory referenced by the load/store.
8937 VecTy = N->getValueType(0);
8939 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8940 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8942 NumBytes /= VecTy.getVectorNumElements();
8944 // If the increment is a constant, it must match the memory ref size.
8945 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8946 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8947 uint64_t IncVal = CInc->getZExtValue();
8948 if (IncVal != NumBytes)
8950 } else if (NumBytes >= 3 * 16) {
8951 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8952 // separate instructions that make it harder to use a non-constant update.
8956 // Create the new updating load/store node.
8958 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8960 for (n = 0; n < NumResultVecs; ++n)
8962 Tys[n++] = MVT::i32;
8963 Tys[n] = MVT::Other;
8964 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8965 SmallVector<SDValue, 8> Ops;
8966 Ops.push_back(N->getOperand(0)); // incoming chain
8967 Ops.push_back(N->getOperand(AddrOpIdx));
8969 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8970 Ops.push_back(N->getOperand(i));
8972 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8973 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8974 Ops, MemInt->getMemoryVT(),
8975 MemInt->getMemOperand());
8978 std::vector<SDValue> NewResults;
8979 for (unsigned i = 0; i < NumResultVecs; ++i) {
8980 NewResults.push_back(SDValue(UpdN.getNode(), i));
8982 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8983 DCI.CombineTo(N, NewResults);
8984 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8991 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8992 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8993 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8995 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8996 SelectionDAG &DAG = DCI.DAG;
8997 EVT VT = N->getValueType(0);
8998 // vldN-dup instructions only support 64-bit vectors for N > 1.
8999 if (!VT.is64BitVector())
9002 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9003 SDNode *VLD = N->getOperand(0).getNode();
9004 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9006 unsigned NumVecs = 0;
9007 unsigned NewOpc = 0;
9008 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9009 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9011 NewOpc = ARMISD::VLD2DUP;
9012 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9014 NewOpc = ARMISD::VLD3DUP;
9015 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9017 NewOpc = ARMISD::VLD4DUP;
9022 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9023 // numbers match the load.
9024 unsigned VLDLaneNo =
9025 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9026 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9028 // Ignore uses of the chain result.
9029 if (UI.getUse().getResNo() == NumVecs)
9032 if (User->getOpcode() != ARMISD::VDUPLANE ||
9033 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9037 // Create the vldN-dup node.
9040 for (n = 0; n < NumVecs; ++n)
9042 Tys[n] = MVT::Other;
9043 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9044 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9045 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9046 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9047 Ops, VLDMemInt->getMemoryVT(),
9048 VLDMemInt->getMemOperand());
9051 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9053 unsigned ResNo = UI.getUse().getResNo();
9054 // Ignore uses of the chain result.
9055 if (ResNo == NumVecs)
9058 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9061 // Now the vldN-lane intrinsic is dead except for its chain result.
9062 // Update uses of the chain.
9063 std::vector<SDValue> VLDDupResults;
9064 for (unsigned n = 0; n < NumVecs; ++n)
9065 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9066 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9067 DCI.CombineTo(VLD, VLDDupResults);
9072 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9073 /// ARMISD::VDUPLANE.
9074 static SDValue PerformVDUPLANECombine(SDNode *N,
9075 TargetLowering::DAGCombinerInfo &DCI) {
9076 SDValue Op = N->getOperand(0);
9078 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9079 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9080 if (CombineVLDDUP(N, DCI))
9081 return SDValue(N, 0);
9083 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9084 // redundant. Ignore bit_converts for now; element sizes are checked below.
9085 while (Op.getOpcode() == ISD::BITCAST)
9086 Op = Op.getOperand(0);
9087 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9090 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9091 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9092 // The canonical VMOV for a zero vector uses a 32-bit element size.
9093 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9095 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9097 EVT VT = N->getValueType(0);
9098 if (EltSize > VT.getVectorElementType().getSizeInBits())
9101 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9104 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9105 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9106 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9110 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9112 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9117 APFloat APF = C->getValueAPF();
9118 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9119 != APFloat::opOK || !isExact)
9122 c0 = (I == 0) ? cN : c0;
9123 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9130 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9131 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9132 /// when the VMUL has a constant operand that is a power of 2.
9134 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9135 /// vmul.f32 d16, d17, d16
9136 /// vcvt.s32.f32 d16, d16
9138 /// vcvt.s32.f32 d16, d16, #3
9139 static SDValue PerformVCVTCombine(SDNode *N,
9140 TargetLowering::DAGCombinerInfo &DCI,
9141 const ARMSubtarget *Subtarget) {
9142 SelectionDAG &DAG = DCI.DAG;
9143 SDValue Op = N->getOperand(0);
9145 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9146 Op.getOpcode() != ISD::FMUL)
9150 SDValue N0 = Op->getOperand(0);
9151 SDValue ConstVec = Op->getOperand(1);
9152 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9154 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9155 !isConstVecPow2(ConstVec, isSigned, C))
9158 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9159 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9160 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9161 // These instructions only exist converting from f32 to i32. We can handle
9162 // smaller integers by generating an extra truncate, but larger ones would
9167 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9168 Intrinsic::arm_neon_vcvtfp2fxu;
9169 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9170 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9171 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9172 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9173 DAG.getConstant(Log2_64(C), MVT::i32));
9175 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9176 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9181 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9182 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9183 /// when the VDIV has a constant operand that is a power of 2.
9185 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9186 /// vcvt.f32.s32 d16, d16
9187 /// vdiv.f32 d16, d17, d16
9189 /// vcvt.f32.s32 d16, d16, #3
9190 static SDValue PerformVDIVCombine(SDNode *N,
9191 TargetLowering::DAGCombinerInfo &DCI,
9192 const ARMSubtarget *Subtarget) {
9193 SelectionDAG &DAG = DCI.DAG;
9194 SDValue Op = N->getOperand(0);
9195 unsigned OpOpcode = Op.getNode()->getOpcode();
9197 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9198 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9202 SDValue ConstVec = N->getOperand(1);
9203 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9205 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9206 !isConstVecPow2(ConstVec, isSigned, C))
9209 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9210 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9211 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9212 // These instructions only exist converting from i32 to f32. We can handle
9213 // smaller integers by generating an extra extend, but larger ones would
9218 SDValue ConvInput = Op.getOperand(0);
9219 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9220 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9221 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9222 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9225 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9226 Intrinsic::arm_neon_vcvtfxu2fp;
9227 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9229 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9230 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9233 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9234 /// operand of a vector shift operation, where all the elements of the
9235 /// build_vector must have the same constant integer value.
9236 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9237 // Ignore bit_converts.
9238 while (Op.getOpcode() == ISD::BITCAST)
9239 Op = Op.getOperand(0);
9240 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9241 APInt SplatBits, SplatUndef;
9242 unsigned SplatBitSize;
9244 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9245 HasAnyUndefs, ElementBits) ||
9246 SplatBitSize > ElementBits)
9248 Cnt = SplatBits.getSExtValue();
9252 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9253 /// operand of a vector shift left operation. That value must be in the range:
9254 /// 0 <= Value < ElementBits for a left shift; or
9255 /// 0 <= Value <= ElementBits for a long left shift.
9256 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9257 assert(VT.isVector() && "vector shift count is not a vector type");
9258 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9259 if (! getVShiftImm(Op, ElementBits, Cnt))
9261 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9264 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9265 /// operand of a vector shift right operation. For a shift opcode, the value
9266 /// is positive, but for an intrinsic the value count must be negative. The
9267 /// absolute value must be in the range:
9268 /// 1 <= |Value| <= ElementBits for a right shift; or
9269 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9270 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9272 assert(VT.isVector() && "vector shift count is not a vector type");
9273 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9274 if (! getVShiftImm(Op, ElementBits, Cnt))
9278 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9281 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9282 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9283 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9286 // Don't do anything for most intrinsics.
9289 // Vector shifts: check for immediate versions and lower them.
9290 // Note: This is done during DAG combining instead of DAG legalizing because
9291 // the build_vectors for 64-bit vector element shift counts are generally
9292 // not legal, and it is hard to see their values after they get legalized to
9293 // loads from a constant pool.
9294 case Intrinsic::arm_neon_vshifts:
9295 case Intrinsic::arm_neon_vshiftu:
9296 case Intrinsic::arm_neon_vrshifts:
9297 case Intrinsic::arm_neon_vrshiftu:
9298 case Intrinsic::arm_neon_vrshiftn:
9299 case Intrinsic::arm_neon_vqshifts:
9300 case Intrinsic::arm_neon_vqshiftu:
9301 case Intrinsic::arm_neon_vqshiftsu:
9302 case Intrinsic::arm_neon_vqshiftns:
9303 case Intrinsic::arm_neon_vqshiftnu:
9304 case Intrinsic::arm_neon_vqshiftnsu:
9305 case Intrinsic::arm_neon_vqrshiftns:
9306 case Intrinsic::arm_neon_vqrshiftnu:
9307 case Intrinsic::arm_neon_vqrshiftnsu: {
9308 EVT VT = N->getOperand(1).getValueType();
9310 unsigned VShiftOpc = 0;
9313 case Intrinsic::arm_neon_vshifts:
9314 case Intrinsic::arm_neon_vshiftu:
9315 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9316 VShiftOpc = ARMISD::VSHL;
9319 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9320 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9321 ARMISD::VSHRs : ARMISD::VSHRu);
9326 case Intrinsic::arm_neon_vrshifts:
9327 case Intrinsic::arm_neon_vrshiftu:
9328 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9332 case Intrinsic::arm_neon_vqshifts:
9333 case Intrinsic::arm_neon_vqshiftu:
9334 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9338 case Intrinsic::arm_neon_vqshiftsu:
9339 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9341 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9343 case Intrinsic::arm_neon_vrshiftn:
9344 case Intrinsic::arm_neon_vqshiftns:
9345 case Intrinsic::arm_neon_vqshiftnu:
9346 case Intrinsic::arm_neon_vqshiftnsu:
9347 case Intrinsic::arm_neon_vqrshiftns:
9348 case Intrinsic::arm_neon_vqrshiftnu:
9349 case Intrinsic::arm_neon_vqrshiftnsu:
9350 // Narrowing shifts require an immediate right shift.
9351 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9353 llvm_unreachable("invalid shift count for narrowing vector shift "
9357 llvm_unreachable("unhandled vector shift");
9361 case Intrinsic::arm_neon_vshifts:
9362 case Intrinsic::arm_neon_vshiftu:
9363 // Opcode already set above.
9365 case Intrinsic::arm_neon_vrshifts:
9366 VShiftOpc = ARMISD::VRSHRs; break;
9367 case Intrinsic::arm_neon_vrshiftu:
9368 VShiftOpc = ARMISD::VRSHRu; break;
9369 case Intrinsic::arm_neon_vrshiftn:
9370 VShiftOpc = ARMISD::VRSHRN; break;
9371 case Intrinsic::arm_neon_vqshifts:
9372 VShiftOpc = ARMISD::VQSHLs; break;
9373 case Intrinsic::arm_neon_vqshiftu:
9374 VShiftOpc = ARMISD::VQSHLu; break;
9375 case Intrinsic::arm_neon_vqshiftsu:
9376 VShiftOpc = ARMISD::VQSHLsu; break;
9377 case Intrinsic::arm_neon_vqshiftns:
9378 VShiftOpc = ARMISD::VQSHRNs; break;
9379 case Intrinsic::arm_neon_vqshiftnu:
9380 VShiftOpc = ARMISD::VQSHRNu; break;
9381 case Intrinsic::arm_neon_vqshiftnsu:
9382 VShiftOpc = ARMISD::VQSHRNsu; break;
9383 case Intrinsic::arm_neon_vqrshiftns:
9384 VShiftOpc = ARMISD::VQRSHRNs; break;
9385 case Intrinsic::arm_neon_vqrshiftnu:
9386 VShiftOpc = ARMISD::VQRSHRNu; break;
9387 case Intrinsic::arm_neon_vqrshiftnsu:
9388 VShiftOpc = ARMISD::VQRSHRNsu; break;
9391 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9392 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9395 case Intrinsic::arm_neon_vshiftins: {
9396 EVT VT = N->getOperand(1).getValueType();
9398 unsigned VShiftOpc = 0;
9400 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9401 VShiftOpc = ARMISD::VSLI;
9402 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9403 VShiftOpc = ARMISD::VSRI;
9405 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9408 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9409 N->getOperand(1), N->getOperand(2),
9410 DAG.getConstant(Cnt, MVT::i32));
9413 case Intrinsic::arm_neon_vqrshifts:
9414 case Intrinsic::arm_neon_vqrshiftu:
9415 // No immediate versions of these to check for.
9422 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9423 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9424 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9425 /// vector element shift counts are generally not legal, and it is hard to see
9426 /// their values after they get legalized to loads from a constant pool.
9427 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9428 const ARMSubtarget *ST) {
9429 EVT VT = N->getValueType(0);
9430 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9431 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9432 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9433 SDValue N1 = N->getOperand(1);
9434 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9435 SDValue N0 = N->getOperand(0);
9436 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9437 DAG.MaskedValueIsZero(N0.getOperand(0),
9438 APInt::getHighBitsSet(32, 16)))
9439 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9443 // Nothing to be done for scalar shifts.
9444 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9445 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9448 assert(ST->hasNEON() && "unexpected vector shift");
9451 switch (N->getOpcode()) {
9452 default: llvm_unreachable("unexpected shift opcode");
9455 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9456 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9457 DAG.getConstant(Cnt, MVT::i32));
9462 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9463 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9464 ARMISD::VSHRs : ARMISD::VSHRu);
9465 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9466 DAG.getConstant(Cnt, MVT::i32));
9472 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9473 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9474 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9475 const ARMSubtarget *ST) {
9476 SDValue N0 = N->getOperand(0);
9478 // Check for sign- and zero-extensions of vector extract operations of 8-
9479 // and 16-bit vector elements. NEON supports these directly. They are
9480 // handled during DAG combining because type legalization will promote them
9481 // to 32-bit types and it is messy to recognize the operations after that.
9482 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9483 SDValue Vec = N0.getOperand(0);
9484 SDValue Lane = N0.getOperand(1);
9485 EVT VT = N->getValueType(0);
9486 EVT EltVT = N0.getValueType();
9487 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9489 if (VT == MVT::i32 &&
9490 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9491 TLI.isTypeLegal(Vec.getValueType()) &&
9492 isa<ConstantSDNode>(Lane)) {
9495 switch (N->getOpcode()) {
9496 default: llvm_unreachable("unexpected opcode");
9497 case ISD::SIGN_EXTEND:
9498 Opc = ARMISD::VGETLANEs;
9500 case ISD::ZERO_EXTEND:
9501 case ISD::ANY_EXTEND:
9502 Opc = ARMISD::VGETLANEu;
9505 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9512 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9513 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9514 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9515 const ARMSubtarget *ST) {
9516 // If the target supports NEON, try to use vmax/vmin instructions for f32
9517 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9518 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9519 // a NaN; only do the transformation when it matches that behavior.
9521 // For now only do this when using NEON for FP operations; if using VFP, it
9522 // is not obvious that the benefit outweighs the cost of switching to the
9524 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9525 N->getValueType(0) != MVT::f32)
9528 SDValue CondLHS = N->getOperand(0);
9529 SDValue CondRHS = N->getOperand(1);
9530 SDValue LHS = N->getOperand(2);
9531 SDValue RHS = N->getOperand(3);
9532 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9534 unsigned Opcode = 0;
9536 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9537 IsReversed = false; // x CC y ? x : y
9538 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9539 IsReversed = true ; // x CC y ? y : x
9553 // If LHS is NaN, an ordered comparison will be false and the result will
9554 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9555 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9556 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9557 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9559 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9560 // will return -0, so vmin can only be used for unsafe math or if one of
9561 // the operands is known to be nonzero.
9562 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9563 !DAG.getTarget().Options.UnsafeFPMath &&
9564 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9566 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9575 // If LHS is NaN, an ordered comparison will be false and the result will
9576 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9577 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9578 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9579 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9581 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9582 // will return +0, so vmax can only be used for unsafe math or if one of
9583 // the operands is known to be nonzero.
9584 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9585 !DAG.getTarget().Options.UnsafeFPMath &&
9586 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9588 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9594 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9597 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9599 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9600 SDValue Cmp = N->getOperand(4);
9601 if (Cmp.getOpcode() != ARMISD::CMPZ)
9602 // Only looking at EQ and NE cases.
9605 EVT VT = N->getValueType(0);
9607 SDValue LHS = Cmp.getOperand(0);
9608 SDValue RHS = Cmp.getOperand(1);
9609 SDValue FalseVal = N->getOperand(0);
9610 SDValue TrueVal = N->getOperand(1);
9611 SDValue ARMcc = N->getOperand(2);
9612 ARMCC::CondCodes CC =
9613 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9631 /// FIXME: Turn this into a target neutral optimization?
9633 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9634 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9635 N->getOperand(3), Cmp);
9636 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9638 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9639 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9640 N->getOperand(3), NewCmp);
9643 if (Res.getNode()) {
9644 APInt KnownZero, KnownOne;
9645 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9646 // Capture demanded bits information that would be otherwise lost.
9647 if (KnownZero == 0xfffffffe)
9648 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9649 DAG.getValueType(MVT::i1));
9650 else if (KnownZero == 0xffffff00)
9651 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9652 DAG.getValueType(MVT::i8));
9653 else if (KnownZero == 0xffff0000)
9654 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9655 DAG.getValueType(MVT::i16));
9661 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9662 DAGCombinerInfo &DCI) const {
9663 switch (N->getOpcode()) {
9665 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9666 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9667 case ISD::SUB: return PerformSUBCombine(N, DCI);
9668 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9669 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9670 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9671 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9672 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9673 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9674 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9675 case ISD::STORE: return PerformSTORECombine(N, DCI);
9676 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9677 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9678 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9679 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9680 case ISD::FP_TO_SINT:
9681 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9682 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9683 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9686 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9687 case ISD::SIGN_EXTEND:
9688 case ISD::ZERO_EXTEND:
9689 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9690 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9691 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9692 case ARMISD::VLD2DUP:
9693 case ARMISD::VLD3DUP:
9694 case ARMISD::VLD4DUP:
9695 return CombineBaseUpdate(N, DCI);
9696 case ARMISD::BUILD_VECTOR:
9697 return PerformARMBUILD_VECTORCombine(N, DCI);
9698 case ISD::INTRINSIC_VOID:
9699 case ISD::INTRINSIC_W_CHAIN:
9700 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9701 case Intrinsic::arm_neon_vld1:
9702 case Intrinsic::arm_neon_vld2:
9703 case Intrinsic::arm_neon_vld3:
9704 case Intrinsic::arm_neon_vld4:
9705 case Intrinsic::arm_neon_vld2lane:
9706 case Intrinsic::arm_neon_vld3lane:
9707 case Intrinsic::arm_neon_vld4lane:
9708 case Intrinsic::arm_neon_vst1:
9709 case Intrinsic::arm_neon_vst2:
9710 case Intrinsic::arm_neon_vst3:
9711 case Intrinsic::arm_neon_vst4:
9712 case Intrinsic::arm_neon_vst2lane:
9713 case Intrinsic::arm_neon_vst3lane:
9714 case Intrinsic::arm_neon_vst4lane:
9715 return CombineBaseUpdate(N, DCI);
9723 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9725 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9728 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9732 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9733 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9735 switch (VT.getSimpleVT().SimpleTy) {
9741 // Unaligned access can use (for example) LRDB, LRDH, LDR
9742 if (AllowsUnaligned) {
9744 *Fast = Subtarget->hasV7Ops();
9751 // For any little-endian targets with neon, we can support unaligned ld/st
9752 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9753 // A big-endian target may also explicitly support unaligned accesses
9754 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9764 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9765 unsigned AlignCheck) {
9766 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9767 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9770 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9771 unsigned DstAlign, unsigned SrcAlign,
9772 bool IsMemset, bool ZeroMemset,
9774 MachineFunction &MF) const {
9775 const Function *F = MF.getFunction();
9777 // See if we can use NEON instructions for this...
9778 if ((!IsMemset || ZeroMemset) &&
9779 Subtarget->hasNEON() &&
9780 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9781 Attribute::NoImplicitFloat)) {
9784 (memOpAlign(SrcAlign, DstAlign, 16) ||
9785 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9787 } else if (Size >= 8 &&
9788 (memOpAlign(SrcAlign, DstAlign, 8) ||
9789 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9795 // Lowering to i32/i16 if the size permits.
9801 // Let the target-independent logic figure it out.
9805 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9806 if (Val.getOpcode() != ISD::LOAD)
9809 EVT VT1 = Val.getValueType();
9810 if (!VT1.isSimple() || !VT1.isInteger() ||
9811 !VT2.isSimple() || !VT2.isInteger())
9814 switch (VT1.getSimpleVT().SimpleTy) {
9819 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9826 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9827 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9830 if (!isTypeLegal(EVT::getEVT(Ty1)))
9833 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9835 // Assuming the caller doesn't have a zeroext or signext return parameter,
9836 // truncation all the way down to i1 is valid.
9841 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9846 switch (VT.getSimpleVT().SimpleTy) {
9847 default: return false;
9862 if ((V & (Scale - 1)) != 0)
9865 return V == (V & ((1LL << 5) - 1));
9868 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9869 const ARMSubtarget *Subtarget) {
9876 switch (VT.getSimpleVT().SimpleTy) {
9877 default: return false;
9882 // + imm12 or - imm8
9884 return V == (V & ((1LL << 8) - 1));
9885 return V == (V & ((1LL << 12) - 1));
9888 // Same as ARM mode. FIXME: NEON?
9889 if (!Subtarget->hasVFP2())
9894 return V == (V & ((1LL << 8) - 1));
9898 /// isLegalAddressImmediate - Return true if the integer value can be used
9899 /// as the offset of the target addressing mode for load / store of the
9901 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9902 const ARMSubtarget *Subtarget) {
9909 if (Subtarget->isThumb1Only())
9910 return isLegalT1AddressImmediate(V, VT);
9911 else if (Subtarget->isThumb2())
9912 return isLegalT2AddressImmediate(V, VT, Subtarget);
9917 switch (VT.getSimpleVT().SimpleTy) {
9918 default: return false;
9923 return V == (V & ((1LL << 12) - 1));
9926 return V == (V & ((1LL << 8) - 1));
9929 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9934 return V == (V & ((1LL << 8) - 1));
9938 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9940 int Scale = AM.Scale;
9944 switch (VT.getSimpleVT().SimpleTy) {
9945 default: return false;
9954 return Scale == 2 || Scale == 4 || Scale == 8;
9957 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9961 // Note, we allow "void" uses (basically, uses that aren't loads or
9962 // stores), because arm allows folding a scale into many arithmetic
9963 // operations. This should be made more precise and revisited later.
9965 // Allow r << imm, but the imm has to be a multiple of two.
9966 if (Scale & 1) return false;
9967 return isPowerOf2_32(Scale);
9971 /// isLegalAddressingMode - Return true if the addressing mode represented
9972 /// by AM is legal for this target, for a load/store of the specified type.
9973 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9975 EVT VT = getValueType(Ty, true);
9976 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9979 // Can never fold addr of global into load/store.
9984 case 0: // no scale reg, must be "r+i" or "r", or "i".
9987 if (Subtarget->isThumb1Only())
9991 // ARM doesn't support any R+R*scale+imm addr modes.
9998 if (Subtarget->isThumb2())
9999 return isLegalT2ScaledAddressingMode(AM, VT);
10001 int Scale = AM.Scale;
10002 switch (VT.getSimpleVT().SimpleTy) {
10003 default: return false;
10007 if (Scale < 0) Scale = -Scale;
10011 return isPowerOf2_32(Scale & ~1);
10015 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10020 // Note, we allow "void" uses (basically, uses that aren't loads or
10021 // stores), because arm allows folding a scale into many arithmetic
10022 // operations. This should be made more precise and revisited later.
10024 // Allow r << imm, but the imm has to be a multiple of two.
10025 if (Scale & 1) return false;
10026 return isPowerOf2_32(Scale);
10032 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10033 /// icmp immediate, that is the target has icmp instructions which can compare
10034 /// a register against the immediate without having to materialize the
10035 /// immediate into a register.
10036 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10037 // Thumb2 and ARM modes can use cmn for negative immediates.
10038 if (!Subtarget->isThumb())
10039 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10040 if (Subtarget->isThumb2())
10041 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10042 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10043 return Imm >= 0 && Imm <= 255;
10046 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10047 /// *or sub* immediate, that is the target has add or sub instructions which can
10048 /// add a register with the immediate without having to materialize the
10049 /// immediate into a register.
10050 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10051 // Same encoding for add/sub, just flip the sign.
10052 int64_t AbsImm = llvm::abs64(Imm);
10053 if (!Subtarget->isThumb())
10054 return ARM_AM::getSOImmVal(AbsImm) != -1;
10055 if (Subtarget->isThumb2())
10056 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10057 // Thumb1 only has 8-bit unsigned immediate.
10058 return AbsImm >= 0 && AbsImm <= 255;
10061 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10062 bool isSEXTLoad, SDValue &Base,
10063 SDValue &Offset, bool &isInc,
10064 SelectionDAG &DAG) {
10065 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10068 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10069 // AddressingMode 3
10070 Base = Ptr->getOperand(0);
10071 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10072 int RHSC = (int)RHS->getZExtValue();
10073 if (RHSC < 0 && RHSC > -256) {
10074 assert(Ptr->getOpcode() == ISD::ADD);
10076 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10080 isInc = (Ptr->getOpcode() == ISD::ADD);
10081 Offset = Ptr->getOperand(1);
10083 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10084 // AddressingMode 2
10085 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10086 int RHSC = (int)RHS->getZExtValue();
10087 if (RHSC < 0 && RHSC > -0x1000) {
10088 assert(Ptr->getOpcode() == ISD::ADD);
10090 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10091 Base = Ptr->getOperand(0);
10096 if (Ptr->getOpcode() == ISD::ADD) {
10098 ARM_AM::ShiftOpc ShOpcVal=
10099 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10100 if (ShOpcVal != ARM_AM::no_shift) {
10101 Base = Ptr->getOperand(1);
10102 Offset = Ptr->getOperand(0);
10104 Base = Ptr->getOperand(0);
10105 Offset = Ptr->getOperand(1);
10110 isInc = (Ptr->getOpcode() == ISD::ADD);
10111 Base = Ptr->getOperand(0);
10112 Offset = Ptr->getOperand(1);
10116 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10120 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10121 bool isSEXTLoad, SDValue &Base,
10122 SDValue &Offset, bool &isInc,
10123 SelectionDAG &DAG) {
10124 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10127 Base = Ptr->getOperand(0);
10128 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10129 int RHSC = (int)RHS->getZExtValue();
10130 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10131 assert(Ptr->getOpcode() == ISD::ADD);
10133 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10135 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10136 isInc = Ptr->getOpcode() == ISD::ADD;
10137 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10145 /// getPreIndexedAddressParts - returns true by value, base pointer and
10146 /// offset pointer and addressing mode by reference if the node's address
10147 /// can be legally represented as pre-indexed load / store address.
10149 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10151 ISD::MemIndexedMode &AM,
10152 SelectionDAG &DAG) const {
10153 if (Subtarget->isThumb1Only())
10158 bool isSEXTLoad = false;
10159 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10160 Ptr = LD->getBasePtr();
10161 VT = LD->getMemoryVT();
10162 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10163 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10164 Ptr = ST->getBasePtr();
10165 VT = ST->getMemoryVT();
10170 bool isLegal = false;
10171 if (Subtarget->isThumb2())
10172 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10173 Offset, isInc, DAG);
10175 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10176 Offset, isInc, DAG);
10180 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10184 /// getPostIndexedAddressParts - returns true by value, base pointer and
10185 /// offset pointer and addressing mode by reference if this node can be
10186 /// combined with a load / store to form a post-indexed load / store.
10187 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10190 ISD::MemIndexedMode &AM,
10191 SelectionDAG &DAG) const {
10192 if (Subtarget->isThumb1Only())
10197 bool isSEXTLoad = false;
10198 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10199 VT = LD->getMemoryVT();
10200 Ptr = LD->getBasePtr();
10201 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10202 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10203 VT = ST->getMemoryVT();
10204 Ptr = ST->getBasePtr();
10209 bool isLegal = false;
10210 if (Subtarget->isThumb2())
10211 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10214 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10220 // Swap base ptr and offset to catch more post-index load / store when
10221 // it's legal. In Thumb2 mode, offset must be an immediate.
10222 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10223 !Subtarget->isThumb2())
10224 std::swap(Base, Offset);
10226 // Post-indexed load / store update the base pointer.
10231 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10235 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10238 const SelectionDAG &DAG,
10239 unsigned Depth) const {
10240 unsigned BitWidth = KnownOne.getBitWidth();
10241 KnownZero = KnownOne = APInt(BitWidth, 0);
10242 switch (Op.getOpcode()) {
10248 // These nodes' second result is a boolean
10249 if (Op.getResNo() == 0)
10251 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10253 case ARMISD::CMOV: {
10254 // Bits are known zero/one if known on the LHS and RHS.
10255 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10256 if (KnownZero == 0 && KnownOne == 0) return;
10258 APInt KnownZeroRHS, KnownOneRHS;
10259 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10260 KnownZero &= KnownZeroRHS;
10261 KnownOne &= KnownOneRHS;
10264 case ISD::INTRINSIC_W_CHAIN: {
10265 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10266 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10269 case Intrinsic::arm_ldaex:
10270 case Intrinsic::arm_ldrex: {
10271 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10272 unsigned MemBits = VT.getScalarType().getSizeInBits();
10273 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10281 //===----------------------------------------------------------------------===//
10282 // ARM Inline Assembly Support
10283 //===----------------------------------------------------------------------===//
10285 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10286 // Looking for "rev" which is V6+.
10287 if (!Subtarget->hasV6Ops())
10290 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10291 std::string AsmStr = IA->getAsmString();
10292 SmallVector<StringRef, 4> AsmPieces;
10293 SplitString(AsmStr, AsmPieces, ";\n");
10295 switch (AsmPieces.size()) {
10296 default: return false;
10298 AsmStr = AsmPieces[0];
10300 SplitString(AsmStr, AsmPieces, " \t,");
10303 if (AsmPieces.size() == 3 &&
10304 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10305 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10306 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10307 if (Ty && Ty->getBitWidth() == 32)
10308 return IntrinsicLowering::LowerToByteSwap(CI);
10316 /// getConstraintType - Given a constraint letter, return the type of
10317 /// constraint it is for this target.
10318 ARMTargetLowering::ConstraintType
10319 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10320 if (Constraint.size() == 1) {
10321 switch (Constraint[0]) {
10323 case 'l': return C_RegisterClass;
10324 case 'w': return C_RegisterClass;
10325 case 'h': return C_RegisterClass;
10326 case 'x': return C_RegisterClass;
10327 case 't': return C_RegisterClass;
10328 case 'j': return C_Other; // Constant for movw.
10329 // An address with a single base register. Due to the way we
10330 // currently handle addresses it is the same as an 'r' memory constraint.
10331 case 'Q': return C_Memory;
10333 } else if (Constraint.size() == 2) {
10334 switch (Constraint[0]) {
10336 // All 'U+' constraints are addresses.
10337 case 'U': return C_Memory;
10340 return TargetLowering::getConstraintType(Constraint);
10343 /// Examine constraint type and operand type and determine a weight value.
10344 /// This object must already have been set up with the operand type
10345 /// and the current alternative constraint selected.
10346 TargetLowering::ConstraintWeight
10347 ARMTargetLowering::getSingleConstraintMatchWeight(
10348 AsmOperandInfo &info, const char *constraint) const {
10349 ConstraintWeight weight = CW_Invalid;
10350 Value *CallOperandVal = info.CallOperandVal;
10351 // If we don't have a value, we can't do a match,
10352 // but allow it at the lowest weight.
10353 if (!CallOperandVal)
10355 Type *type = CallOperandVal->getType();
10356 // Look at the constraint type.
10357 switch (*constraint) {
10359 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10362 if (type->isIntegerTy()) {
10363 if (Subtarget->isThumb())
10364 weight = CW_SpecificReg;
10366 weight = CW_Register;
10370 if (type->isFloatingPointTy())
10371 weight = CW_Register;
10377 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10379 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10381 if (Constraint.size() == 1) {
10382 // GCC ARM Constraint Letters
10383 switch (Constraint[0]) {
10384 case 'l': // Low regs or general regs.
10385 if (Subtarget->isThumb())
10386 return RCPair(0U, &ARM::tGPRRegClass);
10387 return RCPair(0U, &ARM::GPRRegClass);
10388 case 'h': // High regs or no regs.
10389 if (Subtarget->isThumb())
10390 return RCPair(0U, &ARM::hGPRRegClass);
10393 return RCPair(0U, &ARM::GPRRegClass);
10395 if (VT == MVT::Other)
10397 if (VT == MVT::f32)
10398 return RCPair(0U, &ARM::SPRRegClass);
10399 if (VT.getSizeInBits() == 64)
10400 return RCPair(0U, &ARM::DPRRegClass);
10401 if (VT.getSizeInBits() == 128)
10402 return RCPair(0U, &ARM::QPRRegClass);
10405 if (VT == MVT::Other)
10407 if (VT == MVT::f32)
10408 return RCPair(0U, &ARM::SPR_8RegClass);
10409 if (VT.getSizeInBits() == 64)
10410 return RCPair(0U, &ARM::DPR_8RegClass);
10411 if (VT.getSizeInBits() == 128)
10412 return RCPair(0U, &ARM::QPR_8RegClass);
10415 if (VT == MVT::f32)
10416 return RCPair(0U, &ARM::SPRRegClass);
10420 if (StringRef("{cc}").equals_lower(Constraint))
10421 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10423 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10426 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10427 /// vector. If it is invalid, don't add anything to Ops.
10428 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10429 std::string &Constraint,
10430 std::vector<SDValue>&Ops,
10431 SelectionDAG &DAG) const {
10434 // Currently only support length 1 constraints.
10435 if (Constraint.length() != 1) return;
10437 char ConstraintLetter = Constraint[0];
10438 switch (ConstraintLetter) {
10441 case 'I': case 'J': case 'K': case 'L':
10442 case 'M': case 'N': case 'O':
10443 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10447 int64_t CVal64 = C->getSExtValue();
10448 int CVal = (int) CVal64;
10449 // None of these constraints allow values larger than 32 bits. Check
10450 // that the value fits in an int.
10451 if (CVal != CVal64)
10454 switch (ConstraintLetter) {
10456 // Constant suitable for movw, must be between 0 and
10458 if (Subtarget->hasV6T2Ops())
10459 if (CVal >= 0 && CVal <= 65535)
10463 if (Subtarget->isThumb1Only()) {
10464 // This must be a constant between 0 and 255, for ADD
10466 if (CVal >= 0 && CVal <= 255)
10468 } else if (Subtarget->isThumb2()) {
10469 // A constant that can be used as an immediate value in a
10470 // data-processing instruction.
10471 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10474 // A constant that can be used as an immediate value in a
10475 // data-processing instruction.
10476 if (ARM_AM::getSOImmVal(CVal) != -1)
10482 if (Subtarget->isThumb()) { // FIXME thumb2
10483 // This must be a constant between -255 and -1, for negated ADD
10484 // immediates. This can be used in GCC with an "n" modifier that
10485 // prints the negated value, for use with SUB instructions. It is
10486 // not useful otherwise but is implemented for compatibility.
10487 if (CVal >= -255 && CVal <= -1)
10490 // This must be a constant between -4095 and 4095. It is not clear
10491 // what this constraint is intended for. Implemented for
10492 // compatibility with GCC.
10493 if (CVal >= -4095 && CVal <= 4095)
10499 if (Subtarget->isThumb1Only()) {
10500 // A 32-bit value where only one byte has a nonzero value. Exclude
10501 // zero to match GCC. This constraint is used by GCC internally for
10502 // constants that can be loaded with a move/shift combination.
10503 // It is not useful otherwise but is implemented for compatibility.
10504 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10506 } else if (Subtarget->isThumb2()) {
10507 // A constant whose bitwise inverse can be used as an immediate
10508 // value in a data-processing instruction. This can be used in GCC
10509 // with a "B" modifier that prints the inverted value, for use with
10510 // BIC and MVN instructions. It is not useful otherwise but is
10511 // implemented for compatibility.
10512 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10515 // A constant whose bitwise inverse can be used as an immediate
10516 // value in a data-processing instruction. This can be used in GCC
10517 // with a "B" modifier that prints the inverted value, for use with
10518 // BIC and MVN instructions. It is not useful otherwise but is
10519 // implemented for compatibility.
10520 if (ARM_AM::getSOImmVal(~CVal) != -1)
10526 if (Subtarget->isThumb1Only()) {
10527 // This must be a constant between -7 and 7,
10528 // for 3-operand ADD/SUB immediate instructions.
10529 if (CVal >= -7 && CVal < 7)
10531 } else if (Subtarget->isThumb2()) {
10532 // A constant whose negation can be used as an immediate value in a
10533 // data-processing instruction. This can be used in GCC with an "n"
10534 // modifier that prints the negated value, for use with SUB
10535 // instructions. It is not useful otherwise but is implemented for
10537 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10540 // A constant whose negation can be used as an immediate value in a
10541 // data-processing instruction. This can be used in GCC with an "n"
10542 // modifier that prints the negated value, for use with SUB
10543 // instructions. It is not useful otherwise but is implemented for
10545 if (ARM_AM::getSOImmVal(-CVal) != -1)
10551 if (Subtarget->isThumb()) { // FIXME thumb2
10552 // This must be a multiple of 4 between 0 and 1020, for
10553 // ADD sp + immediate.
10554 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10557 // A power of two or a constant between 0 and 32. This is used in
10558 // GCC for the shift amount on shifted register operands, but it is
10559 // useful in general for any shift amounts.
10560 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10566 if (Subtarget->isThumb()) { // FIXME thumb2
10567 // This must be a constant between 0 and 31, for shift amounts.
10568 if (CVal >= 0 && CVal <= 31)
10574 if (Subtarget->isThumb()) { // FIXME thumb2
10575 // This must be a multiple of 4 between -508 and 508, for
10576 // ADD/SUB sp = sp + immediate.
10577 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10582 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10586 if (Result.getNode()) {
10587 Ops.push_back(Result);
10590 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10593 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10594 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10595 unsigned Opcode = Op->getOpcode();
10596 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10597 "Invalid opcode for Div/Rem lowering");
10598 bool isSigned = (Opcode == ISD::SDIVREM);
10599 EVT VT = Op->getValueType(0);
10600 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10603 switch (VT.getSimpleVT().SimpleTy) {
10604 default: llvm_unreachable("Unexpected request for libcall!");
10605 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10606 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10607 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10608 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10611 SDValue InChain = DAG.getEntryNode();
10613 TargetLowering::ArgListTy Args;
10614 TargetLowering::ArgListEntry Entry;
10615 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10616 EVT ArgVT = Op->getOperand(i).getValueType();
10617 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10618 Entry.Node = Op->getOperand(i);
10620 Entry.isSExt = isSigned;
10621 Entry.isZExt = !isSigned;
10622 Args.push_back(Entry);
10625 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10628 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10631 TargetLowering::CallLoweringInfo CLI(DAG);
10632 CLI.setDebugLoc(dl).setChain(InChain)
10633 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10634 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10636 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10637 return CallInfo.first;
10641 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10642 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10646 SDValue Chain = Op.getOperand(0);
10647 SDValue Size = Op.getOperand(1);
10649 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10650 DAG.getConstant(2, MVT::i32));
10653 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10654 Flag = Chain.getValue(1);
10656 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10657 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10659 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10660 Chain = NewSP.getValue(1);
10662 SDValue Ops[2] = { NewSP, Chain };
10663 return DAG.getMergeValues(Ops, DL);
10667 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10668 // The ARM target isn't yet aware of offsets.
10672 bool ARM::isBitFieldInvertedMask(unsigned v) {
10673 if (v == 0xffffffff)
10676 // there can be 1's on either or both "outsides", all the "inside"
10677 // bits must be 0's
10678 unsigned TO = CountTrailingOnes_32(v);
10679 unsigned LO = CountLeadingOnes_32(v);
10680 v = (v >> TO) << TO;
10681 v = (v << LO) >> LO;
10685 /// isFPImmLegal - Returns true if the target can instruction select the
10686 /// specified FP immediate natively. If false, the legalizer will
10687 /// materialize the FP immediate as a load from a constant pool.
10688 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10689 if (!Subtarget->hasVFP3())
10691 if (VT == MVT::f32)
10692 return ARM_AM::getFP32Imm(Imm) != -1;
10693 if (VT == MVT::f64)
10694 return ARM_AM::getFP64Imm(Imm) != -1;
10698 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10699 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10700 /// specified in the intrinsic calls.
10701 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10703 unsigned Intrinsic) const {
10704 switch (Intrinsic) {
10705 case Intrinsic::arm_neon_vld1:
10706 case Intrinsic::arm_neon_vld2:
10707 case Intrinsic::arm_neon_vld3:
10708 case Intrinsic::arm_neon_vld4:
10709 case Intrinsic::arm_neon_vld2lane:
10710 case Intrinsic::arm_neon_vld3lane:
10711 case Intrinsic::arm_neon_vld4lane: {
10712 Info.opc = ISD::INTRINSIC_W_CHAIN;
10713 // Conservatively set memVT to the entire set of vectors loaded.
10714 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10715 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10716 Info.ptrVal = I.getArgOperand(0);
10718 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10719 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10720 Info.vol = false; // volatile loads with NEON intrinsics not supported
10721 Info.readMem = true;
10722 Info.writeMem = false;
10725 case Intrinsic::arm_neon_vst1:
10726 case Intrinsic::arm_neon_vst2:
10727 case Intrinsic::arm_neon_vst3:
10728 case Intrinsic::arm_neon_vst4:
10729 case Intrinsic::arm_neon_vst2lane:
10730 case Intrinsic::arm_neon_vst3lane:
10731 case Intrinsic::arm_neon_vst4lane: {
10732 Info.opc = ISD::INTRINSIC_VOID;
10733 // Conservatively set memVT to the entire set of vectors stored.
10734 unsigned NumElts = 0;
10735 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10736 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10737 if (!ArgTy->isVectorTy())
10739 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10741 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10742 Info.ptrVal = I.getArgOperand(0);
10744 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10745 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10746 Info.vol = false; // volatile stores with NEON intrinsics not supported
10747 Info.readMem = false;
10748 Info.writeMem = true;
10751 case Intrinsic::arm_ldaex:
10752 case Intrinsic::arm_ldrex: {
10753 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10754 Info.opc = ISD::INTRINSIC_W_CHAIN;
10755 Info.memVT = MVT::getVT(PtrTy->getElementType());
10756 Info.ptrVal = I.getArgOperand(0);
10758 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10760 Info.readMem = true;
10761 Info.writeMem = false;
10764 case Intrinsic::arm_stlex:
10765 case Intrinsic::arm_strex: {
10766 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10767 Info.opc = ISD::INTRINSIC_W_CHAIN;
10768 Info.memVT = MVT::getVT(PtrTy->getElementType());
10769 Info.ptrVal = I.getArgOperand(1);
10771 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10773 Info.readMem = false;
10774 Info.writeMem = true;
10777 case Intrinsic::arm_stlexd:
10778 case Intrinsic::arm_strexd: {
10779 Info.opc = ISD::INTRINSIC_W_CHAIN;
10780 Info.memVT = MVT::i64;
10781 Info.ptrVal = I.getArgOperand(2);
10785 Info.readMem = false;
10786 Info.writeMem = true;
10789 case Intrinsic::arm_ldaexd:
10790 case Intrinsic::arm_ldrexd: {
10791 Info.opc = ISD::INTRINSIC_W_CHAIN;
10792 Info.memVT = MVT::i64;
10793 Info.ptrVal = I.getArgOperand(0);
10797 Info.readMem = true;
10798 Info.writeMem = false;
10808 /// \brief Returns true if it is beneficial to convert a load of a constant
10809 /// to just the constant itself.
10810 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10812 assert(Ty->isIntegerTy());
10814 unsigned Bits = Ty->getPrimitiveSizeInBits();
10815 if (Bits == 0 || Bits > 32)
10820 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10821 // Loads and stores less than 64-bits are already atomic; ones above that
10822 // are doomed anyway, so defer to the default libcall and blame the OS when
10823 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10824 // anything for those.
10825 bool IsMClass = Subtarget->isMClass();
10826 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10827 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10828 return Size == 64 && !IsMClass;
10829 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10830 return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10833 // For the real atomic operations, we have ldrex/strex up to 32 bits,
10834 // and up to 64 bits on the non-M profiles
10835 unsigned AtomicLimit = IsMClass ? 32 : 64;
10836 return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10839 // This has so far only been implemented for MachO.
10840 bool ARMTargetLowering::useLoadStackGuardNode() const {
10841 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10844 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10845 AtomicOrdering Ord) const {
10846 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10847 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10849 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10851 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10852 // intrinsic must return {i32, i32} and we have to recombine them into a
10853 // single i64 here.
10854 if (ValTy->getPrimitiveSizeInBits() == 64) {
10855 Intrinsic::ID Int =
10856 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10857 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10859 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10860 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10862 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10863 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10864 if (!Subtarget->isLittle())
10865 std::swap (Lo, Hi);
10866 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10867 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10868 return Builder.CreateOr(
10869 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10872 Type *Tys[] = { Addr->getType() };
10873 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10874 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10876 return Builder.CreateTruncOrBitCast(
10877 Builder.CreateCall(Ldrex, Addr),
10878 cast<PointerType>(Addr->getType())->getElementType());
10881 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10883 AtomicOrdering Ord) const {
10884 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10886 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10888 // Since the intrinsics must have legal type, the i64 intrinsics take two
10889 // parameters: "i32, i32". We must marshal Val into the appropriate form
10890 // before the call.
10891 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10892 Intrinsic::ID Int =
10893 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10894 Function *Strex = Intrinsic::getDeclaration(M, Int);
10895 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10897 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10898 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10899 if (!Subtarget->isLittle())
10900 std::swap (Lo, Hi);
10901 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10902 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10905 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10906 Type *Tys[] = { Addr->getType() };
10907 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10909 return Builder.CreateCall2(
10910 Strex, Builder.CreateZExtOrBitCast(
10911 Val, Strex->getFunctionType()->getParamType(0)),
10923 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10924 uint64_t &Members) {
10925 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10926 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10927 uint64_t SubMembers = 0;
10928 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10930 Members += SubMembers;
10932 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10933 uint64_t SubMembers = 0;
10934 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10936 Members += SubMembers * AT->getNumElements();
10937 } else if (Ty->isFloatTy()) {
10938 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10942 } else if (Ty->isDoubleTy()) {
10943 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10947 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10954 return VT->getBitWidth() == 64;
10956 return VT->getBitWidth() == 128;
10958 switch (VT->getBitWidth()) {
10971 return (Members > 0 && Members <= 4);
10974 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10975 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10976 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10977 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10978 CallingConv::ARM_AAPCS_VFP)
10981 HABaseType Base = HA_UNKNOWN;
10982 uint64_t Members = 0;
10983 bool result = isHomogeneousAggregate(Ty, Base, Members);
10984 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");