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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "arm-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62 cl::desc("Generate calls via indirect call instructions"),
66 ARMInterworking("arm-interworking", cl::Hidden,
67 cl::desc("Enable / disable ARM interworking (for debugging only)"),
71 class ARMCCState : public CCState {
73 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
76 : CCState(CC, isVarArg, MF, locs, C) {
77 assert(((PC == Call) || (PC == Prologue)) &&
78 "ARMCCState users must specify whether their context is call"
79 "or prologue generation.");
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87 ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91 MVT PromotedBitwiseVT) {
92 if (VT != PromotedLdStVT) {
93 setOperationAction(ISD::LOAD, VT, Promote);
94 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
96 setOperationAction(ISD::STORE, VT, Promote);
97 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
100 MVT ElemTy = VT.getVectorElementType();
101 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102 setOperationAction(ISD::SETCC, VT, Custom);
103 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105 if (ElemTy == MVT::i32) {
106 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
111 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
116 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
117 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
118 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
119 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120 setOperationAction(ISD::SELECT, VT, Expand);
121 setOperationAction(ISD::SELECT_CC, VT, Expand);
122 setOperationAction(ISD::VSELECT, VT, Expand);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124 if (VT.isInteger()) {
125 setOperationAction(ISD::SHL, VT, Custom);
126 setOperationAction(ISD::SRA, VT, Custom);
127 setOperationAction(ISD::SRL, VT, Custom);
130 // Promote all bit-wise operations.
131 if (VT.isInteger() && VT != PromotedBitwiseVT) {
132 setOperationAction(ISD::AND, VT, Promote);
133 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::OR, VT, Promote);
135 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::XOR, VT, Promote);
137 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140 // Neon does not support vector divide/remainder operations.
141 setOperationAction(ISD::SDIV, VT, Expand);
142 setOperationAction(ISD::UDIV, VT, Expand);
143 setOperationAction(ISD::FDIV, VT, Expand);
144 setOperationAction(ISD::SREM, VT, Expand);
145 setOperationAction(ISD::UREM, VT, Expand);
146 setOperationAction(ISD::FREM, VT, Expand);
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150 addRegisterClass(VT, &ARM::DPRRegClass);
151 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155 addRegisterClass(VT, &ARM::DPairRegClass);
156 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
160 const ARMSubtarget &STI)
161 : TargetLowering(TM), Subtarget(&STI) {
162 RegInfo = Subtarget->getRegisterInfo();
163 Itins = Subtarget->getInstrItineraryData();
165 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167 if (Subtarget->isTargetMachO()) {
168 // Uses VFP for Thumb libfuncs if available.
169 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
170 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
171 // Single-precision floating-point arithmetic.
172 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
173 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
174 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
175 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
177 // Double-precision floating-point arithmetic.
178 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
179 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
180 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
181 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
183 // Single-precision comparisons.
184 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
185 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
186 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
187 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
188 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
189 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
190 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
191 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
193 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
194 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
195 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
196 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
202 // Double-precision comparisons.
203 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
204 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
205 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
206 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
207 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
208 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
209 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
210 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
212 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
213 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
214 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
215 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
221 // Floating-point to integer conversions.
222 // i64 conversions are done via library routines even when generating VFP
223 // instructions, so use the same ones.
224 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
225 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
226 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
227 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
229 // Conversions between floating types.
230 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
231 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
233 // Integer to floating-point conversions.
234 // i64 conversions are done via library routines even when generating VFP
235 // instructions, so use the same ones.
236 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
237 // e.g., __floatunsidf vs. __floatunssidfvfp.
238 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
239 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
240 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
241 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245 // These libcalls are not available in 32-bit.
246 setLibcallName(RTLIB::SHL_I128, nullptr);
247 setLibcallName(RTLIB::SRL_I128, nullptr);
248 setLibcallName(RTLIB::SRA_I128, nullptr);
250 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
251 !Subtarget->isTargetWindows()) {
252 static const struct {
253 const RTLIB::Libcall Op;
254 const char * const Name;
255 const CallingConv::ID CC;
256 const ISD::CondCode Cond;
258 // Double-precision floating-point arithmetic helper functions
259 // RTABI chapter 4.1.2, Table 2
260 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 // Double-precision floating-point comparison helper functions
266 // RTABI chapter 4.1.2, Table 3
267 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
268 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
269 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 // Single-precision floating-point arithmetic helper functions
277 // RTABI chapter 4.1.2, Table 4
278 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 // Single-precision floating-point comparison helper functions
284 // RTABI chapter 4.1.2, Table 5
285 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 // Floating-point to integer conversions.
295 // RTABI chapter 4.1.2, Table 6
296 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 // Conversions between floating types.
306 // RTABI chapter 4.1.2, Table 7
307 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 // Integer to floating-point conversions.
312 // RTABI chapter 4.1.2, Table 8
313 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 // Long long helper functions
323 // RTABI chapter 4.2, Table 9
324 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Integer division functions
330 // RTABI chapter 4.3.1
331 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 // RTABI chapter 4.3.4
342 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 for (const auto &LC : LibraryCalls) {
348 setLibcallName(LC.Op, LC.Name);
349 setLibcallCallingConv(LC.Op, LC.CC);
350 if (LC.Cond != ISD::SETCC_INVALID)
351 setCmpLibcallCC(LC.Op, LC.Cond);
355 if (Subtarget->isTargetWindows()) {
356 static const struct {
357 const RTLIB::Libcall Op;
358 const char * const Name;
359 const CallingConv::ID CC;
361 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
362 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371 for (const auto &LC : LibraryCalls) {
372 setLibcallName(LC.Op, LC.Name);
373 setLibcallCallingConv(LC.Op, LC.CC);
377 // Use divmod compiler-rt calls for iOS 5.0 and later.
378 if (Subtarget->getTargetTriple().isiOS() &&
379 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
380 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
381 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384 // The half <-> float conversion functions are always soft-float, but are
385 // needed for some targets which use a hard-float calling convention by
387 if (Subtarget->isAAPCS_ABI()) {
388 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
393 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
394 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397 if (Subtarget->isThumb1Only())
398 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
400 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
401 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
402 !Subtarget->isThumb1Only()) {
403 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
404 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407 for (MVT VT : MVT::vector_valuetypes()) {
408 for (MVT InnerVT : MVT::vector_valuetypes()) {
409 setTruncStoreAction(VT, InnerVT, Expand);
410 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
411 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
412 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415 setOperationAction(ISD::MULHS, VT, Expand);
416 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
417 setOperationAction(ISD::MULHU, VT, Expand);
418 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
420 setOperationAction(ISD::BSWAP, VT, Expand);
423 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
426 if (Subtarget->hasNEON()) {
427 addDRTypeForNEON(MVT::v2f32);
428 addDRTypeForNEON(MVT::v8i8);
429 addDRTypeForNEON(MVT::v4i16);
430 addDRTypeForNEON(MVT::v2i32);
431 addDRTypeForNEON(MVT::v1i64);
433 addQRTypeForNEON(MVT::v4f32);
434 addQRTypeForNEON(MVT::v2f64);
435 addQRTypeForNEON(MVT::v16i8);
436 addQRTypeForNEON(MVT::v8i16);
437 addQRTypeForNEON(MVT::v4i32);
438 addQRTypeForNEON(MVT::v2i64);
440 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441 // neither Neon nor VFP support any arithmetic operations on it.
442 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443 // supported for v4f32.
444 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447 // FIXME: Code duplication: FDIV and FREM are expanded always, see
448 // ARMTargetLowering::addTypeForNEON method for details.
449 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451 // FIXME: Create unittest.
452 // In another words, find a way when "copysign" appears in DAG with vector
454 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455 // FIXME: Code duplication: SETCC has custom operation action, see
456 // ARMTargetLowering::addTypeForNEON method for details.
457 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458 // FIXME: Create unittest for FNEG and for FABS.
459 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495 // Mark v2f32 intrinsics.
496 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512 // Neon does not support some operations on v1i64 and v2i64 types.
513 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514 // Custom handling for some quad-vector types to detect VMULL.
515 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518 // Custom handling for some vector types to avoid expensive expansions
519 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526 // a destination type that is wider than the source, and nor does
527 // it have a FP_TO_[SU]INT instruction with a narrower destination than
529 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
535 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
537 // NEON does not have single instruction CTPOP for vectors with element
538 // types wider than 8-bits. However, custom lowering can leverage the
539 // v8i8/v16i8 vcnt instruction.
540 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
541 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
542 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
543 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
545 // NEON only has FMA instructions as of VFP4.
546 if (!Subtarget->hasVFP4()) {
547 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
548 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
551 setTargetDAGCombine(ISD::INTRINSIC_VOID);
552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
554 setTargetDAGCombine(ISD::SHL);
555 setTargetDAGCombine(ISD::SRL);
556 setTargetDAGCombine(ISD::SRA);
557 setTargetDAGCombine(ISD::SIGN_EXTEND);
558 setTargetDAGCombine(ISD::ZERO_EXTEND);
559 setTargetDAGCombine(ISD::ANY_EXTEND);
560 setTargetDAGCombine(ISD::SELECT_CC);
561 setTargetDAGCombine(ISD::BUILD_VECTOR);
562 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
563 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
564 setTargetDAGCombine(ISD::STORE);
565 setTargetDAGCombine(ISD::FP_TO_SINT);
566 setTargetDAGCombine(ISD::FP_TO_UINT);
567 setTargetDAGCombine(ISD::FDIV);
568 setTargetDAGCombine(ISD::LOAD);
570 // It is legal to extload from v4i8 to v4i16 or v4i32.
571 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
572 MVT::v4i16, MVT::v2i16,
574 for (unsigned i = 0; i < 6; ++i) {
575 for (MVT VT : MVT::integer_vector_valuetypes()) {
576 setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
577 setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
578 setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
583 // ARM and Thumb2 support UMLAL/SMLAL.
584 if (!Subtarget->isThumb1Only())
585 setTargetDAGCombine(ISD::ADDC);
587 if (Subtarget->isFPOnlySP()) {
588 // When targetting a floating-point unit with only single-precision
589 // operations, f64 is legal for the few double-precision instructions which
590 // are present However, no double-precision operations other than moves,
591 // loads and stores are provided by the hardware.
592 setOperationAction(ISD::FADD, MVT::f64, Expand);
593 setOperationAction(ISD::FSUB, MVT::f64, Expand);
594 setOperationAction(ISD::FMUL, MVT::f64, Expand);
595 setOperationAction(ISD::FMA, MVT::f64, Expand);
596 setOperationAction(ISD::FDIV, MVT::f64, Expand);
597 setOperationAction(ISD::FREM, MVT::f64, Expand);
598 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
600 setOperationAction(ISD::FNEG, MVT::f64, Expand);
601 setOperationAction(ISD::FABS, MVT::f64, Expand);
602 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
603 setOperationAction(ISD::FSIN, MVT::f64, Expand);
604 setOperationAction(ISD::FCOS, MVT::f64, Expand);
605 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
606 setOperationAction(ISD::FPOW, MVT::f64, Expand);
607 setOperationAction(ISD::FLOG, MVT::f64, Expand);
608 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
609 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
610 setOperationAction(ISD::FEXP, MVT::f64, Expand);
611 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
612 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
613 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
614 setOperationAction(ISD::FRINT, MVT::f64, Expand);
615 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
616 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
617 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
618 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
621 computeRegisterProperties();
623 // ARM does not have floating-point extending loads.
624 for (MVT VT : MVT::fp_valuetypes()) {
625 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
626 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
629 // ... or truncating stores
630 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
631 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
632 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
634 // ARM does not have i1 sign extending load.
635 for (MVT VT : MVT::integer_valuetypes())
636 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
638 // ARM supports all 4 flavors of integer indexed load / store.
639 if (!Subtarget->isThumb1Only()) {
640 for (unsigned im = (unsigned)ISD::PRE_INC;
641 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
642 setIndexedLoadAction(im, MVT::i1, Legal);
643 setIndexedLoadAction(im, MVT::i8, Legal);
644 setIndexedLoadAction(im, MVT::i16, Legal);
645 setIndexedLoadAction(im, MVT::i32, Legal);
646 setIndexedStoreAction(im, MVT::i1, Legal);
647 setIndexedStoreAction(im, MVT::i8, Legal);
648 setIndexedStoreAction(im, MVT::i16, Legal);
649 setIndexedStoreAction(im, MVT::i32, Legal);
653 setOperationAction(ISD::SADDO, MVT::i32, Custom);
654 setOperationAction(ISD::UADDO, MVT::i32, Custom);
655 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
656 setOperationAction(ISD::USUBO, MVT::i32, Custom);
658 // i64 operation support.
659 setOperationAction(ISD::MUL, MVT::i64, Expand);
660 setOperationAction(ISD::MULHU, MVT::i32, Expand);
661 if (Subtarget->isThumb1Only()) {
662 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
663 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
665 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
666 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
667 setOperationAction(ISD::MULHS, MVT::i32, Expand);
669 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
670 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
671 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
672 setOperationAction(ISD::SRL, MVT::i64, Custom);
673 setOperationAction(ISD::SRA, MVT::i64, Custom);
675 if (!Subtarget->isThumb1Only()) {
676 // FIXME: We should do this for Thumb1 as well.
677 setOperationAction(ISD::ADDC, MVT::i32, Custom);
678 setOperationAction(ISD::ADDE, MVT::i32, Custom);
679 setOperationAction(ISD::SUBC, MVT::i32, Custom);
680 setOperationAction(ISD::SUBE, MVT::i32, Custom);
683 // ARM does not have ROTL.
684 setOperationAction(ISD::ROTL, MVT::i32, Expand);
685 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
686 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
687 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
688 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
690 // These just redirect to CTTZ and CTLZ on ARM.
691 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
692 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
694 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
696 // Only ARMv6 has BSWAP.
697 if (!Subtarget->hasV6Ops())
698 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
700 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
701 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
702 // These are expanded into libcalls if the cpu doesn't have HW divider.
703 setOperationAction(ISD::SDIV, MVT::i32, Expand);
704 setOperationAction(ISD::UDIV, MVT::i32, Expand);
707 // FIXME: Also set divmod for SREM on EABI
708 setOperationAction(ISD::SREM, MVT::i32, Expand);
709 setOperationAction(ISD::UREM, MVT::i32, Expand);
710 // Register based DivRem for AEABI (RTABI 4.2)
711 if (Subtarget->isTargetAEABI()) {
712 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
713 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
714 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
715 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
716 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
717 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
718 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
719 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
721 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
722 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
723 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
724 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
725 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
730 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
731 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
733 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
734 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
737 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
738 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
739 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
740 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
741 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
743 setOperationAction(ISD::TRAP, MVT::Other, Legal);
745 // Use the default implementation.
746 setOperationAction(ISD::VASTART, MVT::Other, Custom);
747 setOperationAction(ISD::VAARG, MVT::Other, Expand);
748 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
749 setOperationAction(ISD::VAEND, MVT::Other, Expand);
750 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
751 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
753 if (!Subtarget->isTargetMachO()) {
754 // Non-MachO platforms may return values in these registers via the
755 // personality function.
756 setExceptionPointerRegister(ARM::R0);
757 setExceptionSelectorRegister(ARM::R1);
760 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
761 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
763 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
765 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
766 // the default expansion. If we are targeting a single threaded system,
767 // then set them all for expand so we can lower them later into their
769 if (TM.Options.ThreadModel == ThreadModel::Single)
770 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
771 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
772 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
773 // to ldrex/strex loops already.
774 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
776 // On v8, we have particularly efficient implementations of atomic fences
777 // if they can be combined with nearby atomic loads and stores.
778 if (!Subtarget->hasV8Ops()) {
779 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
780 setInsertFencesForAtomic(true);
783 // If there's anything we can use as a barrier, go through custom lowering
785 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
786 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
788 // Set them all for expansion, which will force libcalls.
789 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
801 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
802 // Unordered/Monotonic case.
803 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
804 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
807 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
809 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
810 if (!Subtarget->hasV6Ops()) {
811 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
812 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
814 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
816 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
817 !Subtarget->isThumb1Only()) {
818 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
819 // iff target supports vfp2.
820 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
821 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
824 // We want to custom lower some of our intrinsics.
825 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
826 if (Subtarget->isTargetDarwin()) {
827 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
828 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
829 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
832 setOperationAction(ISD::SETCC, MVT::i32, Expand);
833 setOperationAction(ISD::SETCC, MVT::f32, Expand);
834 setOperationAction(ISD::SETCC, MVT::f64, Expand);
835 setOperationAction(ISD::SELECT, MVT::i32, Custom);
836 setOperationAction(ISD::SELECT, MVT::f32, Custom);
837 setOperationAction(ISD::SELECT, MVT::f64, Custom);
838 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
839 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
840 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
842 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
843 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
844 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
845 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
846 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
848 // We don't support sin/cos/fmod/copysign/pow
849 setOperationAction(ISD::FSIN, MVT::f64, Expand);
850 setOperationAction(ISD::FSIN, MVT::f32, Expand);
851 setOperationAction(ISD::FCOS, MVT::f32, Expand);
852 setOperationAction(ISD::FCOS, MVT::f64, Expand);
853 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
854 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
855 setOperationAction(ISD::FREM, MVT::f64, Expand);
856 setOperationAction(ISD::FREM, MVT::f32, Expand);
857 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
858 !Subtarget->isThumb1Only()) {
859 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
860 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
862 setOperationAction(ISD::FPOW, MVT::f64, Expand);
863 setOperationAction(ISD::FPOW, MVT::f32, Expand);
865 if (!Subtarget->hasVFP4()) {
866 setOperationAction(ISD::FMA, MVT::f64, Expand);
867 setOperationAction(ISD::FMA, MVT::f32, Expand);
870 // Various VFP goodness
871 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
872 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
873 if (Subtarget->hasVFP2()) {
874 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
875 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
876 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
877 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
880 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
881 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
882 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
883 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
886 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
887 if (!Subtarget->hasFP16()) {
888 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
889 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
893 // Combine sin / cos into one node or libcall if possible.
894 if (Subtarget->hasSinCos()) {
895 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
896 setLibcallName(RTLIB::SINCOS_F64, "sincos");
897 if (Subtarget->getTargetTriple().isiOS()) {
898 // For iOS, we don't want to the normal expansion of a libcall to
899 // sincos. We want to issue a libcall to __sincos_stret.
900 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
901 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
905 // FP-ARMv8 implements a lot of rounding-like FP operations.
906 if (Subtarget->hasFPARMv8()) {
907 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
908 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
909 setOperationAction(ISD::FROUND, MVT::f32, Legal);
910 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
911 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
912 setOperationAction(ISD::FRINT, MVT::f32, Legal);
913 if (!Subtarget->isFPOnlySP()) {
914 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
915 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
916 setOperationAction(ISD::FROUND, MVT::f64, Legal);
917 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
918 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
919 setOperationAction(ISD::FRINT, MVT::f64, Legal);
922 // We have target-specific dag combine patterns for the following nodes:
923 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
924 setTargetDAGCombine(ISD::ADD);
925 setTargetDAGCombine(ISD::SUB);
926 setTargetDAGCombine(ISD::MUL);
927 setTargetDAGCombine(ISD::AND);
928 setTargetDAGCombine(ISD::OR);
929 setTargetDAGCombine(ISD::XOR);
931 if (Subtarget->hasV6Ops())
932 setTargetDAGCombine(ISD::SRL);
934 setStackPointerRegisterToSaveRestore(ARM::SP);
936 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
937 !Subtarget->hasVFP2())
938 setSchedulingPreference(Sched::RegPressure);
940 setSchedulingPreference(Sched::Hybrid);
942 //// temporary - rewrite interface to use type
943 MaxStoresPerMemset = 8;
944 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
945 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
946 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
947 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
948 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
950 // On ARM arguments smaller than 4 bytes are extended, so all arguments
951 // are at least 4 bytes aligned.
952 setMinStackArgumentAlignment(4);
954 // Prefer likely predicted branches to selects on out-of-order cores.
955 PredictableSelectIsExpensive = Subtarget->isLikeA9();
957 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
960 // FIXME: It might make sense to define the representative register class as the
961 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
962 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
963 // SPR's representative would be DPR_VFP2. This should work well if register
964 // pressure tracking were modified such that a register use would increment the
965 // pressure of the register class's representative and all of it's super
966 // classes' representatives transitively. We have not implemented this because
967 // of the difficulty prior to coalescing of modeling operand register classes
968 // due to the common occurrence of cross class copies and subregister insertions
970 std::pair<const TargetRegisterClass*, uint8_t>
971 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
972 const TargetRegisterClass *RRC = nullptr;
974 switch (VT.SimpleTy) {
976 return TargetLowering::findRepresentativeClass(VT);
977 // Use DPR as representative register class for all floating point
978 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
979 // the cost is 1 for both f32 and f64.
980 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
981 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
982 RRC = &ARM::DPRRegClass;
983 // When NEON is used for SP, only half of the register file is available
984 // because operations that define both SP and DP results will be constrained
985 // to the VFP2 class (D0-D15). We currently model this constraint prior to
986 // coalescing by double-counting the SP regs. See the FIXME above.
987 if (Subtarget->useNEONForSinglePrecisionFP())
990 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
991 case MVT::v4f32: case MVT::v2f64:
992 RRC = &ARM::DPRRegClass;
996 RRC = &ARM::DPRRegClass;
1000 RRC = &ARM::DPRRegClass;
1004 return std::make_pair(RRC, Cost);
1007 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1009 default: return nullptr;
1010 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1011 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1012 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1013 case ARMISD::CALL: return "ARMISD::CALL";
1014 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1015 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1016 case ARMISD::tCALL: return "ARMISD::tCALL";
1017 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1018 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1019 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1020 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1021 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1022 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1023 case ARMISD::CMP: return "ARMISD::CMP";
1024 case ARMISD::CMN: return "ARMISD::CMN";
1025 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1026 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1027 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1028 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1029 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1031 case ARMISD::CMOV: return "ARMISD::CMOV";
1033 case ARMISD::RBIT: return "ARMISD::RBIT";
1035 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1036 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1037 case ARMISD::SITOF: return "ARMISD::SITOF";
1038 case ARMISD::UITOF: return "ARMISD::UITOF";
1040 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1041 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1042 case ARMISD::RRX: return "ARMISD::RRX";
1044 case ARMISD::ADDC: return "ARMISD::ADDC";
1045 case ARMISD::ADDE: return "ARMISD::ADDE";
1046 case ARMISD::SUBC: return "ARMISD::SUBC";
1047 case ARMISD::SUBE: return "ARMISD::SUBE";
1049 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1050 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1052 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1053 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1055 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1057 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1059 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1061 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1063 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1065 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1067 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1068 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1069 case ARMISD::VCGE: return "ARMISD::VCGE";
1070 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1071 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1072 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1073 case ARMISD::VCGT: return "ARMISD::VCGT";
1074 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1075 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1076 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1077 case ARMISD::VTST: return "ARMISD::VTST";
1079 case ARMISD::VSHL: return "ARMISD::VSHL";
1080 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1081 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1082 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1083 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1084 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1085 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1086 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1087 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1088 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1089 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1090 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1091 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1092 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1093 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1094 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1095 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1096 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1097 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1098 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1099 case ARMISD::VDUP: return "ARMISD::VDUP";
1100 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1101 case ARMISD::VEXT: return "ARMISD::VEXT";
1102 case ARMISD::VREV64: return "ARMISD::VREV64";
1103 case ARMISD::VREV32: return "ARMISD::VREV32";
1104 case ARMISD::VREV16: return "ARMISD::VREV16";
1105 case ARMISD::VZIP: return "ARMISD::VZIP";
1106 case ARMISD::VUZP: return "ARMISD::VUZP";
1107 case ARMISD::VTRN: return "ARMISD::VTRN";
1108 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1109 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1110 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1111 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1112 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1113 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1114 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1115 case ARMISD::FMAX: return "ARMISD::FMAX";
1116 case ARMISD::FMIN: return "ARMISD::FMIN";
1117 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1118 case ARMISD::VMINNM: return "ARMISD::VMIN";
1119 case ARMISD::BFI: return "ARMISD::BFI";
1120 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1121 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1122 case ARMISD::VBSL: return "ARMISD::VBSL";
1123 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1124 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1125 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1126 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1127 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1128 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1129 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1130 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1131 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1132 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1133 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1134 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1135 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1136 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1137 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1138 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1139 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1140 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1141 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1142 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1147 if (!VT.isVector()) return getPointerTy();
1148 return VT.changeVectorElementTypeToInteger();
1151 /// getRegClassFor - Return the register class that should be used for the
1152 /// specified value type.
1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1154 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1155 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1156 // load / store 4 to 8 consecutive D registers.
1157 if (Subtarget->hasNEON()) {
1158 if (VT == MVT::v4i64)
1159 return &ARM::QQPRRegClass;
1160 if (VT == MVT::v8i64)
1161 return &ARM::QQQQPRRegClass;
1163 return TargetLowering::getRegClassFor(VT);
1166 // Create a fast isel object.
1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1169 const TargetLibraryInfo *libInfo) const {
1170 return ARM::createFastISel(funcInfo, libInfo);
1173 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1174 /// be used for loads / stores from the global.
1175 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1176 return (Subtarget->isThumb1Only() ? 127 : 4095);
1179 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1180 unsigned NumVals = N->getNumValues();
1182 return Sched::RegPressure;
1184 for (unsigned i = 0; i != NumVals; ++i) {
1185 EVT VT = N->getValueType(i);
1186 if (VT == MVT::Glue || VT == MVT::Other)
1188 if (VT.isFloatingPoint() || VT.isVector())
1192 if (!N->isMachineOpcode())
1193 return Sched::RegPressure;
1195 // Load are scheduled for latency even if there instruction itinerary
1196 // is not available.
1197 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1200 if (MCID.getNumDefs() == 0)
1201 return Sched::RegPressure;
1202 if (!Itins->isEmpty() &&
1203 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206 return Sched::RegPressure;
1209 //===----------------------------------------------------------------------===//
1211 //===----------------------------------------------------------------------===//
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1216 default: llvm_unreachable("Unknown condition code!");
1217 case ISD::SETNE: return ARMCC::NE;
1218 case ISD::SETEQ: return ARMCC::EQ;
1219 case ISD::SETGT: return ARMCC::GT;
1220 case ISD::SETGE: return ARMCC::GE;
1221 case ISD::SETLT: return ARMCC::LT;
1222 case ISD::SETLE: return ARMCC::LE;
1223 case ISD::SETUGT: return ARMCC::HI;
1224 case ISD::SETUGE: return ARMCC::HS;
1225 case ISD::SETULT: return ARMCC::LO;
1226 case ISD::SETULE: return ARMCC::LS;
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232 ARMCC::CondCodes &CondCode2) {
1233 CondCode2 = ARMCC::AL;
1235 default: llvm_unreachable("Unknown FP condition!");
1237 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1239 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1241 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245 case ISD::SETO: CondCode = ARMCC::VC; break;
1246 case ISD::SETUO: CondCode = ARMCC::VS; break;
1247 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1251 case ISD::SETULT: CondCode = ARMCC::LT; break;
1253 case ISD::SETULE: CondCode = ARMCC::LE; break;
1255 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259 //===----------------------------------------------------------------------===//
1260 // Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1263 #include "ARMGenCallingConv.inc"
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270 bool isVarArg) const {
1273 llvm_unreachable("Unsupported calling convention");
1274 case CallingConv::ARM_AAPCS:
1275 case CallingConv::ARM_APCS:
1276 case CallingConv::GHC:
1278 case CallingConv::ARM_AAPCS_VFP:
1279 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280 case CallingConv::C:
1281 if (!Subtarget->isAAPCS_ABI())
1282 return CallingConv::ARM_APCS;
1283 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286 return CallingConv::ARM_AAPCS_VFP;
1288 return CallingConv::ARM_AAPCS;
1289 case CallingConv::Fast:
1290 if (!Subtarget->isAAPCS_ABI()) {
1291 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292 return CallingConv::Fast;
1293 return CallingConv::ARM_APCS;
1294 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295 return CallingConv::ARM_AAPCS_VFP;
1297 return CallingConv::ARM_AAPCS;
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1305 bool isVarArg) const {
1306 switch (getEffectiveCallingConv(CC, isVarArg)) {
1308 llvm_unreachable("Unsupported calling convention");
1309 case CallingConv::ARM_APCS:
1310 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311 case CallingConv::ARM_AAPCS:
1312 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313 case CallingConv::ARM_AAPCS_VFP:
1314 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315 case CallingConv::Fast:
1316 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317 case CallingConv::GHC:
1318 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326 CallingConv::ID CallConv, bool isVarArg,
1327 const SmallVectorImpl<ISD::InputArg> &Ins,
1328 SDLoc dl, SelectionDAG &DAG,
1329 SmallVectorImpl<SDValue> &InVals,
1330 bool isThisReturn, SDValue ThisVal) const {
1332 // Assign locations to each value returned by this call.
1333 SmallVector<CCValAssign, 16> RVLocs;
1334 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335 *DAG.getContext(), Call);
1336 CCInfo.AnalyzeCallResult(Ins,
1337 CCAssignFnForNode(CallConv, /* Return*/ true,
1340 // Copy all of the result registers out of their specified physreg.
1341 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342 CCValAssign VA = RVLocs[i];
1344 // Pass 'this' value directly from the argument to return value, to avoid
1345 // reg unit interference
1346 if (i == 0 && isThisReturn) {
1347 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348 "unexpected return calling convention register assignment");
1349 InVals.push_back(ThisVal);
1354 if (VA.needsCustom()) {
1355 // Handle f64 or half of a v2f64.
1356 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1358 Chain = Lo.getValue(1);
1359 InFlag = Lo.getValue(2);
1360 VA = RVLocs[++i]; // skip ahead to next loc
1361 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1363 Chain = Hi.getValue(1);
1364 InFlag = Hi.getValue(2);
1365 if (!Subtarget->isLittle())
1367 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1369 if (VA.getLocVT() == MVT::v2f64) {
1370 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372 DAG.getConstant(0, MVT::i32));
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376 Chain = Lo.getValue(1);
1377 InFlag = Lo.getValue(2);
1378 VA = RVLocs[++i]; // skip ahead to next loc
1379 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380 Chain = Hi.getValue(1);
1381 InFlag = Hi.getValue(2);
1382 if (!Subtarget->isLittle())
1384 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(1, MVT::i32));
1389 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1391 Chain = Val.getValue(1);
1392 InFlag = Val.getValue(2);
1395 switch (VA.getLocInfo()) {
1396 default: llvm_unreachable("Unknown loc info!");
1397 case CCValAssign::Full: break;
1398 case CCValAssign::BCvt:
1399 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403 InVals.push_back(Val);
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412 SDValue StackPtr, SDValue Arg,
1413 SDLoc dl, SelectionDAG &DAG,
1414 const CCValAssign &VA,
1415 ISD::ArgFlagsTy Flags) const {
1416 unsigned LocMemOffset = VA.getLocMemOffset();
1417 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419 return DAG.getStore(Chain, dl, Arg, PtrOff,
1420 MachinePointerInfo::getStack(LocMemOffset),
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425 SDValue Chain, SDValue &Arg,
1426 RegsToPassVector &RegsToPass,
1427 CCValAssign &VA, CCValAssign &NextVA,
1429 SmallVectorImpl<SDValue> &MemOpChains,
1430 ISD::ArgFlagsTy Flags) const {
1432 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434 unsigned id = Subtarget->isLittle() ? 0 : 1;
1435 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1437 if (NextVA.isRegLoc())
1438 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1440 assert(NextVA.isMemLoc());
1441 if (!StackPtr.getNode())
1442 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455 SmallVectorImpl<SDValue> &InVals) const {
1456 SelectionDAG &DAG = CLI.DAG;
1458 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1460 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1461 SDValue Chain = CLI.Chain;
1462 SDValue Callee = CLI.Callee;
1463 bool &isTailCall = CLI.IsTailCall;
1464 CallingConv::ID CallConv = CLI.CallConv;
1465 bool doesNotRet = CLI.DoesNotReturn;
1466 bool isVarArg = CLI.IsVarArg;
1468 MachineFunction &MF = DAG.getMachineFunction();
1469 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470 bool isThisReturn = false;
1471 bool isSibCall = false;
1473 // Disable tail calls if they're not supported.
1474 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478 // Check if it's really possible to do a tail call.
1479 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481 Outs, OutVals, Ins, DAG);
1482 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483 report_fatal_error("failed to perform tail call elimination on a call "
1484 "site marked musttail");
1485 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486 // detected sibcalls.
1493 // Analyze operands of the call, assigning locations to each operand.
1494 SmallVector<CCValAssign, 16> ArgLocs;
1495 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496 *DAG.getContext(), Call);
1497 CCInfo.AnalyzeCallOperands(Outs,
1498 CCAssignFnForNode(CallConv, /* Return*/ false,
1501 // Get a count of how many bytes are to be pushed on the stack.
1502 unsigned NumBytes = CCInfo.getNextStackOffset();
1504 // For tail calls, memory operands are available in our caller's stack.
1508 // Adjust the stack pointer for the new arguments...
1509 // These operations are automatically eliminated by the prolog/epilog pass
1511 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1514 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1516 RegsToPassVector RegsToPass;
1517 SmallVector<SDValue, 8> MemOpChains;
1519 // Walk the register/memloc assignments, inserting copies/loads. In the case
1520 // of tail call optimization, arguments are handled later.
1521 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1523 ++i, ++realArgIdx) {
1524 CCValAssign &VA = ArgLocs[i];
1525 SDValue Arg = OutVals[realArgIdx];
1526 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527 bool isByVal = Flags.isByVal();
1529 // Promote the value if needed.
1530 switch (VA.getLocInfo()) {
1531 default: llvm_unreachable("Unknown loc info!");
1532 case CCValAssign::Full: break;
1533 case CCValAssign::SExt:
1534 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1536 case CCValAssign::ZExt:
1537 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1539 case CCValAssign::AExt:
1540 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1542 case CCValAssign::BCvt:
1543 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548 if (VA.needsCustom()) {
1549 if (VA.getLocVT() == MVT::v2f64) {
1550 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551 DAG.getConstant(0, MVT::i32));
1552 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553 DAG.getConstant(1, MVT::i32));
1555 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1558 VA = ArgLocs[++i]; // skip ahead to next loc
1559 if (VA.isRegLoc()) {
1560 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1563 assert(VA.isMemLoc());
1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566 dl, DAG, VA, Flags));
1569 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570 StackPtr, MemOpChains, Flags);
1572 } else if (VA.isRegLoc()) {
1573 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574 assert(VA.getLocVT() == MVT::i32 &&
1575 "unexpected calling convention register assignment");
1576 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577 "unexpected use of 'returned'");
1578 isThisReturn = true;
1580 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581 } else if (isByVal) {
1582 assert(VA.isMemLoc());
1583 unsigned offset = 0;
1585 // True if this byval aggregate will be split between registers
1587 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1590 if (CurByValIdx < ByValArgsCount) {
1592 unsigned RegBegin, RegEnd;
1593 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1595 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1597 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601 MachinePointerInfo(),
1602 false, false, false,
1603 DAG.InferPtrAlignment(AddArg));
1604 MemOpChains.push_back(Load.getValue(1));
1605 RegsToPass.push_back(std::make_pair(j, Load));
1608 // If parameter size outsides register area, "offset" value
1609 // helps us to calculate stack slot for remained part properly.
1610 offset = RegEnd - RegBegin;
1612 CCInfo.nextInRegsParam();
1615 if (Flags.getByValSize() > 4*offset) {
1616 unsigned LocMemOffset = VA.getLocMemOffset();
1617 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1620 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1624 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1626 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1631 } else if (!isSibCall) {
1632 assert(VA.isMemLoc());
1634 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635 dl, DAG, VA, Flags));
1639 if (!MemOpChains.empty())
1640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1642 // Build a sequence of copy-to-reg nodes chained together with token chain
1643 // and flag operands which copy the outgoing args into the appropriate regs.
1645 // Tail call byval lowering might overwrite argument registers so in case of
1646 // tail call optimization the copies to registers are lowered later.
1648 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650 RegsToPass[i].second, InFlag);
1651 InFlag = Chain.getValue(1);
1654 // For tail calls lower the arguments to the 'real' stack slot.
1656 // Force all the incoming stack arguments to be loaded from the stack
1657 // before any new outgoing arguments are stored to the stack, because the
1658 // outgoing stack slots may alias the incoming argument stack slots, and
1659 // the alias isn't otherwise explicit. This is slightly more conservative
1660 // than necessary, because it means that each store effectively depends
1661 // on every argument instead of just those arguments it would clobber.
1663 // Do not flag preceding copytoreg stuff together with the following stuff.
1665 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667 RegsToPass[i].second, InFlag);
1668 InFlag = Chain.getValue(1);
1673 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675 // node so that legalize doesn't hack it.
1676 bool isDirect = false;
1677 bool isARMFunc = false;
1678 bool isLocalARMFunc = false;
1679 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1681 if (EnableARMLongCalls) {
1682 assert((Subtarget->isTargetWindows() ||
1683 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684 "long-calls with non-static relocation model!");
1685 // Handle a global address or an external symbol. If it's not one of
1686 // those, the target's already in a register, so we don't need to do
1688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689 const GlobalValue *GV = G->getGlobal();
1690 // Create a constant pool entry for the callee address
1691 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692 ARMConstantPoolValue *CPV =
1693 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1695 // Get the address of the callee into a register
1696 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698 Callee = DAG.getLoad(getPointerTy(), dl,
1699 DAG.getEntryNode(), CPAddr,
1700 MachinePointerInfo::getConstantPool(),
1701 false, false, false, 0);
1702 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703 const char *Sym = S->getSymbol();
1705 // Create a constant pool entry for the callee address
1706 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707 ARMConstantPoolValue *CPV =
1708 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709 ARMPCLabelIndex, 0);
1710 // Get the address of the callee into a register
1711 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713 Callee = DAG.getLoad(getPointerTy(), dl,
1714 DAG.getEntryNode(), CPAddr,
1715 MachinePointerInfo::getConstantPool(),
1716 false, false, false, 0);
1718 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719 const GlobalValue *GV = G->getGlobal();
1721 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723 getTargetMachine().getRelocationModel() != Reloc::Static;
1724 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725 // ARM call to a local ARM function is predicable.
1726 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727 // tBX takes a register source operand.
1728 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732 0, ARMII::MO_NONLAZY));
1733 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734 MachinePointerInfo::getGOT(), false, false, true, 0);
1735 } else if (Subtarget->isTargetCOFF()) {
1736 assert(Subtarget->isTargetWindows() &&
1737 "Windows is the only supported COFF target");
1738 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739 ? ARMII::MO_DLLIMPORT
1740 : ARMII::MO_NO_FLAG;
1741 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1743 if (GV->hasDLLImportStorageClass())
1744 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746 Callee), MachinePointerInfo::getGOT(),
1747 false, false, false, 0);
1749 // On ELF targets for PIC code, direct calls should go through the PLT
1750 unsigned OpFlags = 0;
1751 if (Subtarget->isTargetELF() &&
1752 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753 OpFlags = ARMII::MO_PLT;
1754 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1756 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1758 bool isStub = Subtarget->isTargetMachO() &&
1759 getTargetMachine().getRelocationModel() != Reloc::Static;
1760 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761 // tBX takes a register source operand.
1762 const char *Sym = S->getSymbol();
1763 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765 ARMConstantPoolValue *CPV =
1766 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767 ARMPCLabelIndex, 4);
1768 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770 Callee = DAG.getLoad(getPointerTy(), dl,
1771 DAG.getEntryNode(), CPAddr,
1772 MachinePointerInfo::getConstantPool(),
1773 false, false, false, 0);
1774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776 getPointerTy(), Callee, PICLabel);
1778 unsigned OpFlags = 0;
1779 // On ELF targets for PIC code, direct calls should go through the PLT
1780 if (Subtarget->isTargetELF() &&
1781 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782 OpFlags = ARMII::MO_PLT;
1783 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1787 // FIXME: handle tail calls differently.
1789 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1790 if (Subtarget->isThumb()) {
1791 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1792 CallOpc = ARMISD::CALL_NOLINK;
1794 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1796 if (!isDirect && !Subtarget->hasV5TOps())
1797 CallOpc = ARMISD::CALL_NOLINK;
1798 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1799 // Emit regular call when code size is the priority
1801 // "mov lr, pc; b _foo" to avoid confusing the RSP
1802 CallOpc = ARMISD::CALL_NOLINK;
1804 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1807 std::vector<SDValue> Ops;
1808 Ops.push_back(Chain);
1809 Ops.push_back(Callee);
1811 // Add argument registers to the end of the list so that they are known live
1813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815 RegsToPass[i].second.getValueType()));
1817 // Add a register mask operand representing the call-preserved registers.
1819 const uint32_t *Mask;
1820 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1822 // For 'this' returns, use the R0-preserving mask if applicable
1823 Mask = ARI->getThisReturnPreservedMask(CallConv);
1825 // Set isThisReturn to false if the calling convention is not one that
1826 // allows 'returned' to be modeled in this way, so LowerCallResult does
1827 // not try to pass 'this' straight through
1828 isThisReturn = false;
1829 Mask = ARI->getCallPreservedMask(CallConv);
1832 Mask = ARI->getCallPreservedMask(CallConv);
1834 assert(Mask && "Missing call preserved mask for calling convention");
1835 Ops.push_back(DAG.getRegisterMask(Mask));
1838 if (InFlag.getNode())
1839 Ops.push_back(InFlag);
1841 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1843 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1845 // Returns a chain and a flag for retval copy to use.
1846 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1847 InFlag = Chain.getValue(1);
1849 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1850 DAG.getIntPtrConstant(0, true), InFlag, dl);
1852 InFlag = Chain.getValue(1);
1854 // Handle result values, copying them out of physregs into vregs that we
1856 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1857 InVals, isThisReturn,
1858 isThisReturn ? OutVals[0] : SDValue());
1861 /// HandleByVal - Every parameter *after* a byval parameter is passed
1862 /// on the stack. Remember the next parameter register to allocate,
1863 /// and then confiscate the rest of the parameter registers to insure
1866 ARMTargetLowering::HandleByVal(
1867 CCState *State, unsigned &size, unsigned Align) const {
1868 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1869 assert((State->getCallOrPrologue() == Prologue ||
1870 State->getCallOrPrologue() == Call) &&
1871 "unhandled ParmContext");
1873 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1874 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1875 unsigned AlignInRegs = Align / 4;
1876 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1877 for (unsigned i = 0; i < Waste; ++i)
1878 reg = State->AllocateReg(GPRArgRegs, 4);
1881 unsigned excess = 4 * (ARM::R4 - reg);
1883 // Special case when NSAA != SP and parameter size greater than size of
1884 // all remained GPR regs. In that case we can't split parameter, we must
1885 // send it to stack. We also must set NCRN to R4, so waste all
1886 // remained registers.
1887 const unsigned NSAAOffset = State->getNextStackOffset();
1888 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1889 while (State->AllocateReg(GPRArgRegs, 4))
1894 // First register for byval parameter is the first register that wasn't
1895 // allocated before this method call, so it would be "reg".
1896 // If parameter is small enough to be saved in range [reg, r4), then
1897 // the end (first after last) register would be reg + param-size-in-regs,
1898 // else parameter would be splitted between registers and stack,
1899 // end register would be r4 in this case.
1900 unsigned ByValRegBegin = reg;
1901 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1902 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1903 // Note, first register is allocated in the beginning of function already,
1904 // allocate remained amount of registers we need.
1905 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1906 State->AllocateReg(GPRArgRegs, 4);
1907 // A byval parameter that is split between registers and memory needs its
1908 // size truncated here.
1909 // In the case where the entire structure fits in registers, we set the
1910 // size in memory to zero.
1919 /// MatchingStackOffset - Return true if the given stack call argument is
1920 /// already available in the same position (relatively) of the caller's
1921 /// incoming argument stack.
1923 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1924 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1925 const TargetInstrInfo *TII) {
1926 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1928 if (Arg.getOpcode() == ISD::CopyFromReg) {
1929 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1930 if (!TargetRegisterInfo::isVirtualRegister(VR))
1932 MachineInstr *Def = MRI->getVRegDef(VR);
1935 if (!Flags.isByVal()) {
1936 if (!TII->isLoadFromStackSlot(Def, FI))
1941 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1942 if (Flags.isByVal())
1943 // ByVal argument is passed in as a pointer but it's now being
1944 // dereferenced. e.g.
1945 // define @foo(%struct.X* %A) {
1946 // tail call @bar(%struct.X* byval %A)
1949 SDValue Ptr = Ld->getBasePtr();
1950 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1953 FI = FINode->getIndex();
1957 assert(FI != INT_MAX);
1958 if (!MFI->isFixedObjectIndex(FI))
1960 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1963 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1964 /// for tail call optimization. Targets which want to do tail call
1965 /// optimization should implement this function.
1967 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1968 CallingConv::ID CalleeCC,
1970 bool isCalleeStructRet,
1971 bool isCallerStructRet,
1972 const SmallVectorImpl<ISD::OutputArg> &Outs,
1973 const SmallVectorImpl<SDValue> &OutVals,
1974 const SmallVectorImpl<ISD::InputArg> &Ins,
1975 SelectionDAG& DAG) const {
1976 const Function *CallerF = DAG.getMachineFunction().getFunction();
1977 CallingConv::ID CallerCC = CallerF->getCallingConv();
1978 bool CCMatch = CallerCC == CalleeCC;
1980 // Look for obvious safe cases to perform tail call optimization that do not
1981 // require ABI changes. This is what gcc calls sibcall.
1983 // Do not sibcall optimize vararg calls unless the call site is not passing
1985 if (isVarArg && !Outs.empty())
1988 // Exception-handling functions need a special set of instructions to indicate
1989 // a return to the hardware. Tail-calling another function would probably
1991 if (CallerF->hasFnAttribute("interrupt"))
1994 // Also avoid sibcall optimization if either caller or callee uses struct
1995 // return semantics.
1996 if (isCalleeStructRet || isCallerStructRet)
1999 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2000 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2001 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2002 // support in the assembler and linker to be used. This would need to be
2003 // fixed to fully support tail calls in Thumb1.
2005 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2006 // LR. This means if we need to reload LR, it takes an extra instructions,
2007 // which outweighs the value of the tail call; but here we don't know yet
2008 // whether LR is going to be used. Probably the right approach is to
2009 // generate the tail call here and turn it back into CALL/RET in
2010 // emitEpilogue if LR is used.
2012 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2013 // but we need to make sure there are enough registers; the only valid
2014 // registers are the 4 used for parameters. We don't currently do this
2016 if (Subtarget->isThumb1Only())
2019 // Externally-defined functions with weak linkage should not be
2020 // tail-called on ARM when the OS does not support dynamic
2021 // pre-emption of symbols, as the AAELF spec requires normal calls
2022 // to undefined weak functions to be replaced with a NOP or jump to the
2023 // next instruction. The behaviour of branch instructions in this
2024 // situation (as used for tail calls) is implementation-defined, so we
2025 // cannot rely on the linker replacing the tail call with a return.
2026 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2027 const GlobalValue *GV = G->getGlobal();
2028 const Triple TT(getTargetMachine().getTargetTriple());
2029 if (GV->hasExternalWeakLinkage() &&
2030 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2034 // If the calling conventions do not match, then we'd better make sure the
2035 // results are returned in the same way as what the caller expects.
2037 SmallVector<CCValAssign, 16> RVLocs1;
2038 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2039 *DAG.getContext(), Call);
2040 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2042 SmallVector<CCValAssign, 16> RVLocs2;
2043 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2044 *DAG.getContext(), Call);
2045 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2047 if (RVLocs1.size() != RVLocs2.size())
2049 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2050 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2052 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2054 if (RVLocs1[i].isRegLoc()) {
2055 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2058 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2064 // If Caller's vararg or byval argument has been split between registers and
2065 // stack, do not perform tail call, since part of the argument is in caller's
2067 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2068 getInfo<ARMFunctionInfo>();
2069 if (AFI_Caller->getArgRegsSaveSize())
2072 // If the callee takes no arguments then go on to check the results of the
2074 if (!Outs.empty()) {
2075 // Check if stack adjustment is needed. For now, do not do this if any
2076 // argument is passed on the stack.
2077 SmallVector<CCValAssign, 16> ArgLocs;
2078 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2079 *DAG.getContext(), Call);
2080 CCInfo.AnalyzeCallOperands(Outs,
2081 CCAssignFnForNode(CalleeCC, false, isVarArg));
2082 if (CCInfo.getNextStackOffset()) {
2083 MachineFunction &MF = DAG.getMachineFunction();
2085 // Check if the arguments are already laid out in the right way as
2086 // the caller's fixed stack objects.
2087 MachineFrameInfo *MFI = MF.getFrameInfo();
2088 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2089 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2090 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2092 ++i, ++realArgIdx) {
2093 CCValAssign &VA = ArgLocs[i];
2094 EVT RegVT = VA.getLocVT();
2095 SDValue Arg = OutVals[realArgIdx];
2096 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2097 if (VA.getLocInfo() == CCValAssign::Indirect)
2099 if (VA.needsCustom()) {
2100 // f64 and vector types are split into multiple registers or
2101 // register/stack-slot combinations. The types will not match
2102 // the registers; give up on memory f64 refs until we figure
2103 // out what to do about this.
2106 if (!ArgLocs[++i].isRegLoc())
2108 if (RegVT == MVT::v2f64) {
2109 if (!ArgLocs[++i].isRegLoc())
2111 if (!ArgLocs[++i].isRegLoc())
2114 } else if (!VA.isRegLoc()) {
2115 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2127 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2128 MachineFunction &MF, bool isVarArg,
2129 const SmallVectorImpl<ISD::OutputArg> &Outs,
2130 LLVMContext &Context) const {
2131 SmallVector<CCValAssign, 16> RVLocs;
2132 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2133 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2137 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2138 SDLoc DL, SelectionDAG &DAG) {
2139 const MachineFunction &MF = DAG.getMachineFunction();
2140 const Function *F = MF.getFunction();
2142 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2144 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2145 // version of the "preferred return address". These offsets affect the return
2146 // instruction if this is a return from PL1 without hypervisor extensions.
2147 // IRQ/FIQ: +4 "subs pc, lr, #4"
2148 // SWI: 0 "subs pc, lr, #0"
2149 // ABORT: +4 "subs pc, lr, #4"
2150 // UNDEF: +4/+2 "subs pc, lr, #0"
2151 // UNDEF varies depending on where the exception came from ARM or Thumb
2152 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2155 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2158 else if (IntKind == "SWI" || IntKind == "UNDEF")
2161 report_fatal_error("Unsupported interrupt attribute. If present, value "
2162 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2164 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2166 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2170 ARMTargetLowering::LowerReturn(SDValue Chain,
2171 CallingConv::ID CallConv, bool isVarArg,
2172 const SmallVectorImpl<ISD::OutputArg> &Outs,
2173 const SmallVectorImpl<SDValue> &OutVals,
2174 SDLoc dl, SelectionDAG &DAG) const {
2176 // CCValAssign - represent the assignment of the return value to a location.
2177 SmallVector<CCValAssign, 16> RVLocs;
2179 // CCState - Info about the registers and stack slots.
2180 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2181 *DAG.getContext(), Call);
2183 // Analyze outgoing return values.
2184 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2188 SmallVector<SDValue, 4> RetOps;
2189 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2190 bool isLittleEndian = Subtarget->isLittle();
2192 MachineFunction &MF = DAG.getMachineFunction();
2193 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2194 AFI->setReturnRegsCount(RVLocs.size());
2196 // Copy the result values into the output registers.
2197 for (unsigned i = 0, realRVLocIdx = 0;
2199 ++i, ++realRVLocIdx) {
2200 CCValAssign &VA = RVLocs[i];
2201 assert(VA.isRegLoc() && "Can only return in registers!");
2203 SDValue Arg = OutVals[realRVLocIdx];
2205 switch (VA.getLocInfo()) {
2206 default: llvm_unreachable("Unknown loc info!");
2207 case CCValAssign::Full: break;
2208 case CCValAssign::BCvt:
2209 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2213 if (VA.needsCustom()) {
2214 if (VA.getLocVT() == MVT::v2f64) {
2215 // Extract the first half and return it in two registers.
2216 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2217 DAG.getConstant(0, MVT::i32));
2218 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2219 DAG.getVTList(MVT::i32, MVT::i32), Half);
2221 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2222 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2224 Flag = Chain.getValue(1);
2225 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2226 VA = RVLocs[++i]; // skip ahead to next loc
2227 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2228 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2230 Flag = Chain.getValue(1);
2231 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2232 VA = RVLocs[++i]; // skip ahead to next loc
2234 // Extract the 2nd half and fall through to handle it as an f64 value.
2235 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236 DAG.getConstant(1, MVT::i32));
2238 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2240 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2241 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2242 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2243 fmrrd.getValue(isLittleEndian ? 0 : 1),
2245 Flag = Chain.getValue(1);
2246 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2247 VA = RVLocs[++i]; // skip ahead to next loc
2248 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2249 fmrrd.getValue(isLittleEndian ? 1 : 0),
2252 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2254 // Guarantee that all emitted copies are
2255 // stuck together, avoiding something bad.
2256 Flag = Chain.getValue(1);
2257 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2260 // Update chain and glue.
2263 RetOps.push_back(Flag);
2265 // CPUs which aren't M-class use a special sequence to return from
2266 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2267 // though we use "subs pc, lr, #N").
2269 // M-class CPUs actually use a normal return sequence with a special
2270 // (hardware-provided) value in LR, so the normal code path works.
2271 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2272 !Subtarget->isMClass()) {
2273 if (Subtarget->isThumb1Only())
2274 report_fatal_error("interrupt attribute is not supported in Thumb1");
2275 return LowerInterruptReturn(RetOps, dl, DAG);
2278 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2281 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2282 if (N->getNumValues() != 1)
2284 if (!N->hasNUsesOfValue(1, 0))
2287 SDValue TCChain = Chain;
2288 SDNode *Copy = *N->use_begin();
2289 if (Copy->getOpcode() == ISD::CopyToReg) {
2290 // If the copy has a glue operand, we conservatively assume it isn't safe to
2291 // perform a tail call.
2292 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2294 TCChain = Copy->getOperand(0);
2295 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2296 SDNode *VMov = Copy;
2297 // f64 returned in a pair of GPRs.
2298 SmallPtrSet<SDNode*, 2> Copies;
2299 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2301 if (UI->getOpcode() != ISD::CopyToReg)
2305 if (Copies.size() > 2)
2308 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2310 SDValue UseChain = UI->getOperand(0);
2311 if (Copies.count(UseChain.getNode()))
2315 // We are at the top of this chain.
2316 // If the copy has a glue operand, we conservatively assume it
2317 // isn't safe to perform a tail call.
2318 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2324 } else if (Copy->getOpcode() == ISD::BITCAST) {
2325 // f32 returned in a single GPR.
2326 if (!Copy->hasOneUse())
2328 Copy = *Copy->use_begin();
2329 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2331 // If the copy has a glue operand, we conservatively assume it isn't safe to
2332 // perform a tail call.
2333 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2335 TCChain = Copy->getOperand(0);
2340 bool HasRet = false;
2341 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2343 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2344 UI->getOpcode() != ARMISD::INTRET_FLAG)
2356 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2357 if (!Subtarget->supportsTailCall())
2360 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2363 return !Subtarget->isThumb1Only();
2366 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2367 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2368 // one of the above mentioned nodes. It has to be wrapped because otherwise
2369 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2370 // be used to form addressing mode. These wrapped nodes will be selected
2372 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2373 EVT PtrVT = Op.getValueType();
2374 // FIXME there is no actual debug info here
2376 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2378 if (CP->isMachineConstantPoolEntry())
2379 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2380 CP->getAlignment());
2382 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2383 CP->getAlignment());
2384 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2387 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2388 return MachineJumpTableInfo::EK_Inline;
2391 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2392 SelectionDAG &DAG) const {
2393 MachineFunction &MF = DAG.getMachineFunction();
2394 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2395 unsigned ARMPCLabelIndex = 0;
2397 EVT PtrVT = getPointerTy();
2398 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2399 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2401 if (RelocM == Reloc::Static) {
2402 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2404 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2405 ARMPCLabelIndex = AFI->createPICLabelUId();
2406 ARMConstantPoolValue *CPV =
2407 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2408 ARMCP::CPBlockAddress, PCAdj);
2409 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2411 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2412 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2413 MachinePointerInfo::getConstantPool(),
2414 false, false, false, 0);
2415 if (RelocM == Reloc::Static)
2417 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2418 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2421 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2423 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2424 SelectionDAG &DAG) const {
2426 EVT PtrVT = getPointerTy();
2427 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2428 MachineFunction &MF = DAG.getMachineFunction();
2429 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2430 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2431 ARMConstantPoolValue *CPV =
2432 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2433 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2434 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2435 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2436 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2437 MachinePointerInfo::getConstantPool(),
2438 false, false, false, 0);
2439 SDValue Chain = Argument.getValue(1);
2441 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2442 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2444 // call __tls_get_addr.
2447 Entry.Node = Argument;
2448 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2449 Args.push_back(Entry);
2451 // FIXME: is there useful debug info available here?
2452 TargetLowering::CallLoweringInfo CLI(DAG);
2453 CLI.setDebugLoc(dl).setChain(Chain)
2454 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2455 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2458 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2459 return CallResult.first;
2462 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2463 // "local exec" model.
2465 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2467 TLSModel::Model model) const {
2468 const GlobalValue *GV = GA->getGlobal();
2471 SDValue Chain = DAG.getEntryNode();
2472 EVT PtrVT = getPointerTy();
2473 // Get the Thread Pointer
2474 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2476 if (model == TLSModel::InitialExec) {
2477 MachineFunction &MF = DAG.getMachineFunction();
2478 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2479 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2480 // Initial exec model.
2481 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2482 ARMConstantPoolValue *CPV =
2483 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2484 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2486 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2487 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2488 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2489 MachinePointerInfo::getConstantPool(),
2490 false, false, false, 0);
2491 Chain = Offset.getValue(1);
2493 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2494 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2496 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2497 MachinePointerInfo::getConstantPool(),
2498 false, false, false, 0);
2501 assert(model == TLSModel::LocalExec);
2502 ARMConstantPoolValue *CPV =
2503 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2504 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2505 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2506 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2507 MachinePointerInfo::getConstantPool(),
2508 false, false, false, 0);
2511 // The address of the thread local variable is the add of the thread
2512 // pointer with the offset of the variable.
2513 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2517 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2518 // TODO: implement the "local dynamic" model
2519 assert(Subtarget->isTargetELF() &&
2520 "TLS not implemented for non-ELF targets");
2521 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2523 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2526 case TLSModel::GeneralDynamic:
2527 case TLSModel::LocalDynamic:
2528 return LowerToTLSGeneralDynamicModel(GA, DAG);
2529 case TLSModel::InitialExec:
2530 case TLSModel::LocalExec:
2531 return LowerToTLSExecModels(GA, DAG, model);
2533 llvm_unreachable("bogus TLS model");
2536 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2537 SelectionDAG &DAG) const {
2538 EVT PtrVT = getPointerTy();
2540 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2542 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2543 ARMConstantPoolValue *CPV =
2544 ARMConstantPoolConstant::Create(GV,
2545 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2546 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2547 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2548 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2550 MachinePointerInfo::getConstantPool(),
2551 false, false, false, 0);
2552 SDValue Chain = Result.getValue(1);
2553 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2554 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2556 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2557 MachinePointerInfo::getGOT(),
2558 false, false, false, 0);
2562 // If we have T2 ops, we can materialize the address directly via movt/movw
2563 // pair. This is always cheaper.
2564 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2566 // FIXME: Once remat is capable of dealing with instructions with register
2567 // operands, expand this into two nodes.
2568 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2569 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2571 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2572 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2573 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2574 MachinePointerInfo::getConstantPool(),
2575 false, false, false, 0);
2579 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2580 SelectionDAG &DAG) const {
2581 EVT PtrVT = getPointerTy();
2583 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2584 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2586 if (Subtarget->useMovt(DAG.getMachineFunction()))
2589 // FIXME: Once remat is capable of dealing with instructions with register
2590 // operands, expand this into multiple nodes
2592 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2594 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2595 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2597 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2598 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2599 MachinePointerInfo::getGOT(), false, false, false, 0);
2603 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2604 SelectionDAG &DAG) const {
2605 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2606 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2607 "Windows on ARM expects to use movw/movt");
2609 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2610 const ARMII::TOF TargetFlags =
2611 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2612 EVT PtrVT = getPointerTy();
2618 // FIXME: Once remat is capable of dealing with instructions with register
2619 // operands, expand this into two nodes.
2620 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2621 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2623 if (GV->hasDLLImportStorageClass())
2624 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2625 MachinePointerInfo::getGOT(), false, false, false, 0);
2629 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2630 SelectionDAG &DAG) const {
2631 assert(Subtarget->isTargetELF() &&
2632 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2633 MachineFunction &MF = DAG.getMachineFunction();
2634 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2635 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2636 EVT PtrVT = getPointerTy();
2638 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2639 ARMConstantPoolValue *CPV =
2640 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2641 ARMPCLabelIndex, PCAdj);
2642 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2643 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2644 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2645 MachinePointerInfo::getConstantPool(),
2646 false, false, false, 0);
2647 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2648 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2652 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2654 SDValue Val = DAG.getConstant(0, MVT::i32);
2655 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2656 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2657 Op.getOperand(1), Val);
2661 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2663 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2664 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2668 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2669 const ARMSubtarget *Subtarget) const {
2670 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2673 default: return SDValue(); // Don't custom lower most intrinsics.
2674 case Intrinsic::arm_rbit: {
2675 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2676 "RBIT intrinsic must have i32 type!");
2677 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2679 case Intrinsic::arm_thread_pointer: {
2680 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2681 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2683 case Intrinsic::eh_sjlj_lsda: {
2684 MachineFunction &MF = DAG.getMachineFunction();
2685 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2686 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2687 EVT PtrVT = getPointerTy();
2688 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2690 unsigned PCAdj = (RelocM != Reloc::PIC_)
2691 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2692 ARMConstantPoolValue *CPV =
2693 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2694 ARMCP::CPLSDA, PCAdj);
2695 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2696 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2698 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2699 MachinePointerInfo::getConstantPool(),
2700 false, false, false, 0);
2702 if (RelocM == Reloc::PIC_) {
2703 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2704 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2708 case Intrinsic::arm_neon_vmulls:
2709 case Intrinsic::arm_neon_vmullu: {
2710 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2711 ? ARMISD::VMULLs : ARMISD::VMULLu;
2712 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2713 Op.getOperand(1), Op.getOperand(2));
2718 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2719 const ARMSubtarget *Subtarget) {
2720 // FIXME: handle "fence singlethread" more efficiently.
2722 if (!Subtarget->hasDataBarrier()) {
2723 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2724 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2726 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2727 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2728 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2729 DAG.getConstant(0, MVT::i32));
2732 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2733 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2734 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2735 if (Subtarget->isMClass()) {
2736 // Only a full system barrier exists in the M-class architectures.
2737 Domain = ARM_MB::SY;
2738 } else if (Subtarget->isSwift() && Ord == Release) {
2739 // Swift happens to implement ISHST barriers in a way that's compatible with
2740 // Release semantics but weaker than ISH so we'd be fools not to use
2741 // it. Beware: other processors probably don't!
2742 Domain = ARM_MB::ISHST;
2745 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2746 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2747 DAG.getConstant(Domain, MVT::i32));
2750 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2751 const ARMSubtarget *Subtarget) {
2752 // ARM pre v5TE and Thumb1 does not have preload instructions.
2753 if (!(Subtarget->isThumb2() ||
2754 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2755 // Just preserve the chain.
2756 return Op.getOperand(0);
2759 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2761 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2762 // ARMv7 with MP extension has PLDW.
2763 return Op.getOperand(0);
2765 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2766 if (Subtarget->isThumb()) {
2768 isRead = ~isRead & 1;
2769 isData = ~isData & 1;
2772 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2773 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2774 DAG.getConstant(isData, MVT::i32));
2777 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2778 MachineFunction &MF = DAG.getMachineFunction();
2779 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2781 // vastart just stores the address of the VarArgsFrameIndex slot into the
2782 // memory location argument.
2784 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2785 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2786 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2787 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2788 MachinePointerInfo(SV), false, false, 0);
2792 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2793 SDValue &Root, SelectionDAG &DAG,
2795 MachineFunction &MF = DAG.getMachineFunction();
2796 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2798 const TargetRegisterClass *RC;
2799 if (AFI->isThumb1OnlyFunction())
2800 RC = &ARM::tGPRRegClass;
2802 RC = &ARM::GPRRegClass;
2804 // Transform the arguments stored in physical registers into virtual ones.
2805 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2806 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2809 if (NextVA.isMemLoc()) {
2810 MachineFrameInfo *MFI = MF.getFrameInfo();
2811 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2813 // Create load node to retrieve arguments from the stack.
2814 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2815 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2816 MachinePointerInfo::getFixedStack(FI),
2817 false, false, false, 0);
2819 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2820 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2822 if (!Subtarget->isLittle())
2823 std::swap (ArgValue, ArgValue2);
2824 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2828 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2829 unsigned InRegsParamRecordIdx,
2831 unsigned &ArgRegsSize,
2832 unsigned &ArgRegsSaveSize)
2835 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2836 unsigned RBegin, REnd;
2837 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2838 NumGPRs = REnd - RBegin;
2840 unsigned int firstUnalloced;
2841 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2842 sizeof(GPRArgRegs) /
2843 sizeof(GPRArgRegs[0]));
2844 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2847 unsigned Align = Subtarget->getFrameLowering()->getStackAlignment();
2848 ArgRegsSize = NumGPRs * 4;
2850 // If parameter is split between stack and GPRs...
2851 if (NumGPRs && Align > 4 &&
2852 (ArgRegsSize < ArgSize ||
2853 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2854 // Add padding for part of param recovered from GPRs. For example,
2855 // if Align == 8, its last byte must be at address K*8 - 1.
2856 // We need to do it, since remained (stack) part of parameter has
2857 // stack alignment, and we need to "attach" "GPRs head" without gaps
2860 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2861 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2863 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2865 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2866 ArgRegsSaveSize = ArgRegsSize + Padding;
2868 // We don't need to extend regs save size for byval parameters if they
2869 // are passed via GPRs only.
2870 ArgRegsSaveSize = ArgRegsSize;
2873 // The remaining GPRs hold either the beginning of variable-argument
2874 // data, or the beginning of an aggregate passed by value (usually
2875 // byval). Either way, we allocate stack slots adjacent to the data
2876 // provided by our caller, and store the unallocated registers there.
2877 // If this is a variadic function, the va_list pointer will begin with
2878 // these values; otherwise, this reassembles a (byval) structure that
2879 // was split between registers and memory.
2880 // Return: The frame index registers were stored into.
2882 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2883 SDLoc dl, SDValue &Chain,
2884 const Value *OrigArg,
2885 unsigned InRegsParamRecordIdx,
2886 unsigned OffsetFromOrigArg,
2890 unsigned ByValStoreOffset,
2891 unsigned TotalArgRegsSaveSize) const {
2893 // Currently, two use-cases possible:
2894 // Case #1. Non-var-args function, and we meet first byval parameter.
2895 // Setup first unallocated register as first byval register;
2896 // eat all remained registers
2897 // (these two actions are performed by HandleByVal method).
2898 // Then, here, we initialize stack frame with
2899 // "store-reg" instructions.
2900 // Case #2. Var-args function, that doesn't contain byval parameters.
2901 // The same: eat all remained unallocated registers,
2902 // initialize stack frame.
2904 MachineFunction &MF = DAG.getMachineFunction();
2905 MachineFrameInfo *MFI = MF.getFrameInfo();
2906 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2907 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2908 unsigned RBegin, REnd;
2909 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2910 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2911 firstRegToSaveIndex = RBegin - ARM::R0;
2912 lastRegToSaveIndex = REnd - ARM::R0;
2914 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2915 (GPRArgRegs, array_lengthof(GPRArgRegs));
2916 lastRegToSaveIndex = 4;
2919 unsigned ArgRegsSize, ArgRegsSaveSize;
2920 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2921 ArgRegsSize, ArgRegsSaveSize);
2923 // Store any by-val regs to their spots on the stack so that they may be
2924 // loaded by deferencing the result of formal parameter pointer or va_next.
2925 // Note: once stack area for byval/varargs registers
2926 // was initialized, it can't be initialized again.
2927 if (ArgRegsSaveSize) {
2928 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2931 assert(AFI->getStoredByValParamsPadding() == 0 &&
2932 "The only parameter may be padded.");
2933 AFI->setStoredByValParamsPadding(Padding);
2936 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2939 (int64_t)TotalArgRegsSaveSize,
2941 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2943 MFI->CreateFixedObject(Padding,
2944 ArgOffset + ByValStoreOffset -
2945 (int64_t)ArgRegsSaveSize,
2949 SmallVector<SDValue, 4> MemOps;
2950 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2951 ++firstRegToSaveIndex, ++i) {
2952 const TargetRegisterClass *RC;
2953 if (AFI->isThumb1OnlyFunction())
2954 RC = &ARM::tGPRRegClass;
2956 RC = &ARM::GPRRegClass;
2958 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2959 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2961 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2962 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2964 MemOps.push_back(Store);
2965 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2966 DAG.getConstant(4, getPointerTy()));
2969 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2971 if (!MemOps.empty())
2972 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2976 // We cannot allocate a zero-byte object for the first variadic argument,
2977 // so just make up a size.
2980 // This will point to the next argument passed via stack.
2981 return MFI->CreateFixedObject(
2982 ArgSize, ArgOffset, !ForceMutable);
2986 // Setup stack frame, the va_list pointer will start from.
2988 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2989 SDLoc dl, SDValue &Chain,
2991 unsigned TotalArgRegsSaveSize,
2992 bool ForceMutable) const {
2993 MachineFunction &MF = DAG.getMachineFunction();
2994 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2996 // Try to store any remaining integer argument regs
2997 // to their spots on the stack so that they may be loaded by deferencing
2998 // the result of va_next.
2999 // If there is no regs to be stored, just point address after last
3000 // argument passed via stack.
3002 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3003 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3004 0, TotalArgRegsSaveSize);
3006 AFI->setVarArgsFrameIndex(FrameIndex);
3010 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3011 CallingConv::ID CallConv, bool isVarArg,
3012 const SmallVectorImpl<ISD::InputArg>
3014 SDLoc dl, SelectionDAG &DAG,
3015 SmallVectorImpl<SDValue> &InVals)
3017 MachineFunction &MF = DAG.getMachineFunction();
3018 MachineFrameInfo *MFI = MF.getFrameInfo();
3020 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3022 // Assign locations to all of the incoming arguments.
3023 SmallVector<CCValAssign, 16> ArgLocs;
3024 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3025 *DAG.getContext(), Prologue);
3026 CCInfo.AnalyzeFormalArguments(Ins,
3027 CCAssignFnForNode(CallConv, /* Return*/ false,
3030 SmallVector<SDValue, 16> ArgValues;
3031 int lastInsIndex = -1;
3033 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3034 unsigned CurArgIdx = 0;
3036 // Initially ArgRegsSaveSize is zero.
3037 // Then we increase this value each time we meet byval parameter.
3038 // We also increase this value in case of varargs function.
3039 AFI->setArgRegsSaveSize(0);
3041 unsigned ByValStoreOffset = 0;
3042 unsigned TotalArgRegsSaveSize = 0;
3043 unsigned ArgRegsSaveSizeMaxAlign = 4;
3045 // Calculate the amount of stack space that we need to allocate to store
3046 // byval and variadic arguments that are passed in registers.
3047 // We need to know this before we allocate the first byval or variadic
3048 // argument, as they will be allocated a stack slot below the CFA (Canonical
3049 // Frame Address, the stack pointer at entry to the function).
3050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051 CCValAssign &VA = ArgLocs[i];
3052 if (VA.isMemLoc()) {
3053 int index = VA.getValNo();
3054 if (index != lastInsIndex) {
3055 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3056 if (Flags.isByVal()) {
3057 unsigned ExtraArgRegsSize;
3058 unsigned ExtraArgRegsSaveSize;
3059 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3060 Flags.getByValSize(),
3061 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3063 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3064 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3065 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3066 CCInfo.nextInRegsParam();
3068 lastInsIndex = index;
3072 CCInfo.rewindByValRegsInfo();
3074 if (isVarArg && MFI->hasVAStart()) {
3075 unsigned ExtraArgRegsSize;
3076 unsigned ExtraArgRegsSaveSize;
3077 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3078 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3079 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3081 // If the arg regs save area contains N-byte aligned values, the
3082 // bottom of it must be at least N-byte aligned.
3083 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3084 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3086 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3087 CCValAssign &VA = ArgLocs[i];
3088 if (Ins[VA.getValNo()].isOrigArg()) {
3089 std::advance(CurOrigArg,
3090 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3091 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3093 // Arguments stored in registers.
3094 if (VA.isRegLoc()) {
3095 EVT RegVT = VA.getLocVT();
3097 if (VA.needsCustom()) {
3098 // f64 and vector types are split up into multiple registers or
3099 // combinations of registers and stack slots.
3100 if (VA.getLocVT() == MVT::v2f64) {
3101 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3103 VA = ArgLocs[++i]; // skip ahead to next loc
3105 if (VA.isMemLoc()) {
3106 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3107 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3108 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3109 MachinePointerInfo::getFixedStack(FI),
3110 false, false, false, 0);
3112 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3115 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3116 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3117 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3118 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3119 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3121 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3124 const TargetRegisterClass *RC;
3126 if (RegVT == MVT::f32)
3127 RC = &ARM::SPRRegClass;
3128 else if (RegVT == MVT::f64)
3129 RC = &ARM::DPRRegClass;
3130 else if (RegVT == MVT::v2f64)
3131 RC = &ARM::QPRRegClass;
3132 else if (RegVT == MVT::i32)
3133 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3134 : &ARM::GPRRegClass;
3136 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3138 // Transform the arguments in physical registers into virtual ones.
3139 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3140 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3143 // If this is an 8 or 16-bit value, it is really passed promoted
3144 // to 32 bits. Insert an assert[sz]ext to capture this, then
3145 // truncate to the right size.
3146 switch (VA.getLocInfo()) {
3147 default: llvm_unreachable("Unknown loc info!");
3148 case CCValAssign::Full: break;
3149 case CCValAssign::BCvt:
3150 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3152 case CCValAssign::SExt:
3153 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3154 DAG.getValueType(VA.getValVT()));
3155 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3157 case CCValAssign::ZExt:
3158 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3159 DAG.getValueType(VA.getValVT()));
3160 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3164 InVals.push_back(ArgValue);
3166 } else { // VA.isRegLoc()
3169 assert(VA.isMemLoc());
3170 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3172 int index = VA.getValNo();
3174 // Some Ins[] entries become multiple ArgLoc[] entries.
3175 // Process them only once.
3176 if (index != lastInsIndex)
3178 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3179 // FIXME: For now, all byval parameter objects are marked mutable.
3180 // This can be changed with more analysis.
3181 // In case of tail call optimization mark all arguments mutable.
3182 // Since they could be overwritten by lowering of arguments in case of
3184 if (Flags.isByVal()) {
3185 assert(Ins[index].isOrigArg() &&
3186 "Byval arguments cannot be implicit");
3187 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3189 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3190 int FrameIndex = StoreByValRegs(
3191 CCInfo, DAG, dl, Chain, CurOrigArg,
3193 Ins[VA.getValNo()].PartOffset,
3194 VA.getLocMemOffset(),
3195 Flags.getByValSize(),
3196 true /*force mutable frames*/,
3198 TotalArgRegsSaveSize);
3199 ByValStoreOffset += Flags.getByValSize();
3200 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3201 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3202 CCInfo.nextInRegsParam();
3204 unsigned FIOffset = VA.getLocMemOffset();
3205 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3208 // Create load nodes to retrieve arguments from the stack.
3209 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3210 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3211 MachinePointerInfo::getFixedStack(FI),
3212 false, false, false, 0));
3214 lastInsIndex = index;
3220 if (isVarArg && MFI->hasVAStart())
3221 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3222 CCInfo.getNextStackOffset(),
3223 TotalArgRegsSaveSize);
3225 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3230 /// isFloatingPointZero - Return true if this is +0.0.
3231 static bool isFloatingPointZero(SDValue Op) {
3232 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3233 return CFP->getValueAPF().isPosZero();
3234 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3235 // Maybe this has already been legalized into the constant pool?
3236 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3237 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3238 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3239 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3240 return CFP->getValueAPF().isPosZero();
3242 } else if (Op->getOpcode() == ISD::BITCAST &&
3243 Op->getValueType(0) == MVT::f64) {
3244 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3245 // created by LowerConstantFP().
3246 SDValue BitcastOp = Op->getOperand(0);
3247 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3248 SDValue MoveOp = BitcastOp->getOperand(0);
3249 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3250 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3258 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3259 /// the given operands.
3261 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3262 SDValue &ARMcc, SelectionDAG &DAG,
3264 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3265 unsigned C = RHSC->getZExtValue();
3266 if (!isLegalICmpImmediate(C)) {
3267 // Constant does not fit, try adjusting it by one?
3272 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3273 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3274 RHS = DAG.getConstant(C-1, MVT::i32);
3279 if (C != 0 && isLegalICmpImmediate(C-1)) {
3280 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3281 RHS = DAG.getConstant(C-1, MVT::i32);
3286 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3287 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3288 RHS = DAG.getConstant(C+1, MVT::i32);
3293 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3294 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3295 RHS = DAG.getConstant(C+1, MVT::i32);
3302 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3303 ARMISD::NodeType CompareType;
3306 CompareType = ARMISD::CMP;
3311 CompareType = ARMISD::CMPZ;
3314 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3315 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3318 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3320 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3322 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3324 if (!isFloatingPointZero(RHS))
3325 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3327 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3328 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3331 /// duplicateCmp - Glue values can have only one use, so this function
3332 /// duplicates a comparison node.
3334 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3335 unsigned Opc = Cmp.getOpcode();
3337 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3338 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3340 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3341 Cmp = Cmp.getOperand(0);
3342 Opc = Cmp.getOpcode();
3343 if (Opc == ARMISD::CMPFP)
3344 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3346 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3347 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3349 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3352 std::pair<SDValue, SDValue>
3353 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3354 SDValue &ARMcc) const {
3355 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3357 SDValue Value, OverflowCmp;
3358 SDValue LHS = Op.getOperand(0);
3359 SDValue RHS = Op.getOperand(1);
3362 // FIXME: We are currently always generating CMPs because we don't support
3363 // generating CMN through the backend. This is not as good as the natural
3364 // CMP case because it causes a register dependency and cannot be folded
3367 switch (Op.getOpcode()) {
3369 llvm_unreachable("Unknown overflow instruction!");
3371 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3372 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3373 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3376 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3377 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3378 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3381 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3382 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3383 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3386 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3387 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3388 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3392 return std::make_pair(Value, OverflowCmp);
3397 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3398 // Let legalize expand this if it isn't a legal type yet.
3399 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3402 SDValue Value, OverflowCmp;
3404 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3405 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3406 // We use 0 and 1 as false and true values.
3407 SDValue TVal = DAG.getConstant(1, MVT::i32);
3408 SDValue FVal = DAG.getConstant(0, MVT::i32);
3409 EVT VT = Op.getValueType();
3411 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3412 ARMcc, CCR, OverflowCmp);
3414 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3415 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3419 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3420 SDValue Cond = Op.getOperand(0);
3421 SDValue SelectTrue = Op.getOperand(1);
3422 SDValue SelectFalse = Op.getOperand(2);
3424 unsigned Opc = Cond.getOpcode();
3426 if (Cond.getResNo() == 1 &&
3427 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3428 Opc == ISD::USUBO)) {
3429 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3432 SDValue Value, OverflowCmp;
3434 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3435 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3436 EVT VT = Op.getValueType();
3438 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3444 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3445 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3447 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3448 const ConstantSDNode *CMOVTrue =
3449 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3450 const ConstantSDNode *CMOVFalse =
3451 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3453 if (CMOVTrue && CMOVFalse) {
3454 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3455 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3459 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3461 False = SelectFalse;
3462 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3467 if (True.getNode() && False.getNode()) {
3468 EVT VT = Op.getValueType();
3469 SDValue ARMcc = Cond.getOperand(2);
3470 SDValue CCR = Cond.getOperand(3);
3471 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3472 assert(True.getValueType() == VT);
3473 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3478 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3479 // undefined bits before doing a full-word comparison with zero.
3480 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3481 DAG.getConstant(1, Cond.getValueType()));
3483 return DAG.getSelectCC(dl, Cond,
3484 DAG.getConstant(0, Cond.getValueType()),
3485 SelectTrue, SelectFalse, ISD::SETNE);
3488 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3489 if (CC == ISD::SETNE)
3491 return ISD::getSetCCInverse(CC, true);
3494 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3495 bool &swpCmpOps, bool &swpVselOps) {
3496 // Start by selecting the GE condition code for opcodes that return true for
3498 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3500 CondCode = ARMCC::GE;
3502 // and GT for opcodes that return false for 'equality'.
3503 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3505 CondCode = ARMCC::GT;
3507 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3508 // to swap the compare operands.
3509 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3513 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3514 // If we have an unordered opcode, we need to swap the operands to the VSEL
3515 // instruction (effectively negating the condition).
3517 // This also has the effect of swapping which one of 'less' or 'greater'
3518 // returns true, so we also swap the compare operands. It also switches
3519 // whether we return true for 'equality', so we compensate by picking the
3520 // opposite condition code to our original choice.
3521 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3522 CC == ISD::SETUGT) {
3523 swpCmpOps = !swpCmpOps;
3524 swpVselOps = !swpVselOps;
3525 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3528 // 'ordered' is 'anything but unordered', so use the VS condition code and
3529 // swap the VSEL operands.
3530 if (CC == ISD::SETO) {
3531 CondCode = ARMCC::VS;
3535 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3536 // code and swap the VSEL operands.
3537 if (CC == ISD::SETUNE) {
3538 CondCode = ARMCC::EQ;
3543 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3544 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3545 SDValue Cmp, SelectionDAG &DAG) const {
3546 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3547 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3548 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3549 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3550 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3552 SDValue TrueLow = TrueVal.getValue(0);
3553 SDValue TrueHigh = TrueVal.getValue(1);
3554 SDValue FalseLow = FalseVal.getValue(0);
3555 SDValue FalseHigh = FalseVal.getValue(1);
3557 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3559 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3560 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3562 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3564 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3569 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3570 EVT VT = Op.getValueType();
3571 SDValue LHS = Op.getOperand(0);
3572 SDValue RHS = Op.getOperand(1);
3573 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3574 SDValue TrueVal = Op.getOperand(2);
3575 SDValue FalseVal = Op.getOperand(3);
3578 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3579 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3582 // If softenSetCCOperands only returned one value, we should compare it to
3584 if (!RHS.getNode()) {
3585 RHS = DAG.getConstant(0, LHS.getValueType());
3590 if (LHS.getValueType() == MVT::i32) {
3591 // Try to generate VSEL on ARMv8.
3592 // The VSEL instruction can't use all the usual ARM condition
3593 // codes: it only has two bits to select the condition code, so it's
3594 // constrained to use only GE, GT, VS and EQ.
3596 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3597 // swap the operands of the previous compare instruction (effectively
3598 // inverting the compare condition, swapping 'less' and 'greater') and
3599 // sometimes need to swap the operands to the VSEL (which inverts the
3600 // condition in the sense of firing whenever the previous condition didn't)
3601 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3602 TrueVal.getValueType() == MVT::f64)) {
3603 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3604 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3605 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3606 CC = getInverseCCForVSEL(CC);
3607 std::swap(TrueVal, FalseVal);
3612 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3613 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3614 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3617 ARMCC::CondCodes CondCode, CondCode2;
3618 FPCCToARMCC(CC, CondCode, CondCode2);
3620 // Try to generate VSEL on ARMv8.
3621 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3622 TrueVal.getValueType() == MVT::f64)) {
3623 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3624 // same operands, as follows:
3625 // c = fcmp [ogt, olt, ugt, ult] a, b
3627 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3628 // handled differently than the original code sequence.
3629 if (getTargetMachine().Options.UnsafeFPMath) {
3630 if (LHS == TrueVal && RHS == FalseVal) {
3631 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3632 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3633 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3634 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3635 } else if (LHS == FalseVal && RHS == TrueVal) {
3636 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3637 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3638 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3639 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3643 bool swpCmpOps = false;
3644 bool swpVselOps = false;
3645 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3647 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3648 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3650 std::swap(LHS, RHS);
3652 std::swap(TrueVal, FalseVal);
3656 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3657 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3658 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3659 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3660 if (CondCode2 != ARMCC::AL) {
3661 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3662 // FIXME: Needs another CMP because flag can have but one use.
3663 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3664 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3669 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3670 /// to morph to an integer compare sequence.
3671 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3672 const ARMSubtarget *Subtarget) {
3673 SDNode *N = Op.getNode();
3674 if (!N->hasOneUse())
3675 // Otherwise it requires moving the value from fp to integer registers.
3677 if (!N->getNumValues())
3679 EVT VT = Op.getValueType();
3680 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3681 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3682 // vmrs are very slow, e.g. cortex-a8.
3685 if (isFloatingPointZero(Op)) {
3689 return ISD::isNormalLoad(N);
3692 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3693 if (isFloatingPointZero(Op))
3694 return DAG.getConstant(0, MVT::i32);
3696 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3697 return DAG.getLoad(MVT::i32, SDLoc(Op),
3698 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3699 Ld->isVolatile(), Ld->isNonTemporal(),
3700 Ld->isInvariant(), Ld->getAlignment());
3702 llvm_unreachable("Unknown VFP cmp argument!");
3705 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3706 SDValue &RetVal1, SDValue &RetVal2) {
3707 if (isFloatingPointZero(Op)) {
3708 RetVal1 = DAG.getConstant(0, MVT::i32);
3709 RetVal2 = DAG.getConstant(0, MVT::i32);
3713 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3714 SDValue Ptr = Ld->getBasePtr();
3715 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3716 Ld->getChain(), Ptr,
3717 Ld->getPointerInfo(),
3718 Ld->isVolatile(), Ld->isNonTemporal(),
3719 Ld->isInvariant(), Ld->getAlignment());
3721 EVT PtrType = Ptr.getValueType();
3722 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3723 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3724 PtrType, Ptr, DAG.getConstant(4, PtrType));
3725 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3726 Ld->getChain(), NewPtr,
3727 Ld->getPointerInfo().getWithOffset(4),
3728 Ld->isVolatile(), Ld->isNonTemporal(),
3729 Ld->isInvariant(), NewAlign);
3733 llvm_unreachable("Unknown VFP cmp argument!");
3736 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3737 /// f32 and even f64 comparisons to integer ones.
3739 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3740 SDValue Chain = Op.getOperand(0);
3741 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3742 SDValue LHS = Op.getOperand(2);
3743 SDValue RHS = Op.getOperand(3);
3744 SDValue Dest = Op.getOperand(4);
3747 bool LHSSeenZero = false;
3748 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3749 bool RHSSeenZero = false;
3750 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3751 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3752 // If unsafe fp math optimization is enabled and there are no other uses of
3753 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3754 // to an integer comparison.
3755 if (CC == ISD::SETOEQ)
3757 else if (CC == ISD::SETUNE)
3760 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3762 if (LHS.getValueType() == MVT::f32) {
3763 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3764 bitcastf32Toi32(LHS, DAG), Mask);
3765 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3766 bitcastf32Toi32(RHS, DAG), Mask);
3767 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3768 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3769 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3770 Chain, Dest, ARMcc, CCR, Cmp);
3775 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3776 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3777 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3778 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3779 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3780 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3781 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3782 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3783 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3789 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3790 SDValue Chain = Op.getOperand(0);
3791 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3792 SDValue LHS = Op.getOperand(2);
3793 SDValue RHS = Op.getOperand(3);
3794 SDValue Dest = Op.getOperand(4);
3797 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3798 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3801 // If softenSetCCOperands only returned one value, we should compare it to
3803 if (!RHS.getNode()) {
3804 RHS = DAG.getConstant(0, LHS.getValueType());
3809 if (LHS.getValueType() == MVT::i32) {
3811 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3812 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3813 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3814 Chain, Dest, ARMcc, CCR, Cmp);
3817 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3819 if (getTargetMachine().Options.UnsafeFPMath &&
3820 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3821 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3822 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3823 if (Result.getNode())
3827 ARMCC::CondCodes CondCode, CondCode2;
3828 FPCCToARMCC(CC, CondCode, CondCode2);
3830 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3831 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3832 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3833 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3834 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3835 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3836 if (CondCode2 != ARMCC::AL) {
3837 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3838 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3839 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3844 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3845 SDValue Chain = Op.getOperand(0);
3846 SDValue Table = Op.getOperand(1);
3847 SDValue Index = Op.getOperand(2);
3850 EVT PTy = getPointerTy();
3851 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3852 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3853 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3854 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3855 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3856 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3857 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3858 if (Subtarget->isThumb2()) {
3859 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3860 // which does another jump to the destination. This also makes it easier
3861 // to translate it to TBB / TBH later.
3862 // FIXME: This might not work if the function is extremely large.
3863 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3864 Addr, Op.getOperand(2), JTI, UId);
3866 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3867 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3868 MachinePointerInfo::getJumpTable(),
3869 false, false, false, 0);
3870 Chain = Addr.getValue(1);
3871 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3872 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3874 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3875 MachinePointerInfo::getJumpTable(),
3876 false, false, false, 0);
3877 Chain = Addr.getValue(1);
3878 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3882 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3883 EVT VT = Op.getValueType();
3886 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3887 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3889 return DAG.UnrollVectorOp(Op.getNode());
3892 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3893 "Invalid type for custom lowering!");
3894 if (VT != MVT::v4i16)
3895 return DAG.UnrollVectorOp(Op.getNode());
3897 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3898 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3901 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3902 EVT VT = Op.getValueType();
3904 return LowerVectorFP_TO_INT(Op, DAG);
3906 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3908 if (Op.getOpcode() == ISD::FP_TO_SINT)
3909 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3912 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3914 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3915 /*isSigned*/ false, SDLoc(Op)).first;
3921 switch (Op.getOpcode()) {
3922 default: llvm_unreachable("Invalid opcode!");
3923 case ISD::FP_TO_SINT:
3924 Opc = ARMISD::FTOSI;
3926 case ISD::FP_TO_UINT:
3927 Opc = ARMISD::FTOUI;
3930 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3931 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3934 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3935 EVT VT = Op.getValueType();
3938 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3939 if (VT.getVectorElementType() == MVT::f32)
3941 return DAG.UnrollVectorOp(Op.getNode());
3944 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3945 "Invalid type for custom lowering!");
3946 if (VT != MVT::v4f32)
3947 return DAG.UnrollVectorOp(Op.getNode());
3951 switch (Op.getOpcode()) {
3952 default: llvm_unreachable("Invalid opcode!");
3953 case ISD::SINT_TO_FP:
3954 CastOpc = ISD::SIGN_EXTEND;
3955 Opc = ISD::SINT_TO_FP;
3957 case ISD::UINT_TO_FP:
3958 CastOpc = ISD::ZERO_EXTEND;
3959 Opc = ISD::UINT_TO_FP;
3963 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3964 return DAG.getNode(Opc, dl, VT, Op);
3967 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3968 EVT VT = Op.getValueType();
3970 return LowerVectorINT_TO_FP(Op, DAG);
3972 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3974 if (Op.getOpcode() == ISD::SINT_TO_FP)
3975 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3978 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3980 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3981 /*isSigned*/ false, SDLoc(Op)).first;
3987 switch (Op.getOpcode()) {
3988 default: llvm_unreachable("Invalid opcode!");
3989 case ISD::SINT_TO_FP:
3990 Opc = ARMISD::SITOF;
3992 case ISD::UINT_TO_FP:
3993 Opc = ARMISD::UITOF;
3997 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3998 return DAG.getNode(Opc, dl, VT, Op);
4001 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4002 // Implement fcopysign with a fabs and a conditional fneg.
4003 SDValue Tmp0 = Op.getOperand(0);
4004 SDValue Tmp1 = Op.getOperand(1);
4006 EVT VT = Op.getValueType();
4007 EVT SrcVT = Tmp1.getValueType();
4008 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4009 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4010 bool UseNEON = !InGPR && Subtarget->hasNEON();
4013 // Use VBSL to copy the sign bit.
4014 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4015 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4016 DAG.getTargetConstant(EncodedVal, MVT::i32));
4017 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4019 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4020 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4021 DAG.getConstant(32, MVT::i32));
4022 else /*if (VT == MVT::f32)*/
4023 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4024 if (SrcVT == MVT::f32) {
4025 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4027 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4028 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4029 DAG.getConstant(32, MVT::i32));
4030 } else if (VT == MVT::f32)
4031 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4032 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4033 DAG.getConstant(32, MVT::i32));
4034 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4035 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4037 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4039 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4040 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4041 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4043 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4044 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4045 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4046 if (VT == MVT::f32) {
4047 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4048 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4049 DAG.getConstant(0, MVT::i32));
4051 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4057 // Bitcast operand 1 to i32.
4058 if (SrcVT == MVT::f64)
4059 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4061 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4063 // Or in the signbit with integer operations.
4064 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4065 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4066 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4067 if (VT == MVT::f32) {
4068 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4069 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4070 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4071 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4074 // f64: Or the high part with signbit and then combine two parts.
4075 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4077 SDValue Lo = Tmp0.getValue(0);
4078 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4079 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4080 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4083 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4084 MachineFunction &MF = DAG.getMachineFunction();
4085 MachineFrameInfo *MFI = MF.getFrameInfo();
4086 MFI->setReturnAddressIsTaken(true);
4088 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4091 EVT VT = Op.getValueType();
4093 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4095 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4096 SDValue Offset = DAG.getConstant(4, MVT::i32);
4097 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4098 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4099 MachinePointerInfo(), false, false, false, 0);
4102 // Return LR, which contains the return address. Mark it an implicit live-in.
4103 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4104 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4107 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4108 const ARMBaseRegisterInfo &ARI =
4109 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4110 MachineFunction &MF = DAG.getMachineFunction();
4111 MachineFrameInfo *MFI = MF.getFrameInfo();
4112 MFI->setFrameAddressIsTaken(true);
4114 EVT VT = Op.getValueType();
4115 SDLoc dl(Op); // FIXME probably not meaningful
4116 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4117 unsigned FrameReg = ARI.getFrameRegister(MF);
4118 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4120 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4121 MachinePointerInfo(),
4122 false, false, false, 0);
4126 // FIXME? Maybe this could be a TableGen attribute on some registers and
4127 // this table could be generated automatically from RegInfo.
4128 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4130 unsigned Reg = StringSwitch<unsigned>(RegName)
4131 .Case("sp", ARM::SP)
4135 report_fatal_error("Invalid register name global variable");
4138 /// ExpandBITCAST - If the target supports VFP, this function is called to
4139 /// expand a bit convert where either the source or destination type is i64 to
4140 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4141 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4142 /// vectors), since the legalizer won't know what to do with that.
4143 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4146 SDValue Op = N->getOperand(0);
4148 // This function is only supposed to be called for i64 types, either as the
4149 // source or destination of the bit convert.
4150 EVT SrcVT = Op.getValueType();
4151 EVT DstVT = N->getValueType(0);
4152 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4153 "ExpandBITCAST called for non-i64 type");
4155 // Turn i64->f64 into VMOVDRR.
4156 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4157 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4158 DAG.getConstant(0, MVT::i32));
4159 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4160 DAG.getConstant(1, MVT::i32));
4161 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4162 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4165 // Turn f64->i64 into VMOVRRD.
4166 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4168 if (TLI.isBigEndian() && SrcVT.isVector() &&
4169 SrcVT.getVectorNumElements() > 1)
4170 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4171 DAG.getVTList(MVT::i32, MVT::i32),
4172 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4174 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4175 DAG.getVTList(MVT::i32, MVT::i32), Op);
4176 // Merge the pieces into a single i64 value.
4177 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4183 /// getZeroVector - Returns a vector of specified type with all zero elements.
4184 /// Zero vectors are used to represent vector negation and in those cases
4185 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4186 /// not support i64 elements, so sometimes the zero vectors will need to be
4187 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4189 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4190 assert(VT.isVector() && "Expected a vector type");
4191 // The canonical modified immediate encoding of a zero vector is....0!
4192 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4193 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4194 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4195 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4198 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4199 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4200 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4201 SelectionDAG &DAG) const {
4202 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4203 EVT VT = Op.getValueType();
4204 unsigned VTBits = VT.getSizeInBits();
4206 SDValue ShOpLo = Op.getOperand(0);
4207 SDValue ShOpHi = Op.getOperand(1);
4208 SDValue ShAmt = Op.getOperand(2);
4210 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4212 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4214 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4215 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4216 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4217 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4218 DAG.getConstant(VTBits, MVT::i32));
4219 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4220 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4221 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4223 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4224 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4226 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4227 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4230 SDValue Ops[2] = { Lo, Hi };
4231 return DAG.getMergeValues(Ops, dl);
4234 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4235 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4236 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4237 SelectionDAG &DAG) const {
4238 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4239 EVT VT = Op.getValueType();
4240 unsigned VTBits = VT.getSizeInBits();
4242 SDValue ShOpLo = Op.getOperand(0);
4243 SDValue ShOpHi = Op.getOperand(1);
4244 SDValue ShAmt = Op.getOperand(2);
4247 assert(Op.getOpcode() == ISD::SHL_PARTS);
4248 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4249 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4250 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4251 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4252 DAG.getConstant(VTBits, MVT::i32));
4253 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4254 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4256 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4257 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4258 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4260 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4261 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4264 SDValue Ops[2] = { Lo, Hi };
4265 return DAG.getMergeValues(Ops, dl);
4268 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4269 SelectionDAG &DAG) const {
4270 // The rounding mode is in bits 23:22 of the FPSCR.
4271 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4272 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4273 // so that the shift + and get folded into a bitfield extract.
4275 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4276 DAG.getConstant(Intrinsic::arm_get_fpscr,
4278 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4279 DAG.getConstant(1U << 22, MVT::i32));
4280 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4281 DAG.getConstant(22, MVT::i32));
4282 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4283 DAG.getConstant(3, MVT::i32));
4286 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4287 const ARMSubtarget *ST) {
4288 EVT VT = N->getValueType(0);
4291 if (!ST->hasV6T2Ops())
4294 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4295 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4298 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4299 /// for each 16-bit element from operand, repeated. The basic idea is to
4300 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4302 /// Trace for v4i16:
4303 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4304 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4305 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4306 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4307 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4308 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4309 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4310 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4311 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4312 EVT VT = N->getValueType(0);
4315 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4316 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4317 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4318 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4319 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4320 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4323 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4324 /// bit-count for each 16-bit element from the operand. We need slightly
4325 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4326 /// 64/128-bit registers.
4328 /// Trace for v4i16:
4329 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4330 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4331 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4332 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4333 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4334 EVT VT = N->getValueType(0);
4337 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4338 if (VT.is64BitVector()) {
4339 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4340 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4341 DAG.getIntPtrConstant(0));
4343 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4344 BitCounts, DAG.getIntPtrConstant(0));
4345 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4349 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4350 /// bit-count for each 32-bit element from the operand. The idea here is
4351 /// to split the vector into 16-bit elements, leverage the 16-bit count
4352 /// routine, and then combine the results.
4354 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4355 /// input = [v0 v1 ] (vi: 32-bit elements)
4356 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4357 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4358 /// vrev: N0 = [k1 k0 k3 k2 ]
4360 /// N1 =+[k1 k0 k3 k2 ]
4362 /// N2 =+[k1 k3 k0 k2 ]
4364 /// Extended =+[k1 k3 k0 k2 ]
4366 /// Extracted=+[k1 k3 ]
4368 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4369 EVT VT = N->getValueType(0);
4372 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4374 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4375 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4376 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4377 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4378 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4380 if (VT.is64BitVector()) {
4381 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4382 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4383 DAG.getIntPtrConstant(0));
4385 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4386 DAG.getIntPtrConstant(0));
4387 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4391 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4392 const ARMSubtarget *ST) {
4393 EVT VT = N->getValueType(0);
4395 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4396 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4397 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4398 "Unexpected type for custom ctpop lowering");
4400 if (VT.getVectorElementType() == MVT::i32)
4401 return lowerCTPOP32BitElements(N, DAG);
4403 return lowerCTPOP16BitElements(N, DAG);
4406 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4407 const ARMSubtarget *ST) {
4408 EVT VT = N->getValueType(0);
4414 // Lower vector shifts on NEON to use VSHL.
4415 assert(ST->hasNEON() && "unexpected vector shift");
4417 // Left shifts translate directly to the vshiftu intrinsic.
4418 if (N->getOpcode() == ISD::SHL)
4419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4420 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4421 N->getOperand(0), N->getOperand(1));
4423 assert((N->getOpcode() == ISD::SRA ||
4424 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4426 // NEON uses the same intrinsics for both left and right shifts. For
4427 // right shifts, the shift amounts are negative, so negate the vector of
4429 EVT ShiftVT = N->getOperand(1).getValueType();
4430 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4431 getZeroVector(ShiftVT, DAG, dl),
4433 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4434 Intrinsic::arm_neon_vshifts :
4435 Intrinsic::arm_neon_vshiftu);
4436 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4437 DAG.getConstant(vshiftInt, MVT::i32),
4438 N->getOperand(0), NegatedCount);
4441 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4442 const ARMSubtarget *ST) {
4443 EVT VT = N->getValueType(0);
4446 // We can get here for a node like i32 = ISD::SHL i32, i64
4450 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4451 "Unknown shift to lower!");
4453 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4454 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4455 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4458 // If we are in thumb mode, we don't have RRX.
4459 if (ST->isThumb1Only()) return SDValue();
4461 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4462 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4463 DAG.getConstant(0, MVT::i32));
4464 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4465 DAG.getConstant(1, MVT::i32));
4467 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4468 // captures the result into a carry flag.
4469 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4470 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4472 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4473 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4475 // Merge the pieces into a single i64 value.
4476 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4479 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4480 SDValue TmpOp0, TmpOp1;
4481 bool Invert = false;
4485 SDValue Op0 = Op.getOperand(0);
4486 SDValue Op1 = Op.getOperand(1);
4487 SDValue CC = Op.getOperand(2);
4488 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4489 EVT VT = Op.getValueType();
4490 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4493 if (Op1.getValueType().isFloatingPoint()) {
4494 switch (SetCCOpcode) {
4495 default: llvm_unreachable("Illegal FP comparison");
4497 case ISD::SETNE: Invert = true; // Fallthrough
4499 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4501 case ISD::SETLT: Swap = true; // Fallthrough
4503 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4505 case ISD::SETLE: Swap = true; // Fallthrough
4507 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4508 case ISD::SETUGE: Swap = true; // Fallthrough
4509 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4510 case ISD::SETUGT: Swap = true; // Fallthrough
4511 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4512 case ISD::SETUEQ: Invert = true; // Fallthrough
4514 // Expand this to (OLT | OGT).
4518 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4519 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4521 case ISD::SETUO: Invert = true; // Fallthrough
4523 // Expand this to (OLT | OGE).
4527 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4528 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4532 // Integer comparisons.
4533 switch (SetCCOpcode) {
4534 default: llvm_unreachable("Illegal integer comparison");
4535 case ISD::SETNE: Invert = true;
4536 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4537 case ISD::SETLT: Swap = true;
4538 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4539 case ISD::SETLE: Swap = true;
4540 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4541 case ISD::SETULT: Swap = true;
4542 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4543 case ISD::SETULE: Swap = true;
4544 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4547 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4548 if (Opc == ARMISD::VCEQ) {
4551 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4553 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4556 // Ignore bitconvert.
4557 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4558 AndOp = AndOp.getOperand(0);
4560 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4562 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4563 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4570 std::swap(Op0, Op1);
4572 // If one of the operands is a constant vector zero, attempt to fold the
4573 // comparison to a specialized compare-against-zero form.
4575 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4577 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4578 if (Opc == ARMISD::VCGE)
4579 Opc = ARMISD::VCLEZ;
4580 else if (Opc == ARMISD::VCGT)
4581 Opc = ARMISD::VCLTZ;
4586 if (SingleOp.getNode()) {
4589 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4591 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4593 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4595 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4597 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4599 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4602 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4605 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4608 Result = DAG.getNOT(dl, Result, VT);
4613 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4614 /// valid vector constant for a NEON instruction with a "modified immediate"
4615 /// operand (e.g., VMOV). If so, return the encoded value.
4616 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4617 unsigned SplatBitSize, SelectionDAG &DAG,
4618 EVT &VT, bool is128Bits, NEONModImmType type) {
4619 unsigned OpCmode, Imm;
4621 // SplatBitSize is set to the smallest size that splats the vector, so a
4622 // zero vector will always have SplatBitSize == 8. However, NEON modified
4623 // immediate instructions others than VMOV do not support the 8-bit encoding
4624 // of a zero vector, and the default encoding of zero is supposed to be the
4629 switch (SplatBitSize) {
4631 if (type != VMOVModImm)
4633 // Any 1-byte value is OK. Op=0, Cmode=1110.
4634 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4637 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4641 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4642 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4643 if ((SplatBits & ~0xff) == 0) {
4644 // Value = 0x00nn: Op=x, Cmode=100x.
4649 if ((SplatBits & ~0xff00) == 0) {
4650 // Value = 0xnn00: Op=x, Cmode=101x.
4652 Imm = SplatBits >> 8;
4658 // NEON's 32-bit VMOV supports splat values where:
4659 // * only one byte is nonzero, or
4660 // * the least significant byte is 0xff and the second byte is nonzero, or
4661 // * the least significant 2 bytes are 0xff and the third is nonzero.
4662 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4663 if ((SplatBits & ~0xff) == 0) {
4664 // Value = 0x000000nn: Op=x, Cmode=000x.
4669 if ((SplatBits & ~0xff00) == 0) {
4670 // Value = 0x0000nn00: Op=x, Cmode=001x.
4672 Imm = SplatBits >> 8;
4675 if ((SplatBits & ~0xff0000) == 0) {
4676 // Value = 0x00nn0000: Op=x, Cmode=010x.
4678 Imm = SplatBits >> 16;
4681 if ((SplatBits & ~0xff000000) == 0) {
4682 // Value = 0xnn000000: Op=x, Cmode=011x.
4684 Imm = SplatBits >> 24;
4688 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4689 if (type == OtherModImm) return SDValue();
4691 if ((SplatBits & ~0xffff) == 0 &&
4692 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4693 // Value = 0x0000nnff: Op=x, Cmode=1100.
4695 Imm = SplatBits >> 8;
4699 if ((SplatBits & ~0xffffff) == 0 &&
4700 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4701 // Value = 0x00nnffff: Op=x, Cmode=1101.
4703 Imm = SplatBits >> 16;
4707 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4708 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4709 // VMOV.I32. A (very) minor optimization would be to replicate the value
4710 // and fall through here to test for a valid 64-bit splat. But, then the
4711 // caller would also need to check and handle the change in size.
4715 if (type != VMOVModImm)
4717 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4718 uint64_t BitMask = 0xff;
4720 unsigned ImmMask = 1;
4722 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4723 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4726 } else if ((SplatBits & BitMask) != 0) {
4733 if (DAG.getTargetLoweringInfo().isBigEndian())
4734 // swap higher and lower 32 bit word
4735 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4737 // Op=1, Cmode=1110.
4739 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4744 llvm_unreachable("unexpected size for isNEONModifiedImm");
4747 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4748 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4751 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4752 const ARMSubtarget *ST) const {
4756 bool IsDouble = Op.getValueType() == MVT::f64;
4757 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4759 // Use the default (constant pool) lowering for double constants when we have
4761 if (IsDouble && Subtarget->isFPOnlySP())
4764 // Try splatting with a VMOV.f32...
4765 APFloat FPVal = CFP->getValueAPF();
4766 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4769 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4770 // We have code in place to select a valid ConstantFP already, no need to
4775 // It's a float and we are trying to use NEON operations where
4776 // possible. Lower it to a splat followed by an extract.
4778 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4779 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4781 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4782 DAG.getConstant(0, MVT::i32));
4785 // The rest of our options are NEON only, make sure that's allowed before
4787 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4791 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4793 // It wouldn't really be worth bothering for doubles except for one very
4794 // important value, which does happen to match: 0.0. So make sure we don't do
4796 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4799 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4800 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4802 if (NewVal != SDValue()) {
4804 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4807 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4809 // It's a float: cast and extract a vector element.
4810 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4812 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4813 DAG.getConstant(0, MVT::i32));
4816 // Finally, try a VMVN.i32
4817 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4819 if (NewVal != SDValue()) {
4821 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4824 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4826 // It's a float: cast and extract a vector element.
4827 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4829 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4830 DAG.getConstant(0, MVT::i32));
4836 // check if an VEXT instruction can handle the shuffle mask when the
4837 // vector sources of the shuffle are the same.
4838 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4839 unsigned NumElts = VT.getVectorNumElements();
4841 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4847 // If this is a VEXT shuffle, the immediate value is the index of the first
4848 // element. The other shuffle indices must be the successive elements after
4850 unsigned ExpectedElt = Imm;
4851 for (unsigned i = 1; i < NumElts; ++i) {
4852 // Increment the expected index. If it wraps around, just follow it
4853 // back to index zero and keep going.
4855 if (ExpectedElt == NumElts)
4858 if (M[i] < 0) continue; // ignore UNDEF indices
4859 if (ExpectedElt != static_cast<unsigned>(M[i]))
4867 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4868 bool &ReverseVEXT, unsigned &Imm) {
4869 unsigned NumElts = VT.getVectorNumElements();
4870 ReverseVEXT = false;
4872 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4878 // If this is a VEXT shuffle, the immediate value is the index of the first
4879 // element. The other shuffle indices must be the successive elements after
4881 unsigned ExpectedElt = Imm;
4882 for (unsigned i = 1; i < NumElts; ++i) {
4883 // Increment the expected index. If it wraps around, it may still be
4884 // a VEXT but the source vectors must be swapped.
4886 if (ExpectedElt == NumElts * 2) {
4891 if (M[i] < 0) continue; // ignore UNDEF indices
4892 if (ExpectedElt != static_cast<unsigned>(M[i]))
4896 // Adjust the index value if the source operands will be swapped.
4903 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4904 /// instruction with the specified blocksize. (The order of the elements
4905 /// within each block of the vector is reversed.)
4906 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4907 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4908 "Only possible block sizes for VREV are: 16, 32, 64");
4910 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4914 unsigned NumElts = VT.getVectorNumElements();
4915 unsigned BlockElts = M[0] + 1;
4916 // If the first shuffle index is UNDEF, be optimistic.
4918 BlockElts = BlockSize / EltSz;
4920 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4923 for (unsigned i = 0; i < NumElts; ++i) {
4924 if (M[i] < 0) continue; // ignore UNDEF indices
4925 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4932 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4933 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4934 // range, then 0 is placed into the resulting vector. So pretty much any mask
4935 // of 8 elements can work here.
4936 return VT == MVT::v8i8 && M.size() == 8;
4939 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4940 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4944 unsigned NumElts = VT.getVectorNumElements();
4945 WhichResult = (M[0] == 0 ? 0 : 1);
4946 for (unsigned i = 0; i < NumElts; i += 2) {
4947 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4948 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4954 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4955 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4956 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4957 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4958 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4962 unsigned NumElts = VT.getVectorNumElements();
4963 WhichResult = (M[0] == 0 ? 0 : 1);
4964 for (unsigned i = 0; i < NumElts; i += 2) {
4965 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4966 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4972 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4973 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4977 unsigned NumElts = VT.getVectorNumElements();
4978 WhichResult = (M[0] == 0 ? 0 : 1);
4979 for (unsigned i = 0; i != NumElts; ++i) {
4980 if (M[i] < 0) continue; // ignore UNDEF indices
4981 if ((unsigned) M[i] != 2 * i + WhichResult)
4985 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4986 if (VT.is64BitVector() && EltSz == 32)
4992 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4993 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4994 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4995 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4996 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5000 unsigned Half = VT.getVectorNumElements() / 2;
5001 WhichResult = (M[0] == 0 ? 0 : 1);
5002 for (unsigned j = 0; j != 2; ++j) {
5003 unsigned Idx = WhichResult;
5004 for (unsigned i = 0; i != Half; ++i) {
5005 int MIdx = M[i + j * Half];
5006 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5012 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5013 if (VT.is64BitVector() && EltSz == 32)
5019 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5020 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5024 unsigned NumElts = VT.getVectorNumElements();
5025 WhichResult = (M[0] == 0 ? 0 : 1);
5026 unsigned Idx = WhichResult * NumElts / 2;
5027 for (unsigned i = 0; i != NumElts; i += 2) {
5028 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5029 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5034 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5035 if (VT.is64BitVector() && EltSz == 32)
5041 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5042 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5043 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5044 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5045 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5049 unsigned NumElts = VT.getVectorNumElements();
5050 WhichResult = (M[0] == 0 ? 0 : 1);
5051 unsigned Idx = WhichResult * NumElts / 2;
5052 for (unsigned i = 0; i != NumElts; i += 2) {
5053 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5054 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5059 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5060 if (VT.is64BitVector() && EltSz == 32)
5066 /// \return true if this is a reverse operation on an vector.
5067 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5068 unsigned NumElts = VT.getVectorNumElements();
5069 // Make sure the mask has the right size.
5070 if (NumElts != M.size())
5073 // Look for <15, ..., 3, -1, 1, 0>.
5074 for (unsigned i = 0; i != NumElts; ++i)
5075 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5081 // If N is an integer constant that can be moved into a register in one
5082 // instruction, return an SDValue of such a constant (will become a MOV
5083 // instruction). Otherwise return null.
5084 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5085 const ARMSubtarget *ST, SDLoc dl) {
5087 if (!isa<ConstantSDNode>(N))
5089 Val = cast<ConstantSDNode>(N)->getZExtValue();
5091 if (ST->isThumb1Only()) {
5092 if (Val <= 255 || ~Val <= 255)
5093 return DAG.getConstant(Val, MVT::i32);
5095 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5096 return DAG.getConstant(Val, MVT::i32);
5101 // If this is a case we can't handle, return null and let the default
5102 // expansion code take care of it.
5103 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5104 const ARMSubtarget *ST) const {
5105 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5107 EVT VT = Op.getValueType();
5109 APInt SplatBits, SplatUndef;
5110 unsigned SplatBitSize;
5112 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5113 if (SplatBitSize <= 64) {
5114 // Check if an immediate VMOV works.
5116 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5117 SplatUndef.getZExtValue(), SplatBitSize,
5118 DAG, VmovVT, VT.is128BitVector(),
5120 if (Val.getNode()) {
5121 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5122 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5125 // Try an immediate VMVN.
5126 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5127 Val = isNEONModifiedImm(NegatedImm,
5128 SplatUndef.getZExtValue(), SplatBitSize,
5129 DAG, VmovVT, VT.is128BitVector(),
5131 if (Val.getNode()) {
5132 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5133 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5136 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5137 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5138 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5140 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5141 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5147 // Scan through the operands to see if only one value is used.
5149 // As an optimisation, even if more than one value is used it may be more
5150 // profitable to splat with one value then change some lanes.
5152 // Heuristically we decide to do this if the vector has a "dominant" value,
5153 // defined as splatted to more than half of the lanes.
5154 unsigned NumElts = VT.getVectorNumElements();
5155 bool isOnlyLowElement = true;
5156 bool usesOnlyOneValue = true;
5157 bool hasDominantValue = false;
5158 bool isConstant = true;
5160 // Map of the number of times a particular SDValue appears in the
5162 DenseMap<SDValue, unsigned> ValueCounts;
5164 for (unsigned i = 0; i < NumElts; ++i) {
5165 SDValue V = Op.getOperand(i);
5166 if (V.getOpcode() == ISD::UNDEF)
5169 isOnlyLowElement = false;
5170 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5173 ValueCounts.insert(std::make_pair(V, 0));
5174 unsigned &Count = ValueCounts[V];
5176 // Is this value dominant? (takes up more than half of the lanes)
5177 if (++Count > (NumElts / 2)) {
5178 hasDominantValue = true;
5182 if (ValueCounts.size() != 1)
5183 usesOnlyOneValue = false;
5184 if (!Value.getNode() && ValueCounts.size() > 0)
5185 Value = ValueCounts.begin()->first;
5187 if (ValueCounts.size() == 0)
5188 return DAG.getUNDEF(VT);
5190 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5191 // Keep going if we are hitting this case.
5192 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5193 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5195 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5197 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5198 // i32 and try again.
5199 if (hasDominantValue && EltSize <= 32) {
5203 // If we are VDUPing a value that comes directly from a vector, that will
5204 // cause an unnecessary move to and from a GPR, where instead we could
5205 // just use VDUPLANE. We can only do this if the lane being extracted
5206 // is at a constant index, as the VDUP from lane instructions only have
5207 // constant-index forms.
5208 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5209 isa<ConstantSDNode>(Value->getOperand(1))) {
5210 // We need to create a new undef vector to use for the VDUPLANE if the
5211 // size of the vector from which we get the value is different than the
5212 // size of the vector that we need to create. We will insert the element
5213 // such that the register coalescer will remove unnecessary copies.
5214 if (VT != Value->getOperand(0).getValueType()) {
5215 ConstantSDNode *constIndex;
5216 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5217 assert(constIndex && "The index is not a constant!");
5218 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5219 VT.getVectorNumElements();
5220 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5221 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5222 Value, DAG.getConstant(index, MVT::i32)),
5223 DAG.getConstant(index, MVT::i32));
5225 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5226 Value->getOperand(0), Value->getOperand(1));
5228 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5230 if (!usesOnlyOneValue) {
5231 // The dominant value was splatted as 'N', but we now have to insert
5232 // all differing elements.
5233 for (unsigned I = 0; I < NumElts; ++I) {
5234 if (Op.getOperand(I) == Value)
5236 SmallVector<SDValue, 3> Ops;
5238 Ops.push_back(Op.getOperand(I));
5239 Ops.push_back(DAG.getConstant(I, MVT::i32));
5240 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5245 if (VT.getVectorElementType().isFloatingPoint()) {
5246 SmallVector<SDValue, 8> Ops;
5247 for (unsigned i = 0; i < NumElts; ++i)
5248 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5250 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5251 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5252 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5254 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5256 if (usesOnlyOneValue) {
5257 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5258 if (isConstant && Val.getNode())
5259 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5263 // If all elements are constants and the case above didn't get hit, fall back
5264 // to the default expansion, which will generate a load from the constant
5269 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5271 SDValue shuffle = ReconstructShuffle(Op, DAG);
5272 if (shuffle != SDValue())
5276 // Vectors with 32- or 64-bit elements can be built by directly assigning
5277 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5278 // will be legalized.
5279 if (EltSize >= 32) {
5280 // Do the expansion with floating-point types, since that is what the VFP
5281 // registers are defined to use, and since i64 is not legal.
5282 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5283 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5284 SmallVector<SDValue, 8> Ops;
5285 for (unsigned i = 0; i < NumElts; ++i)
5286 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5287 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5288 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5291 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5292 // know the default expansion would otherwise fall back on something even
5293 // worse. For a vector with one or two non-undef values, that's
5294 // scalar_to_vector for the elements followed by a shuffle (provided the
5295 // shuffle is valid for the target) and materialization element by element
5296 // on the stack followed by a load for everything else.
5297 if (!isConstant && !usesOnlyOneValue) {
5298 SDValue Vec = DAG.getUNDEF(VT);
5299 for (unsigned i = 0 ; i < NumElts; ++i) {
5300 SDValue V = Op.getOperand(i);
5301 if (V.getOpcode() == ISD::UNDEF)
5303 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5304 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5312 // Gather data to see if the operation can be modelled as a
5313 // shuffle in combination with VEXTs.
5314 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5315 SelectionDAG &DAG) const {
5317 EVT VT = Op.getValueType();
5318 unsigned NumElts = VT.getVectorNumElements();
5320 SmallVector<SDValue, 2> SourceVecs;
5321 SmallVector<unsigned, 2> MinElts;
5322 SmallVector<unsigned, 2> MaxElts;
5324 for (unsigned i = 0; i < NumElts; ++i) {
5325 SDValue V = Op.getOperand(i);
5326 if (V.getOpcode() == ISD::UNDEF)
5328 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5329 // A shuffle can only come from building a vector from various
5330 // elements of other vectors.
5332 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5333 VT.getVectorElementType()) {
5334 // This code doesn't know how to handle shuffles where the vector
5335 // element types do not match (this happens because type legalization
5336 // promotes the return type of EXTRACT_VECTOR_ELT).
5337 // FIXME: It might be appropriate to extend this code to handle
5338 // mismatched types.
5342 // Record this extraction against the appropriate vector if possible...
5343 SDValue SourceVec = V.getOperand(0);
5344 // If the element number isn't a constant, we can't effectively
5345 // analyze what's going on.
5346 if (!isa<ConstantSDNode>(V.getOperand(1)))
5348 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5349 bool FoundSource = false;
5350 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5351 if (SourceVecs[j] == SourceVec) {
5352 if (MinElts[j] > EltNo)
5354 if (MaxElts[j] < EltNo)
5361 // Or record a new source if not...
5363 SourceVecs.push_back(SourceVec);
5364 MinElts.push_back(EltNo);
5365 MaxElts.push_back(EltNo);
5369 // Currently only do something sane when at most two source vectors
5371 if (SourceVecs.size() > 2)
5374 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5375 int VEXTOffsets[2] = {0, 0};
5377 // This loop extracts the usage patterns of the source vectors
5378 // and prepares appropriate SDValues for a shuffle if possible.
5379 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5380 if (SourceVecs[i].getValueType() == VT) {
5381 // No VEXT necessary
5382 ShuffleSrcs[i] = SourceVecs[i];
5385 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5386 // It probably isn't worth padding out a smaller vector just to
5387 // break it down again in a shuffle.
5391 // Since only 64-bit and 128-bit vectors are legal on ARM and
5392 // we've eliminated the other cases...
5393 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5394 "unexpected vector sizes in ReconstructShuffle");
5396 if (MaxElts[i] - MinElts[i] >= NumElts) {
5397 // Span too large for a VEXT to cope
5401 if (MinElts[i] >= NumElts) {
5402 // The extraction can just take the second half
5403 VEXTOffsets[i] = NumElts;
5404 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5406 DAG.getIntPtrConstant(NumElts));
5407 } else if (MaxElts[i] < NumElts) {
5408 // The extraction can just take the first half
5410 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5412 DAG.getIntPtrConstant(0));
5414 // An actual VEXT is needed
5415 VEXTOffsets[i] = MinElts[i];
5416 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5418 DAG.getIntPtrConstant(0));
5419 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5421 DAG.getIntPtrConstant(NumElts));
5422 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5423 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5427 SmallVector<int, 8> Mask;
5429 for (unsigned i = 0; i < NumElts; ++i) {
5430 SDValue Entry = Op.getOperand(i);
5431 if (Entry.getOpcode() == ISD::UNDEF) {
5436 SDValue ExtractVec = Entry.getOperand(0);
5437 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5438 .getOperand(1))->getSExtValue();
5439 if (ExtractVec == SourceVecs[0]) {
5440 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5442 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5446 // Final check before we try to produce nonsense...
5447 if (isShuffleMaskLegal(Mask, VT))
5448 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5454 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5455 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5456 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5457 /// are assumed to be legal.
5459 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5461 if (VT.getVectorNumElements() == 4 &&
5462 (VT.is128BitVector() || VT.is64BitVector())) {
5463 unsigned PFIndexes[4];
5464 for (unsigned i = 0; i != 4; ++i) {
5468 PFIndexes[i] = M[i];
5471 // Compute the index in the perfect shuffle table.
5472 unsigned PFTableIndex =
5473 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5474 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5475 unsigned Cost = (PFEntry >> 30);
5482 unsigned Imm, WhichResult;
5484 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5485 return (EltSize >= 32 ||
5486 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5487 isVREVMask(M, VT, 64) ||
5488 isVREVMask(M, VT, 32) ||
5489 isVREVMask(M, VT, 16) ||
5490 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5491 isVTBLMask(M, VT) ||
5492 isVTRNMask(M, VT, WhichResult) ||
5493 isVUZPMask(M, VT, WhichResult) ||
5494 isVZIPMask(M, VT, WhichResult) ||
5495 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5496 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5497 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5498 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5501 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5502 /// the specified operations to build the shuffle.
5503 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5504 SDValue RHS, SelectionDAG &DAG,
5506 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5507 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5508 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5511 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5520 OP_VUZPL, // VUZP, left result
5521 OP_VUZPR, // VUZP, right result
5522 OP_VZIPL, // VZIP, left result
5523 OP_VZIPR, // VZIP, right result
5524 OP_VTRNL, // VTRN, left result
5525 OP_VTRNR // VTRN, right result
5528 if (OpNum == OP_COPY) {
5529 if (LHSID == (1*9+2)*9+3) return LHS;
5530 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5534 SDValue OpLHS, OpRHS;
5535 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5536 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5537 EVT VT = OpLHS.getValueType();
5540 default: llvm_unreachable("Unknown shuffle opcode!");
5542 // VREV divides the vector in half and swaps within the half.
5543 if (VT.getVectorElementType() == MVT::i32 ||
5544 VT.getVectorElementType() == MVT::f32)
5545 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5546 // vrev <4 x i16> -> VREV32
5547 if (VT.getVectorElementType() == MVT::i16)
5548 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5549 // vrev <4 x i8> -> VREV16
5550 assert(VT.getVectorElementType() == MVT::i8);
5551 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5556 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5557 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5561 return DAG.getNode(ARMISD::VEXT, dl, VT,
5563 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5566 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5567 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5570 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5571 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5574 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5575 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5579 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5580 ArrayRef<int> ShuffleMask,
5581 SelectionDAG &DAG) {
5582 // Check to see if we can use the VTBL instruction.
5583 SDValue V1 = Op.getOperand(0);
5584 SDValue V2 = Op.getOperand(1);
5587 SmallVector<SDValue, 8> VTBLMask;
5588 for (ArrayRef<int>::iterator
5589 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5590 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5592 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5593 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5594 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5596 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5597 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5600 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5601 SelectionDAG &DAG) {
5603 SDValue OpLHS = Op.getOperand(0);
5604 EVT VT = OpLHS.getValueType();
5606 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5607 "Expect an v8i16/v16i8 type");
5608 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5609 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5610 // extract the first 8 bytes into the top double word and the last 8 bytes
5611 // into the bottom double word. The v8i16 case is similar.
5612 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5613 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5614 DAG.getConstant(ExtractNum, MVT::i32));
5617 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5618 SDValue V1 = Op.getOperand(0);
5619 SDValue V2 = Op.getOperand(1);
5621 EVT VT = Op.getValueType();
5622 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5624 // Convert shuffles that are directly supported on NEON to target-specific
5625 // DAG nodes, instead of keeping them as shuffles and matching them again
5626 // during code selection. This is more efficient and avoids the possibility
5627 // of inconsistencies between legalization and selection.
5628 // FIXME: floating-point vectors should be canonicalized to integer vectors
5629 // of the same time so that they get CSEd properly.
5630 ArrayRef<int> ShuffleMask = SVN->getMask();
5632 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5633 if (EltSize <= 32) {
5634 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5635 int Lane = SVN->getSplatIndex();
5636 // If this is undef splat, generate it via "just" vdup, if possible.
5637 if (Lane == -1) Lane = 0;
5639 // Test if V1 is a SCALAR_TO_VECTOR.
5640 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5641 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5643 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5644 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5646 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5647 !isa<ConstantSDNode>(V1.getOperand(0))) {
5648 bool IsScalarToVector = true;
5649 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5650 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5651 IsScalarToVector = false;
5654 if (IsScalarToVector)
5655 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5657 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5658 DAG.getConstant(Lane, MVT::i32));
5663 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5666 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5667 DAG.getConstant(Imm, MVT::i32));
5670 if (isVREVMask(ShuffleMask, VT, 64))
5671 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5672 if (isVREVMask(ShuffleMask, VT, 32))
5673 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5674 if (isVREVMask(ShuffleMask, VT, 16))
5675 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5677 if (V2->getOpcode() == ISD::UNDEF &&
5678 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5679 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5680 DAG.getConstant(Imm, MVT::i32));
5683 // Check for Neon shuffles that modify both input vectors in place.
5684 // If both results are used, i.e., if there are two shuffles with the same
5685 // source operands and with masks corresponding to both results of one of
5686 // these operations, DAG memoization will ensure that a single node is
5687 // used for both shuffles.
5688 unsigned WhichResult;
5689 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5690 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5691 V1, V2).getValue(WhichResult);
5692 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5693 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5694 V1, V2).getValue(WhichResult);
5695 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5696 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5697 V1, V2).getValue(WhichResult);
5699 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5700 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5701 V1, V1).getValue(WhichResult);
5702 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5703 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5704 V1, V1).getValue(WhichResult);
5705 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5706 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5707 V1, V1).getValue(WhichResult);
5710 // If the shuffle is not directly supported and it has 4 elements, use
5711 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5712 unsigned NumElts = VT.getVectorNumElements();
5714 unsigned PFIndexes[4];
5715 for (unsigned i = 0; i != 4; ++i) {
5716 if (ShuffleMask[i] < 0)
5719 PFIndexes[i] = ShuffleMask[i];
5722 // Compute the index in the perfect shuffle table.
5723 unsigned PFTableIndex =
5724 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5725 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5726 unsigned Cost = (PFEntry >> 30);
5729 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5732 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5733 if (EltSize >= 32) {
5734 // Do the expansion with floating-point types, since that is what the VFP
5735 // registers are defined to use, and since i64 is not legal.
5736 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5737 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5738 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5739 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5740 SmallVector<SDValue, 8> Ops;
5741 for (unsigned i = 0; i < NumElts; ++i) {
5742 if (ShuffleMask[i] < 0)
5743 Ops.push_back(DAG.getUNDEF(EltVT));
5745 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5746 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5747 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5750 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5751 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5754 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5755 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5757 if (VT == MVT::v8i8) {
5758 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5759 if (NewOp.getNode())
5766 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5767 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5768 SDValue Lane = Op.getOperand(2);
5769 if (!isa<ConstantSDNode>(Lane))
5775 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5776 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5777 SDValue Lane = Op.getOperand(1);
5778 if (!isa<ConstantSDNode>(Lane))
5781 SDValue Vec = Op.getOperand(0);
5782 if (Op.getValueType() == MVT::i32 &&
5783 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5785 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5791 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5792 // The only time a CONCAT_VECTORS operation can have legal types is when
5793 // two 64-bit vectors are concatenated to a 128-bit vector.
5794 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5795 "unexpected CONCAT_VECTORS");
5797 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5798 SDValue Op0 = Op.getOperand(0);
5799 SDValue Op1 = Op.getOperand(1);
5800 if (Op0.getOpcode() != ISD::UNDEF)
5801 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5802 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5803 DAG.getIntPtrConstant(0));
5804 if (Op1.getOpcode() != ISD::UNDEF)
5805 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5806 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5807 DAG.getIntPtrConstant(1));
5808 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5811 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5812 /// element has been zero/sign-extended, depending on the isSigned parameter,
5813 /// from an integer type half its size.
5814 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5816 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5817 EVT VT = N->getValueType(0);
5818 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5819 SDNode *BVN = N->getOperand(0).getNode();
5820 if (BVN->getValueType(0) != MVT::v4i32 ||
5821 BVN->getOpcode() != ISD::BUILD_VECTOR)
5823 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5824 unsigned HiElt = 1 - LoElt;
5825 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5826 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5827 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5828 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5829 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5832 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5833 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5836 if (Hi0->isNullValue() && Hi1->isNullValue())
5842 if (N->getOpcode() != ISD::BUILD_VECTOR)
5845 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5846 SDNode *Elt = N->getOperand(i).getNode();
5847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5848 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5849 unsigned HalfSize = EltSize / 2;
5851 if (!isIntN(HalfSize, C->getSExtValue()))
5854 if (!isUIntN(HalfSize, C->getZExtValue()))
5865 /// isSignExtended - Check if a node is a vector value that is sign-extended
5866 /// or a constant BUILD_VECTOR with sign-extended elements.
5867 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5868 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5870 if (isExtendedBUILD_VECTOR(N, DAG, true))
5875 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5876 /// or a constant BUILD_VECTOR with zero-extended elements.
5877 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5878 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5880 if (isExtendedBUILD_VECTOR(N, DAG, false))
5885 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5886 if (OrigVT.getSizeInBits() >= 64)
5889 assert(OrigVT.isSimple() && "Expecting a simple value type");
5891 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5892 switch (OrigSimpleTy) {
5893 default: llvm_unreachable("Unexpected Vector Type");
5902 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5903 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5904 /// We insert the required extension here to get the vector to fill a D register.
5905 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5908 unsigned ExtOpcode) {
5909 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5910 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5911 // 64-bits we need to insert a new extension so that it will be 64-bits.
5912 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5913 if (OrigTy.getSizeInBits() >= 64)
5916 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5917 EVT NewVT = getExtensionTo64Bits(OrigTy);
5919 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5922 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5923 /// does not do any sign/zero extension. If the original vector is less
5924 /// than 64 bits, an appropriate extension will be added after the load to
5925 /// reach a total size of 64 bits. We have to add the extension separately
5926 /// because ARM does not have a sign/zero extending load for vectors.
5927 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5928 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5930 // The load already has the right type.
5931 if (ExtendedTy == LD->getMemoryVT())
5932 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5933 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5934 LD->isNonTemporal(), LD->isInvariant(),
5935 LD->getAlignment());
5937 // We need to create a zextload/sextload. We cannot just create a load
5938 // followed by a zext/zext node because LowerMUL is also run during normal
5939 // operation legalization where we can't create illegal types.
5940 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5941 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5942 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5943 LD->isNonTemporal(), LD->getAlignment());
5946 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5947 /// extending load, or BUILD_VECTOR with extended elements, return the
5948 /// unextended value. The unextended vector should be 64 bits so that it can
5949 /// be used as an operand to a VMULL instruction. If the original vector size
5950 /// before extension is less than 64 bits we add a an extension to resize
5951 /// the vector to 64 bits.
5952 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5953 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5954 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5955 N->getOperand(0)->getValueType(0),
5959 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5960 return SkipLoadExtensionForVMULL(LD, DAG);
5962 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5963 // have been legalized as a BITCAST from v4i32.
5964 if (N->getOpcode() == ISD::BITCAST) {
5965 SDNode *BVN = N->getOperand(0).getNode();
5966 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5967 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5968 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5969 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5970 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5972 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5973 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5974 EVT VT = N->getValueType(0);
5975 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5976 unsigned NumElts = VT.getVectorNumElements();
5977 MVT TruncVT = MVT::getIntegerVT(EltSize);
5978 SmallVector<SDValue, 8> Ops;
5979 for (unsigned i = 0; i != NumElts; ++i) {
5980 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5981 const APInt &CInt = C->getAPIntValue();
5982 // Element types smaller than 32 bits are not legal, so use i32 elements.
5983 // The values are implicitly truncated so sext vs. zext doesn't matter.
5984 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5986 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5987 MVT::getVectorVT(TruncVT, NumElts), Ops);
5990 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5991 unsigned Opcode = N->getOpcode();
5992 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5993 SDNode *N0 = N->getOperand(0).getNode();
5994 SDNode *N1 = N->getOperand(1).getNode();
5995 return N0->hasOneUse() && N1->hasOneUse() &&
5996 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6001 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6002 unsigned Opcode = N->getOpcode();
6003 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6004 SDNode *N0 = N->getOperand(0).getNode();
6005 SDNode *N1 = N->getOperand(1).getNode();
6006 return N0->hasOneUse() && N1->hasOneUse() &&
6007 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6012 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6013 // Multiplications are only custom-lowered for 128-bit vectors so that
6014 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6015 EVT VT = Op.getValueType();
6016 assert(VT.is128BitVector() && VT.isInteger() &&
6017 "unexpected type for custom-lowering ISD::MUL");
6018 SDNode *N0 = Op.getOperand(0).getNode();
6019 SDNode *N1 = Op.getOperand(1).getNode();
6020 unsigned NewOpc = 0;
6022 bool isN0SExt = isSignExtended(N0, DAG);
6023 bool isN1SExt = isSignExtended(N1, DAG);
6024 if (isN0SExt && isN1SExt)
6025 NewOpc = ARMISD::VMULLs;
6027 bool isN0ZExt = isZeroExtended(N0, DAG);
6028 bool isN1ZExt = isZeroExtended(N1, DAG);
6029 if (isN0ZExt && isN1ZExt)
6030 NewOpc = ARMISD::VMULLu;
6031 else if (isN1SExt || isN1ZExt) {
6032 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6033 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6034 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6035 NewOpc = ARMISD::VMULLs;
6037 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6038 NewOpc = ARMISD::VMULLu;
6040 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6042 NewOpc = ARMISD::VMULLu;
6048 if (VT == MVT::v2i64)
6049 // Fall through to expand this. It is not legal.
6052 // Other vector multiplications are legal.
6057 // Legalize to a VMULL instruction.
6060 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6062 Op0 = SkipExtensionForVMULL(N0, DAG);
6063 assert(Op0.getValueType().is64BitVector() &&
6064 Op1.getValueType().is64BitVector() &&
6065 "unexpected types for extended operands to VMULL");
6066 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6069 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6070 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6077 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6078 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6079 EVT Op1VT = Op1.getValueType();
6080 return DAG.getNode(N0->getOpcode(), DL, VT,
6081 DAG.getNode(NewOpc, DL, VT,
6082 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6083 DAG.getNode(NewOpc, DL, VT,
6084 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6088 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6090 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6091 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6092 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6093 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6094 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6095 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6096 // Get reciprocal estimate.
6097 // float4 recip = vrecpeq_f32(yf);
6098 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6099 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6100 // Because char has a smaller range than uchar, we can actually get away
6101 // without any newton steps. This requires that we use a weird bias
6102 // of 0xb000, however (again, this has been exhaustively tested).
6103 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6104 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6105 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6106 Y = DAG.getConstant(0xb000, MVT::i32);
6107 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6108 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6109 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6110 // Convert back to short.
6111 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6112 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6117 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6119 // Convert to float.
6120 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6121 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6122 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6123 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6124 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6125 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6127 // Use reciprocal estimate and one refinement step.
6128 // float4 recip = vrecpeq_f32(yf);
6129 // recip *= vrecpsq_f32(yf, recip);
6130 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6131 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6132 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6133 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6135 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6136 // Because short has a smaller range than ushort, we can actually get away
6137 // with only a single newton step. This requires that we use a weird bias
6138 // of 89, however (again, this has been exhaustively tested).
6139 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6140 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6141 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6142 N1 = DAG.getConstant(0x89, MVT::i32);
6143 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6144 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6145 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6146 // Convert back to integer and return.
6147 // return vmovn_s32(vcvt_s32_f32(result));
6148 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6149 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6153 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6154 EVT VT = Op.getValueType();
6155 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6156 "unexpected type for custom-lowering ISD::SDIV");
6159 SDValue N0 = Op.getOperand(0);
6160 SDValue N1 = Op.getOperand(1);
6163 if (VT == MVT::v8i8) {
6164 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6165 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6167 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6168 DAG.getIntPtrConstant(4));
6169 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6170 DAG.getIntPtrConstant(4));
6171 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6172 DAG.getIntPtrConstant(0));
6173 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6174 DAG.getIntPtrConstant(0));
6176 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6177 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6179 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6180 N0 = LowerCONCAT_VECTORS(N0, DAG);
6182 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6185 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6188 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6189 EVT VT = Op.getValueType();
6190 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6191 "unexpected type for custom-lowering ISD::UDIV");
6194 SDValue N0 = Op.getOperand(0);
6195 SDValue N1 = Op.getOperand(1);
6198 if (VT == MVT::v8i8) {
6199 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6200 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6202 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6203 DAG.getIntPtrConstant(4));
6204 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6205 DAG.getIntPtrConstant(4));
6206 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6207 DAG.getIntPtrConstant(0));
6208 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6209 DAG.getIntPtrConstant(0));
6211 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6212 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6214 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6215 N0 = LowerCONCAT_VECTORS(N0, DAG);
6217 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6218 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6223 // v4i16 sdiv ... Convert to float.
6224 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6225 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6226 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6227 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6228 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6229 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6231 // Use reciprocal estimate and two refinement steps.
6232 // float4 recip = vrecpeq_f32(yf);
6233 // recip *= vrecpsq_f32(yf, recip);
6234 // recip *= vrecpsq_f32(yf, recip);
6235 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6236 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6237 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6238 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6240 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6241 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6242 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6244 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6245 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6246 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6247 // and that it will never cause us to return an answer too large).
6248 // float4 result = as_float4(as_int4(xf*recip) + 2);
6249 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6250 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6251 N1 = DAG.getConstant(2, MVT::i32);
6252 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6253 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6254 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6255 // Convert back to integer and return.
6256 // return vmovn_u32(vcvt_s32_f32(result));
6257 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6258 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6262 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6263 EVT VT = Op.getNode()->getValueType(0);
6264 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6267 bool ExtraOp = false;
6268 switch (Op.getOpcode()) {
6269 default: llvm_unreachable("Invalid code");
6270 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6271 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6272 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6273 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6277 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6279 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6280 Op.getOperand(1), Op.getOperand(2));
6283 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6284 assert(Subtarget->isTargetDarwin());
6286 // For iOS, we want to call an alternative entry point: __sincos_stret,
6287 // return values are passed via sret.
6289 SDValue Arg = Op.getOperand(0);
6290 EVT ArgVT = Arg.getValueType();
6291 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6293 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6294 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6296 // Pair of floats / doubles used to pass the result.
6297 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6299 // Create stack object for sret.
6300 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6301 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6302 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6303 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6309 Entry.Ty = RetTy->getPointerTo();
6310 Entry.isSExt = false;
6311 Entry.isZExt = false;
6312 Entry.isSRet = true;
6313 Args.push_back(Entry);
6317 Entry.isSExt = false;
6318 Entry.isZExt = false;
6319 Args.push_back(Entry);
6321 const char *LibcallName = (ArgVT == MVT::f64)
6322 ? "__sincos_stret" : "__sincosf_stret";
6323 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6325 TargetLowering::CallLoweringInfo CLI(DAG);
6326 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6327 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6329 .setDiscardResult();
6331 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6333 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6334 MachinePointerInfo(), false, false, false, 0);
6336 // Address of cos field.
6337 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6338 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6339 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6340 MachinePointerInfo(), false, false, false, 0);
6342 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6343 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6344 LoadSin.getValue(0), LoadCos.getValue(0));
6347 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6348 // Monotonic load/store is legal for all targets
6349 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6352 // Acquire/Release load/store is not legal for targets without a
6353 // dmb or equivalent available.
6357 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6358 SmallVectorImpl<SDValue> &Results,
6360 const ARMSubtarget *Subtarget) {
6362 SDValue Cycles32, OutChain;
6364 if (Subtarget->hasPerfMon()) {
6365 // Under Power Management extensions, the cycle-count is:
6366 // mrc p15, #0, <Rt>, c9, c13, #0
6367 SDValue Ops[] = { N->getOperand(0), // Chain
6368 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6369 DAG.getConstant(15, MVT::i32),
6370 DAG.getConstant(0, MVT::i32),
6371 DAG.getConstant(9, MVT::i32),
6372 DAG.getConstant(13, MVT::i32),
6373 DAG.getConstant(0, MVT::i32)
6376 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6377 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6378 OutChain = Cycles32.getValue(1);
6380 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6381 // there are older ARM CPUs that have implementation-specific ways of
6382 // obtaining this information (FIXME!).
6383 Cycles32 = DAG.getConstant(0, MVT::i32);
6384 OutChain = DAG.getEntryNode();
6388 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6389 Cycles32, DAG.getConstant(0, MVT::i32));
6390 Results.push_back(Cycles64);
6391 Results.push_back(OutChain);
6394 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6395 switch (Op.getOpcode()) {
6396 default: llvm_unreachable("Don't know how to custom lower this!");
6397 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6398 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6399 case ISD::GlobalAddress:
6400 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6401 default: llvm_unreachable("unknown object format");
6403 return LowerGlobalAddressWindows(Op, DAG);
6405 return LowerGlobalAddressELF(Op, DAG);
6407 return LowerGlobalAddressDarwin(Op, DAG);
6409 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6410 case ISD::SELECT: return LowerSELECT(Op, DAG);
6411 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6412 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6413 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6414 case ISD::VASTART: return LowerVASTART(Op, DAG);
6415 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6416 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6417 case ISD::SINT_TO_FP:
6418 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6419 case ISD::FP_TO_SINT:
6420 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6421 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6422 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6423 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6424 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6425 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6426 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6427 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6429 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6432 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6433 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6434 case ISD::SRL_PARTS:
6435 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6436 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6437 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6438 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6439 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6440 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6441 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6442 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6443 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6444 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6445 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6446 case ISD::MUL: return LowerMUL(Op, DAG);
6447 case ISD::SDIV: return LowerSDIV(Op, DAG);
6448 case ISD::UDIV: return LowerUDIV(Op, DAG);
6452 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6457 return LowerXALUO(Op, DAG);
6458 case ISD::ATOMIC_LOAD:
6459 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6460 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6462 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6463 case ISD::DYNAMIC_STACKALLOC:
6464 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6465 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6466 llvm_unreachable("Don't know how to custom lower this!");
6467 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6468 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6472 /// ReplaceNodeResults - Replace the results of node with an illegal result
6473 /// type with new values built out of custom code.
6474 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6475 SmallVectorImpl<SDValue>&Results,
6476 SelectionDAG &DAG) const {
6478 switch (N->getOpcode()) {
6480 llvm_unreachable("Don't know how to custom expand this!");
6482 Res = ExpandBITCAST(N, DAG);
6486 Res = Expand64BitShift(N, DAG, Subtarget);
6488 case ISD::READCYCLECOUNTER:
6489 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6493 Results.push_back(Res);
6496 //===----------------------------------------------------------------------===//
6497 // ARM Scheduler Hooks
6498 //===----------------------------------------------------------------------===//
6500 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6501 /// registers the function context.
6502 void ARMTargetLowering::
6503 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6504 MachineBasicBlock *DispatchBB, int FI) const {
6505 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6506 DebugLoc dl = MI->getDebugLoc();
6507 MachineFunction *MF = MBB->getParent();
6508 MachineRegisterInfo *MRI = &MF->getRegInfo();
6509 MachineConstantPool *MCP = MF->getConstantPool();
6510 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6511 const Function *F = MF->getFunction();
6513 bool isThumb = Subtarget->isThumb();
6514 bool isThumb2 = Subtarget->isThumb2();
6516 unsigned PCLabelId = AFI->createPICLabelUId();
6517 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6518 ARMConstantPoolValue *CPV =
6519 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6520 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6522 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6523 : &ARM::GPRRegClass;
6525 // Grab constant pool and fixed stack memory operands.
6526 MachineMemOperand *CPMMO =
6527 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6528 MachineMemOperand::MOLoad, 4, 4);
6530 MachineMemOperand *FIMMOSt =
6531 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6532 MachineMemOperand::MOStore, 4, 4);
6534 // Load the address of the dispatch MBB into the jump buffer.
6536 // Incoming value: jbuf
6537 // ldr.n r5, LCPI1_1
6540 // str r5, [$jbuf, #+4] ; &jbuf[1]
6541 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6542 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6543 .addConstantPoolIndex(CPI)
6544 .addMemOperand(CPMMO));
6545 // Set the low bit because of thumb mode.
6546 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6548 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6549 .addReg(NewVReg1, RegState::Kill)
6551 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6552 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6553 .addReg(NewVReg2, RegState::Kill)
6555 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6556 .addReg(NewVReg3, RegState::Kill)
6558 .addImm(36) // &jbuf[1] :: pc
6559 .addMemOperand(FIMMOSt));
6560 } else if (isThumb) {
6561 // Incoming value: jbuf
6562 // ldr.n r1, LCPI1_4
6566 // add r2, $jbuf, #+4 ; &jbuf[1]
6568 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6569 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6570 .addConstantPoolIndex(CPI)
6571 .addMemOperand(CPMMO));
6572 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6573 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6574 .addReg(NewVReg1, RegState::Kill)
6576 // Set the low bit because of thumb mode.
6577 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6578 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6579 .addReg(ARM::CPSR, RegState::Define)
6581 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6582 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6583 .addReg(ARM::CPSR, RegState::Define)
6584 .addReg(NewVReg2, RegState::Kill)
6585 .addReg(NewVReg3, RegState::Kill));
6586 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6587 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6589 .addImm(36); // &jbuf[1] :: pc
6590 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6591 .addReg(NewVReg4, RegState::Kill)
6592 .addReg(NewVReg5, RegState::Kill)
6594 .addMemOperand(FIMMOSt));
6596 // Incoming value: jbuf
6599 // str r1, [$jbuf, #+4] ; &jbuf[1]
6600 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6601 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6602 .addConstantPoolIndex(CPI)
6604 .addMemOperand(CPMMO));
6605 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6606 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6607 .addReg(NewVReg1, RegState::Kill)
6608 .addImm(PCLabelId));
6609 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6610 .addReg(NewVReg2, RegState::Kill)
6612 .addImm(36) // &jbuf[1] :: pc
6613 .addMemOperand(FIMMOSt));
6617 MachineBasicBlock *ARMTargetLowering::
6618 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6619 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6620 DebugLoc dl = MI->getDebugLoc();
6621 MachineFunction *MF = MBB->getParent();
6622 MachineRegisterInfo *MRI = &MF->getRegInfo();
6623 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6624 MachineFrameInfo *MFI = MF->getFrameInfo();
6625 int FI = MFI->getFunctionContextIndex();
6627 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6628 : &ARM::GPRnopcRegClass;
6630 // Get a mapping of the call site numbers to all of the landing pads they're
6632 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6633 unsigned MaxCSNum = 0;
6634 MachineModuleInfo &MMI = MF->getMMI();
6635 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6637 if (!BB->isLandingPad()) continue;
6639 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6641 for (MachineBasicBlock::iterator
6642 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6643 if (!II->isEHLabel()) continue;
6645 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6646 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6648 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6649 for (SmallVectorImpl<unsigned>::iterator
6650 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6651 CSI != CSE; ++CSI) {
6652 CallSiteNumToLPad[*CSI].push_back(BB);
6653 MaxCSNum = std::max(MaxCSNum, *CSI);
6659 // Get an ordered list of the machine basic blocks for the jump table.
6660 std::vector<MachineBasicBlock*> LPadList;
6661 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6662 LPadList.reserve(CallSiteNumToLPad.size());
6663 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6664 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6665 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6666 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6667 LPadList.push_back(*II);
6668 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6672 assert(!LPadList.empty() &&
6673 "No landing pad destinations for the dispatch jump table!");
6675 // Create the jump table and associated information.
6676 MachineJumpTableInfo *JTI =
6677 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6678 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6679 unsigned UId = AFI->createJumpTableUId();
6680 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6682 // Create the MBBs for the dispatch code.
6684 // Shove the dispatch's address into the return slot in the function context.
6685 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6686 DispatchBB->setIsLandingPad();
6688 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6689 unsigned trap_opcode;
6690 if (Subtarget->isThumb())
6691 trap_opcode = ARM::tTRAP;
6693 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6695 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6696 DispatchBB->addSuccessor(TrapBB);
6698 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6699 DispatchBB->addSuccessor(DispContBB);
6702 MF->insert(MF->end(), DispatchBB);
6703 MF->insert(MF->end(), DispContBB);
6704 MF->insert(MF->end(), TrapBB);
6706 // Insert code into the entry block that creates and registers the function
6708 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6710 MachineMemOperand *FIMMOLd =
6711 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6712 MachineMemOperand::MOLoad |
6713 MachineMemOperand::MOVolatile, 4, 4);
6715 MachineInstrBuilder MIB;
6716 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6718 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6719 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6721 // Add a register mask with no preserved registers. This results in all
6722 // registers being marked as clobbered.
6723 MIB.addRegMask(RI.getNoPreservedMask());
6725 unsigned NumLPads = LPadList.size();
6726 if (Subtarget->isThumb2()) {
6727 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6728 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6731 .addMemOperand(FIMMOLd));
6733 if (NumLPads < 256) {
6734 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6736 .addImm(LPadList.size()));
6738 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6739 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6740 .addImm(NumLPads & 0xFFFF));
6742 unsigned VReg2 = VReg1;
6743 if ((NumLPads & 0xFFFF0000) != 0) {
6744 VReg2 = MRI->createVirtualRegister(TRC);
6745 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6747 .addImm(NumLPads >> 16));
6750 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6755 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6760 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6761 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6762 .addJumpTableIndex(MJTI)
6765 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6768 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6769 .addReg(NewVReg3, RegState::Kill)
6771 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6773 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6774 .addReg(NewVReg4, RegState::Kill)
6776 .addJumpTableIndex(MJTI)
6778 } else if (Subtarget->isThumb()) {
6779 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6780 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6783 .addMemOperand(FIMMOLd));
6785 if (NumLPads < 256) {
6786 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6790 MachineConstantPool *ConstantPool = MF->getConstantPool();
6791 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6792 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6794 // MachineConstantPool wants an explicit alignment.
6795 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6797 Align = getDataLayout()->getTypeAllocSize(C->getType());
6798 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6800 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6801 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6802 .addReg(VReg1, RegState::Define)
6803 .addConstantPoolIndex(Idx));
6804 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6809 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6814 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6815 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6816 .addReg(ARM::CPSR, RegState::Define)
6820 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6821 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6822 .addJumpTableIndex(MJTI)
6825 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6826 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6827 .addReg(ARM::CPSR, RegState::Define)
6828 .addReg(NewVReg2, RegState::Kill)
6831 MachineMemOperand *JTMMOLd =
6832 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6833 MachineMemOperand::MOLoad, 4, 4);
6835 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6836 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6837 .addReg(NewVReg4, RegState::Kill)
6839 .addMemOperand(JTMMOLd));
6841 unsigned NewVReg6 = NewVReg5;
6842 if (RelocM == Reloc::PIC_) {
6843 NewVReg6 = MRI->createVirtualRegister(TRC);
6844 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6845 .addReg(ARM::CPSR, RegState::Define)
6846 .addReg(NewVReg5, RegState::Kill)
6850 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6851 .addReg(NewVReg6, RegState::Kill)
6852 .addJumpTableIndex(MJTI)
6855 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6856 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6859 .addMemOperand(FIMMOLd));
6861 if (NumLPads < 256) {
6862 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6865 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6866 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6867 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6868 .addImm(NumLPads & 0xFFFF));
6870 unsigned VReg2 = VReg1;
6871 if ((NumLPads & 0xFFFF0000) != 0) {
6872 VReg2 = MRI->createVirtualRegister(TRC);
6873 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6875 .addImm(NumLPads >> 16));
6878 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6882 MachineConstantPool *ConstantPool = MF->getConstantPool();
6883 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6884 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6886 // MachineConstantPool wants an explicit alignment.
6887 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6889 Align = getDataLayout()->getTypeAllocSize(C->getType());
6890 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6892 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6893 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6894 .addReg(VReg1, RegState::Define)
6895 .addConstantPoolIndex(Idx)
6897 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6899 .addReg(VReg1, RegState::Kill));
6902 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6907 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6909 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6911 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6912 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6913 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6914 .addJumpTableIndex(MJTI)
6917 MachineMemOperand *JTMMOLd =
6918 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6919 MachineMemOperand::MOLoad, 4, 4);
6920 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6922 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6923 .addReg(NewVReg3, RegState::Kill)
6926 .addMemOperand(JTMMOLd));
6928 if (RelocM == Reloc::PIC_) {
6929 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6930 .addReg(NewVReg5, RegState::Kill)
6932 .addJumpTableIndex(MJTI)
6935 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6936 .addReg(NewVReg5, RegState::Kill)
6937 .addJumpTableIndex(MJTI)
6942 // Add the jump table entries as successors to the MBB.
6943 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6944 for (std::vector<MachineBasicBlock*>::iterator
6945 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6946 MachineBasicBlock *CurMBB = *I;
6947 if (SeenMBBs.insert(CurMBB).second)
6948 DispContBB->addSuccessor(CurMBB);
6951 // N.B. the order the invoke BBs are processed in doesn't matter here.
6952 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6953 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6954 for (MachineBasicBlock *BB : InvokeBBs) {
6956 // Remove the landing pad successor from the invoke block and replace it
6957 // with the new dispatch block.
6958 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6960 while (!Successors.empty()) {
6961 MachineBasicBlock *SMBB = Successors.pop_back_val();
6962 if (SMBB->isLandingPad()) {
6963 BB->removeSuccessor(SMBB);
6964 MBBLPads.push_back(SMBB);
6968 BB->addSuccessor(DispatchBB);
6970 // Find the invoke call and mark all of the callee-saved registers as
6971 // 'implicit defined' so that they're spilled. This prevents code from
6972 // moving instructions to before the EH block, where they will never be
6974 for (MachineBasicBlock::reverse_iterator
6975 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6976 if (!II->isCall()) continue;
6978 DenseMap<unsigned, bool> DefRegs;
6979 for (MachineInstr::mop_iterator
6980 OI = II->operands_begin(), OE = II->operands_end();
6982 if (!OI->isReg()) continue;
6983 DefRegs[OI->getReg()] = true;
6986 MachineInstrBuilder MIB(*MF, &*II);
6988 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6989 unsigned Reg = SavedRegs[i];
6990 if (Subtarget->isThumb2() &&
6991 !ARM::tGPRRegClass.contains(Reg) &&
6992 !ARM::hGPRRegClass.contains(Reg))
6994 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6996 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6999 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7006 // Mark all former landing pads as non-landing pads. The dispatch is the only
7008 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7009 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7010 (*I)->setIsLandingPad(false);
7012 // The instruction is gone now.
7013 MI->eraseFromParent();
7019 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7020 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7021 E = MBB->succ_end(); I != E; ++I)
7024 llvm_unreachable("Expecting a BB with two successors!");
7027 /// Return the load opcode for a given load size. If load size >= 8,
7028 /// neon opcode will be returned.
7029 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7031 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7032 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7034 return LdSize == 4 ? ARM::tLDRi
7035 : LdSize == 2 ? ARM::tLDRHi
7036 : LdSize == 1 ? ARM::tLDRBi : 0;
7038 return LdSize == 4 ? ARM::t2LDR_POST
7039 : LdSize == 2 ? ARM::t2LDRH_POST
7040 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7041 return LdSize == 4 ? ARM::LDR_POST_IMM
7042 : LdSize == 2 ? ARM::LDRH_POST
7043 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7046 /// Return the store opcode for a given store size. If store size >= 8,
7047 /// neon opcode will be returned.
7048 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7050 return StSize == 16 ? ARM::VST1q32wb_fixed
7051 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7053 return StSize == 4 ? ARM::tSTRi
7054 : StSize == 2 ? ARM::tSTRHi
7055 : StSize == 1 ? ARM::tSTRBi : 0;
7057 return StSize == 4 ? ARM::t2STR_POST
7058 : StSize == 2 ? ARM::t2STRH_POST
7059 : StSize == 1 ? ARM::t2STRB_POST : 0;
7060 return StSize == 4 ? ARM::STR_POST_IMM
7061 : StSize == 2 ? ARM::STRH_POST
7062 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7065 /// Emit a post-increment load operation with given size. The instructions
7066 /// will be added to BB at Pos.
7067 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7068 const TargetInstrInfo *TII, DebugLoc dl,
7069 unsigned LdSize, unsigned Data, unsigned AddrIn,
7070 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7071 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7072 assert(LdOpc != 0 && "Should have a load opcode");
7074 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7075 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7077 } else if (IsThumb1) {
7078 // load + update AddrIn
7079 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7080 .addReg(AddrIn).addImm(0));
7081 MachineInstrBuilder MIB =
7082 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7083 MIB = AddDefaultT1CC(MIB);
7084 MIB.addReg(AddrIn).addImm(LdSize);
7085 AddDefaultPred(MIB);
7086 } else if (IsThumb2) {
7087 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7088 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7091 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7092 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7093 .addReg(0).addImm(LdSize));
7097 /// Emit a post-increment store operation with given size. The instructions
7098 /// will be added to BB at Pos.
7099 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7100 const TargetInstrInfo *TII, DebugLoc dl,
7101 unsigned StSize, unsigned Data, unsigned AddrIn,
7102 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7103 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7104 assert(StOpc != 0 && "Should have a store opcode");
7106 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7107 .addReg(AddrIn).addImm(0).addReg(Data));
7108 } else if (IsThumb1) {
7109 // store + update AddrIn
7110 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7111 .addReg(AddrIn).addImm(0));
7112 MachineInstrBuilder MIB =
7113 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7114 MIB = AddDefaultT1CC(MIB);
7115 MIB.addReg(AddrIn).addImm(StSize);
7116 AddDefaultPred(MIB);
7117 } else if (IsThumb2) {
7118 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7119 .addReg(Data).addReg(AddrIn).addImm(StSize));
7121 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7122 .addReg(Data).addReg(AddrIn).addReg(0)
7128 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7129 MachineBasicBlock *BB) const {
7130 // This pseudo instruction has 3 operands: dst, src, size
7131 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7132 // Otherwise, we will generate unrolled scalar copies.
7133 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7134 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7135 MachineFunction::iterator It = BB;
7138 unsigned dest = MI->getOperand(0).getReg();
7139 unsigned src = MI->getOperand(1).getReg();
7140 unsigned SizeVal = MI->getOperand(2).getImm();
7141 unsigned Align = MI->getOperand(3).getImm();
7142 DebugLoc dl = MI->getDebugLoc();
7144 MachineFunction *MF = BB->getParent();
7145 MachineRegisterInfo &MRI = MF->getRegInfo();
7146 unsigned UnitSize = 0;
7147 const TargetRegisterClass *TRC = nullptr;
7148 const TargetRegisterClass *VecTRC = nullptr;
7150 bool IsThumb1 = Subtarget->isThumb1Only();
7151 bool IsThumb2 = Subtarget->isThumb2();
7155 } else if (Align & 2) {
7158 // Check whether we can use NEON instructions.
7159 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7160 Subtarget->hasNEON()) {
7161 if ((Align % 16 == 0) && SizeVal >= 16)
7163 else if ((Align % 8 == 0) && SizeVal >= 8)
7166 // Can't use NEON instructions.
7171 // Select the correct opcode and register class for unit size load/store
7172 bool IsNeon = UnitSize >= 8;
7173 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7175 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7176 : UnitSize == 8 ? &ARM::DPRRegClass
7179 unsigned BytesLeft = SizeVal % UnitSize;
7180 unsigned LoopSize = SizeVal - BytesLeft;
7182 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7183 // Use LDR and STR to copy.
7184 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7185 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7186 unsigned srcIn = src;
7187 unsigned destIn = dest;
7188 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7189 unsigned srcOut = MRI.createVirtualRegister(TRC);
7190 unsigned destOut = MRI.createVirtualRegister(TRC);
7191 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7192 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7193 IsThumb1, IsThumb2);
7194 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7195 IsThumb1, IsThumb2);
7200 // Handle the leftover bytes with LDRB and STRB.
7201 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7202 // [destOut] = STRB_POST(scratch, destIn, 1)
7203 for (unsigned i = 0; i < BytesLeft; i++) {
7204 unsigned srcOut = MRI.createVirtualRegister(TRC);
7205 unsigned destOut = MRI.createVirtualRegister(TRC);
7206 unsigned scratch = MRI.createVirtualRegister(TRC);
7207 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7208 IsThumb1, IsThumb2);
7209 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7210 IsThumb1, IsThumb2);
7214 MI->eraseFromParent(); // The instruction is gone now.
7218 // Expand the pseudo op to a loop.
7221 // movw varEnd, # --> with thumb2
7223 // ldrcp varEnd, idx --> without thumb2
7224 // fallthrough --> loopMBB
7226 // PHI varPhi, varEnd, varLoop
7227 // PHI srcPhi, src, srcLoop
7228 // PHI destPhi, dst, destLoop
7229 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7230 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7231 // subs varLoop, varPhi, #UnitSize
7233 // fallthrough --> exitMBB
7235 // epilogue to handle left-over bytes
7236 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7237 // [destOut] = STRB_POST(scratch, destLoop, 1)
7238 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7239 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7240 MF->insert(It, loopMBB);
7241 MF->insert(It, exitMBB);
7243 // Transfer the remainder of BB and its successor edges to exitMBB.
7244 exitMBB->splice(exitMBB->begin(), BB,
7245 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7246 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7248 // Load an immediate to varEnd.
7249 unsigned varEnd = MRI.createVirtualRegister(TRC);
7251 unsigned Vtmp = varEnd;
7252 if ((LoopSize & 0xFFFF0000) != 0)
7253 Vtmp = MRI.createVirtualRegister(TRC);
7254 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7255 .addImm(LoopSize & 0xFFFF));
7257 if ((LoopSize & 0xFFFF0000) != 0)
7258 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7259 .addReg(Vtmp).addImm(LoopSize >> 16));
7261 MachineConstantPool *ConstantPool = MF->getConstantPool();
7262 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7263 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7265 // MachineConstantPool wants an explicit alignment.
7266 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7268 Align = getDataLayout()->getTypeAllocSize(C->getType());
7269 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7272 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7273 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7275 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7276 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7278 BB->addSuccessor(loopMBB);
7280 // Generate the loop body:
7281 // varPhi = PHI(varLoop, varEnd)
7282 // srcPhi = PHI(srcLoop, src)
7283 // destPhi = PHI(destLoop, dst)
7284 MachineBasicBlock *entryBB = BB;
7286 unsigned varLoop = MRI.createVirtualRegister(TRC);
7287 unsigned varPhi = MRI.createVirtualRegister(TRC);
7288 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7289 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7290 unsigned destLoop = MRI.createVirtualRegister(TRC);
7291 unsigned destPhi = MRI.createVirtualRegister(TRC);
7293 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7294 .addReg(varLoop).addMBB(loopMBB)
7295 .addReg(varEnd).addMBB(entryBB);
7296 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7297 .addReg(srcLoop).addMBB(loopMBB)
7298 .addReg(src).addMBB(entryBB);
7299 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7300 .addReg(destLoop).addMBB(loopMBB)
7301 .addReg(dest).addMBB(entryBB);
7303 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7304 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7305 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7306 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7307 IsThumb1, IsThumb2);
7308 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7309 IsThumb1, IsThumb2);
7311 // Decrement loop variable by UnitSize.
7313 MachineInstrBuilder MIB =
7314 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7315 MIB = AddDefaultT1CC(MIB);
7316 MIB.addReg(varPhi).addImm(UnitSize);
7317 AddDefaultPred(MIB);
7319 MachineInstrBuilder MIB =
7320 BuildMI(*BB, BB->end(), dl,
7321 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7322 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7323 MIB->getOperand(5).setReg(ARM::CPSR);
7324 MIB->getOperand(5).setIsDef(true);
7326 BuildMI(*BB, BB->end(), dl,
7327 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7328 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7330 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7331 BB->addSuccessor(loopMBB);
7332 BB->addSuccessor(exitMBB);
7334 // Add epilogue to handle BytesLeft.
7336 MachineInstr *StartOfExit = exitMBB->begin();
7338 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7339 // [destOut] = STRB_POST(scratch, destLoop, 1)
7340 unsigned srcIn = srcLoop;
7341 unsigned destIn = destLoop;
7342 for (unsigned i = 0; i < BytesLeft; i++) {
7343 unsigned srcOut = MRI.createVirtualRegister(TRC);
7344 unsigned destOut = MRI.createVirtualRegister(TRC);
7345 unsigned scratch = MRI.createVirtualRegister(TRC);
7346 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7347 IsThumb1, IsThumb2);
7348 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7349 IsThumb1, IsThumb2);
7354 MI->eraseFromParent(); // The instruction is gone now.
7359 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7360 MachineBasicBlock *MBB) const {
7361 const TargetMachine &TM = getTargetMachine();
7362 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7363 DebugLoc DL = MI->getDebugLoc();
7365 assert(Subtarget->isTargetWindows() &&
7366 "__chkstk is only supported on Windows");
7367 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7369 // __chkstk takes the number of words to allocate on the stack in R4, and
7370 // returns the stack adjustment in number of bytes in R4. This will not
7371 // clober any other registers (other than the obvious lr).
7373 // Although, technically, IP should be considered a register which may be
7374 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7375 // thumb-2 environment, so there is no interworking required. As a result, we
7376 // do not expect a veneer to be emitted by the linker, clobbering IP.
7378 // Each module receives its own copy of __chkstk, so no import thunk is
7379 // required, again, ensuring that IP is not clobbered.
7381 // Finally, although some linkers may theoretically provide a trampoline for
7382 // out of range calls (which is quite common due to a 32M range limitation of
7383 // branches for Thumb), we can generate the long-call version via
7384 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7387 switch (TM.getCodeModel()) {
7388 case CodeModel::Small:
7389 case CodeModel::Medium:
7390 case CodeModel::Default:
7391 case CodeModel::Kernel:
7392 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7393 .addImm((unsigned)ARMCC::AL).addReg(0)
7394 .addExternalSymbol("__chkstk")
7395 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7396 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7397 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7399 case CodeModel::Large:
7400 case CodeModel::JITDefault: {
7401 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7402 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7404 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7405 .addExternalSymbol("__chkstk");
7406 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7407 .addImm((unsigned)ARMCC::AL).addReg(0)
7408 .addReg(Reg, RegState::Kill)
7409 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7410 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7411 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7416 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7418 .addReg(ARM::SP).addReg(ARM::R4)));
7420 MI->eraseFromParent();
7425 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7426 MachineBasicBlock *BB) const {
7427 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7428 DebugLoc dl = MI->getDebugLoc();
7429 bool isThumb2 = Subtarget->isThumb2();
7430 switch (MI->getOpcode()) {
7433 llvm_unreachable("Unexpected instr type to insert");
7435 // The Thumb2 pre-indexed stores have the same MI operands, they just
7436 // define them differently in the .td files from the isel patterns, so
7437 // they need pseudos.
7438 case ARM::t2STR_preidx:
7439 MI->setDesc(TII->get(ARM::t2STR_PRE));
7441 case ARM::t2STRB_preidx:
7442 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7444 case ARM::t2STRH_preidx:
7445 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7448 case ARM::STRi_preidx:
7449 case ARM::STRBi_preidx: {
7450 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7451 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7452 // Decode the offset.
7453 unsigned Offset = MI->getOperand(4).getImm();
7454 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7455 Offset = ARM_AM::getAM2Offset(Offset);
7459 MachineMemOperand *MMO = *MI->memoperands_begin();
7460 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7461 .addOperand(MI->getOperand(0)) // Rn_wb
7462 .addOperand(MI->getOperand(1)) // Rt
7463 .addOperand(MI->getOperand(2)) // Rn
7464 .addImm(Offset) // offset (skip GPR==zero_reg)
7465 .addOperand(MI->getOperand(5)) // pred
7466 .addOperand(MI->getOperand(6))
7467 .addMemOperand(MMO);
7468 MI->eraseFromParent();
7471 case ARM::STRr_preidx:
7472 case ARM::STRBr_preidx:
7473 case ARM::STRH_preidx: {
7475 switch (MI->getOpcode()) {
7476 default: llvm_unreachable("unexpected opcode!");
7477 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7478 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7479 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7481 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7482 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7483 MIB.addOperand(MI->getOperand(i));
7484 MI->eraseFromParent();
7488 case ARM::tMOVCCr_pseudo: {
7489 // To "insert" a SELECT_CC instruction, we actually have to insert the
7490 // diamond control-flow pattern. The incoming instruction knows the
7491 // destination vreg to set, the condition code register to branch on, the
7492 // true/false values to select between, and a branch opcode to use.
7493 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7494 MachineFunction::iterator It = BB;
7500 // cmpTY ccX, r1, r2
7502 // fallthrough --> copy0MBB
7503 MachineBasicBlock *thisMBB = BB;
7504 MachineFunction *F = BB->getParent();
7505 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7506 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7507 F->insert(It, copy0MBB);
7508 F->insert(It, sinkMBB);
7510 // Transfer the remainder of BB and its successor edges to sinkMBB.
7511 sinkMBB->splice(sinkMBB->begin(), BB,
7512 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7513 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7515 BB->addSuccessor(copy0MBB);
7516 BB->addSuccessor(sinkMBB);
7518 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7519 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7522 // %FalseValue = ...
7523 // # fallthrough to sinkMBB
7526 // Update machine-CFG edges
7527 BB->addSuccessor(sinkMBB);
7530 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7533 BuildMI(*BB, BB->begin(), dl,
7534 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7535 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7536 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7538 MI->eraseFromParent(); // The pseudo instruction is gone now.
7543 case ARM::BCCZi64: {
7544 // If there is an unconditional branch to the other successor, remove it.
7545 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7547 // Compare both parts that make up the double comparison separately for
7549 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7551 unsigned LHS1 = MI->getOperand(1).getReg();
7552 unsigned LHS2 = MI->getOperand(2).getReg();
7554 AddDefaultPred(BuildMI(BB, dl,
7555 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7556 .addReg(LHS1).addImm(0));
7557 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7558 .addReg(LHS2).addImm(0)
7559 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7561 unsigned RHS1 = MI->getOperand(3).getReg();
7562 unsigned RHS2 = MI->getOperand(4).getReg();
7563 AddDefaultPred(BuildMI(BB, dl,
7564 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7565 .addReg(LHS1).addReg(RHS1));
7566 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7567 .addReg(LHS2).addReg(RHS2)
7568 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7571 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7572 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7573 if (MI->getOperand(0).getImm() == ARMCC::NE)
7574 std::swap(destMBB, exitMBB);
7576 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7577 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7579 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7581 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7583 MI->eraseFromParent(); // The pseudo instruction is gone now.
7587 case ARM::Int_eh_sjlj_setjmp:
7588 case ARM::Int_eh_sjlj_setjmp_nofp:
7589 case ARM::tInt_eh_sjlj_setjmp:
7590 case ARM::t2Int_eh_sjlj_setjmp:
7591 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7592 EmitSjLjDispatchBlock(MI, BB);
7597 // To insert an ABS instruction, we have to insert the
7598 // diamond control-flow pattern. The incoming instruction knows the
7599 // source vreg to test against 0, the destination vreg to set,
7600 // the condition code register to branch on, the
7601 // true/false values to select between, and a branch opcode to use.
7606 // BCC (branch to SinkBB if V0 >= 0)
7607 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7608 // SinkBB: V1 = PHI(V2, V3)
7609 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7610 MachineFunction::iterator BBI = BB;
7612 MachineFunction *Fn = BB->getParent();
7613 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7614 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7615 Fn->insert(BBI, RSBBB);
7616 Fn->insert(BBI, SinkBB);
7618 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7619 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7620 bool isThumb2 = Subtarget->isThumb2();
7621 MachineRegisterInfo &MRI = Fn->getRegInfo();
7622 // In Thumb mode S must not be specified if source register is the SP or
7623 // PC and if destination register is the SP, so restrict register class
7624 unsigned NewRsbDstReg =
7625 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7627 // Transfer the remainder of BB and its successor edges to sinkMBB.
7628 SinkBB->splice(SinkBB->begin(), BB,
7629 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7630 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7632 BB->addSuccessor(RSBBB);
7633 BB->addSuccessor(SinkBB);
7635 // fall through to SinkMBB
7636 RSBBB->addSuccessor(SinkBB);
7638 // insert a cmp at the end of BB
7639 AddDefaultPred(BuildMI(BB, dl,
7640 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7641 .addReg(ABSSrcReg).addImm(0));
7643 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7645 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7646 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7648 // insert rsbri in RSBBB
7649 // Note: BCC and rsbri will be converted into predicated rsbmi
7650 // by if-conversion pass
7651 BuildMI(*RSBBB, RSBBB->begin(), dl,
7652 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7653 .addReg(ABSSrcReg, RegState::Kill)
7654 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7656 // insert PHI in SinkBB,
7657 // reuse ABSDstReg to not change uses of ABS instruction
7658 BuildMI(*SinkBB, SinkBB->begin(), dl,
7659 TII->get(ARM::PHI), ABSDstReg)
7660 .addReg(NewRsbDstReg).addMBB(RSBBB)
7661 .addReg(ABSSrcReg).addMBB(BB);
7663 // remove ABS instruction
7664 MI->eraseFromParent();
7666 // return last added BB
7669 case ARM::COPY_STRUCT_BYVAL_I32:
7671 return EmitStructByval(MI, BB);
7672 case ARM::WIN__CHKSTK:
7673 return EmitLowered__chkstk(MI, BB);
7677 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7678 SDNode *Node) const {
7679 const MCInstrDesc *MCID = &MI->getDesc();
7680 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7681 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7682 // operand is still set to noreg. If needed, set the optional operand's
7683 // register to CPSR, and remove the redundant implicit def.
7685 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7687 // Rename pseudo opcodes.
7688 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7690 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7691 MCID = &TII->get(NewOpc);
7693 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7694 "converted opcode should be the same except for cc_out");
7698 // Add the optional cc_out operand
7699 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7701 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7703 // Any ARM instruction that sets the 's' bit should specify an optional
7704 // "cc_out" operand in the last operand position.
7705 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7706 assert(!NewOpc && "Optional cc_out operand required");
7709 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7710 // since we already have an optional CPSR def.
7711 bool definesCPSR = false;
7712 bool deadCPSR = false;
7713 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7715 const MachineOperand &MO = MI->getOperand(i);
7716 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7720 MI->RemoveOperand(i);
7725 assert(!NewOpc && "Optional cc_out operand required");
7728 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7730 assert(!MI->getOperand(ccOutIdx).getReg() &&
7731 "expect uninitialized optional cc_out operand");
7735 // If this instruction was defined with an optional CPSR def and its dag node
7736 // had a live implicit CPSR def, then activate the optional CPSR def.
7737 MachineOperand &MO = MI->getOperand(ccOutIdx);
7738 MO.setReg(ARM::CPSR);
7742 //===----------------------------------------------------------------------===//
7743 // ARM Optimization Hooks
7744 //===----------------------------------------------------------------------===//
7746 // Helper function that checks if N is a null or all ones constant.
7747 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7751 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7754 // Return true if N is conditionally 0 or all ones.
7755 // Detects these expressions where cc is an i1 value:
7757 // (select cc 0, y) [AllOnes=0]
7758 // (select cc y, 0) [AllOnes=0]
7759 // (zext cc) [AllOnes=0]
7760 // (sext cc) [AllOnes=0/1]
7761 // (select cc -1, y) [AllOnes=1]
7762 // (select cc y, -1) [AllOnes=1]
7764 // Invert is set when N is the null/all ones constant when CC is false.
7765 // OtherOp is set to the alternative value of N.
7766 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7767 SDValue &CC, bool &Invert,
7769 SelectionDAG &DAG) {
7770 switch (N->getOpcode()) {
7771 default: return false;
7773 CC = N->getOperand(0);
7774 SDValue N1 = N->getOperand(1);
7775 SDValue N2 = N->getOperand(2);
7776 if (isZeroOrAllOnes(N1, AllOnes)) {
7781 if (isZeroOrAllOnes(N2, AllOnes)) {
7788 case ISD::ZERO_EXTEND:
7789 // (zext cc) can never be the all ones value.
7793 case ISD::SIGN_EXTEND: {
7794 EVT VT = N->getValueType(0);
7795 CC = N->getOperand(0);
7796 if (CC.getValueType() != MVT::i1)
7800 // When looking for an AllOnes constant, N is an sext, and the 'other'
7802 OtherOp = DAG.getConstant(0, VT);
7803 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7804 // When looking for a 0 constant, N can be zext or sext.
7805 OtherOp = DAG.getConstant(1, VT);
7807 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7813 // Combine a constant select operand into its use:
7815 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7816 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7817 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7818 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7819 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7821 // The transform is rejected if the select doesn't have a constant operand that
7822 // is null, or all ones when AllOnes is set.
7824 // Also recognize sext/zext from i1:
7826 // (add (zext cc), x) -> (select cc (add x, 1), x)
7827 // (add (sext cc), x) -> (select cc (add x, -1), x)
7829 // These transformations eventually create predicated instructions.
7831 // @param N The node to transform.
7832 // @param Slct The N operand that is a select.
7833 // @param OtherOp The other N operand (x above).
7834 // @param DCI Context.
7835 // @param AllOnes Require the select constant to be all ones instead of null.
7836 // @returns The new node, or SDValue() on failure.
7838 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7839 TargetLowering::DAGCombinerInfo &DCI,
7840 bool AllOnes = false) {
7841 SelectionDAG &DAG = DCI.DAG;
7842 EVT VT = N->getValueType(0);
7843 SDValue NonConstantVal;
7846 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7847 NonConstantVal, DAG))
7850 // Slct is now know to be the desired identity constant when CC is true.
7851 SDValue TrueVal = OtherOp;
7852 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7853 OtherOp, NonConstantVal);
7854 // Unless SwapSelectOps says CC should be false.
7856 std::swap(TrueVal, FalseVal);
7858 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7859 CCOp, TrueVal, FalseVal);
7862 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7864 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7865 TargetLowering::DAGCombinerInfo &DCI) {
7866 SDValue N0 = N->getOperand(0);
7867 SDValue N1 = N->getOperand(1);
7868 if (N0.getNode()->hasOneUse()) {
7869 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7870 if (Result.getNode())
7873 if (N1.getNode()->hasOneUse()) {
7874 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7875 if (Result.getNode())
7881 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7882 // (only after legalization).
7883 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7884 TargetLowering::DAGCombinerInfo &DCI,
7885 const ARMSubtarget *Subtarget) {
7887 // Only perform optimization if after legalize, and if NEON is available. We
7888 // also expected both operands to be BUILD_VECTORs.
7889 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7890 || N0.getOpcode() != ISD::BUILD_VECTOR
7891 || N1.getOpcode() != ISD::BUILD_VECTOR)
7894 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7895 EVT VT = N->getValueType(0);
7896 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7899 // Check that the vector operands are of the right form.
7900 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7901 // operands, where N is the size of the formed vector.
7902 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7903 // index such that we have a pair wise add pattern.
7905 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7906 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7908 SDValue Vec = N0->getOperand(0)->getOperand(0);
7909 SDNode *V = Vec.getNode();
7910 unsigned nextIndex = 0;
7912 // For each operands to the ADD which are BUILD_VECTORs,
7913 // check to see if each of their operands are an EXTRACT_VECTOR with
7914 // the same vector and appropriate index.
7915 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7916 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7917 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7919 SDValue ExtVec0 = N0->getOperand(i);
7920 SDValue ExtVec1 = N1->getOperand(i);
7922 // First operand is the vector, verify its the same.
7923 if (V != ExtVec0->getOperand(0).getNode() ||
7924 V != ExtVec1->getOperand(0).getNode())
7927 // Second is the constant, verify its correct.
7928 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7929 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7931 // For the constant, we want to see all the even or all the odd.
7932 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7933 || C1->getZExtValue() != nextIndex+1)
7942 // Create VPADDL node.
7943 SelectionDAG &DAG = DCI.DAG;
7944 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7946 // Build operand list.
7947 SmallVector<SDValue, 8> Ops;
7948 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7949 TLI.getPointerTy()));
7951 // Input is the vector.
7954 // Get widened type and narrowed type.
7956 unsigned numElem = VT.getVectorNumElements();
7958 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7959 switch (inputLaneType.getSimpleVT().SimpleTy) {
7960 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7961 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7962 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7964 llvm_unreachable("Invalid vector element type for padd optimization.");
7967 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7968 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7969 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7972 static SDValue findMUL_LOHI(SDValue V) {
7973 if (V->getOpcode() == ISD::UMUL_LOHI ||
7974 V->getOpcode() == ISD::SMUL_LOHI)
7979 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7980 TargetLowering::DAGCombinerInfo &DCI,
7981 const ARMSubtarget *Subtarget) {
7983 if (Subtarget->isThumb1Only()) return SDValue();
7985 // Only perform the checks after legalize when the pattern is available.
7986 if (DCI.isBeforeLegalize()) return SDValue();
7988 // Look for multiply add opportunities.
7989 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7990 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7991 // a glue link from the first add to the second add.
7992 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7993 // a S/UMLAL instruction.
7996 // \ / \ [no multiline comment]
8002 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8003 SDValue AddcOp0 = AddcNode->getOperand(0);
8004 SDValue AddcOp1 = AddcNode->getOperand(1);
8006 // Check if the two operands are from the same mul_lohi node.
8007 if (AddcOp0.getNode() == AddcOp1.getNode())
8010 assert(AddcNode->getNumValues() == 2 &&
8011 AddcNode->getValueType(0) == MVT::i32 &&
8012 "Expect ADDC with two result values. First: i32");
8014 // Check that we have a glued ADDC node.
8015 if (AddcNode->getValueType(1) != MVT::Glue)
8018 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8019 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8020 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8021 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8022 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8025 // Look for the glued ADDE.
8026 SDNode* AddeNode = AddcNode->getGluedUser();
8030 // Make sure it is really an ADDE.
8031 if (AddeNode->getOpcode() != ISD::ADDE)
8034 assert(AddeNode->getNumOperands() == 3 &&
8035 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8036 "ADDE node has the wrong inputs");
8038 // Check for the triangle shape.
8039 SDValue AddeOp0 = AddeNode->getOperand(0);
8040 SDValue AddeOp1 = AddeNode->getOperand(1);
8042 // Make sure that the ADDE operands are not coming from the same node.
8043 if (AddeOp0.getNode() == AddeOp1.getNode())
8046 // Find the MUL_LOHI node walking up ADDE's operands.
8047 bool IsLeftOperandMUL = false;
8048 SDValue MULOp = findMUL_LOHI(AddeOp0);
8049 if (MULOp == SDValue())
8050 MULOp = findMUL_LOHI(AddeOp1);
8052 IsLeftOperandMUL = true;
8053 if (MULOp == SDValue())
8056 // Figure out the right opcode.
8057 unsigned Opc = MULOp->getOpcode();
8058 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8060 // Figure out the high and low input values to the MLAL node.
8061 SDValue* HiAdd = nullptr;
8062 SDValue* LoMul = nullptr;
8063 SDValue* LowAdd = nullptr;
8065 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8066 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8069 if (IsLeftOperandMUL)
8075 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8076 // whose low result is fed to the ADDC we are checking.
8078 if (AddcOp0 == MULOp.getValue(0)) {
8082 if (AddcOp1 == MULOp.getValue(0)) {
8090 // Create the merged node.
8091 SelectionDAG &DAG = DCI.DAG;
8093 // Build operand list.
8094 SmallVector<SDValue, 8> Ops;
8095 Ops.push_back(LoMul->getOperand(0));
8096 Ops.push_back(LoMul->getOperand(1));
8097 Ops.push_back(*LowAdd);
8098 Ops.push_back(*HiAdd);
8100 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8101 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8103 // Replace the ADDs' nodes uses by the MLA node's values.
8104 SDValue HiMLALResult(MLALNode.getNode(), 1);
8105 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8107 SDValue LoMLALResult(MLALNode.getNode(), 0);
8108 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8110 // Return original node to notify the driver to stop replacing.
8111 SDValue resNode(AddcNode, 0);
8115 /// PerformADDCCombine - Target-specific dag combine transform from
8116 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8117 static SDValue PerformADDCCombine(SDNode *N,
8118 TargetLowering::DAGCombinerInfo &DCI,
8119 const ARMSubtarget *Subtarget) {
8121 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8125 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8126 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8127 /// called with the default operands, and if that fails, with commuted
8129 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8130 TargetLowering::DAGCombinerInfo &DCI,
8131 const ARMSubtarget *Subtarget){
8133 // Attempt to create vpaddl for this add.
8134 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8135 if (Result.getNode())
8138 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8139 if (N0.getNode()->hasOneUse()) {
8140 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8141 if (Result.getNode()) return Result;
8146 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8148 static SDValue PerformADDCombine(SDNode *N,
8149 TargetLowering::DAGCombinerInfo &DCI,
8150 const ARMSubtarget *Subtarget) {
8151 SDValue N0 = N->getOperand(0);
8152 SDValue N1 = N->getOperand(1);
8154 // First try with the default operand order.
8155 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8156 if (Result.getNode())
8159 // If that didn't work, try again with the operands commuted.
8160 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8163 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8165 static SDValue PerformSUBCombine(SDNode *N,
8166 TargetLowering::DAGCombinerInfo &DCI) {
8167 SDValue N0 = N->getOperand(0);
8168 SDValue N1 = N->getOperand(1);
8170 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8171 if (N1.getNode()->hasOneUse()) {
8172 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8173 if (Result.getNode()) return Result;
8179 /// PerformVMULCombine
8180 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8181 /// special multiplier accumulator forwarding.
8187 // However, for (A + B) * (A + B),
8194 static SDValue PerformVMULCombine(SDNode *N,
8195 TargetLowering::DAGCombinerInfo &DCI,
8196 const ARMSubtarget *Subtarget) {
8197 if (!Subtarget->hasVMLxForwarding())
8200 SelectionDAG &DAG = DCI.DAG;
8201 SDValue N0 = N->getOperand(0);
8202 SDValue N1 = N->getOperand(1);
8203 unsigned Opcode = N0.getOpcode();
8204 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8205 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8206 Opcode = N1.getOpcode();
8207 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8208 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8216 EVT VT = N->getValueType(0);
8218 SDValue N00 = N0->getOperand(0);
8219 SDValue N01 = N0->getOperand(1);
8220 return DAG.getNode(Opcode, DL, VT,
8221 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8222 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8225 static SDValue PerformMULCombine(SDNode *N,
8226 TargetLowering::DAGCombinerInfo &DCI,
8227 const ARMSubtarget *Subtarget) {
8228 SelectionDAG &DAG = DCI.DAG;
8230 if (Subtarget->isThumb1Only())
8233 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8236 EVT VT = N->getValueType(0);
8237 if (VT.is64BitVector() || VT.is128BitVector())
8238 return PerformVMULCombine(N, DCI, Subtarget);
8242 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8246 int64_t MulAmt = C->getSExtValue();
8247 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8249 ShiftAmt = ShiftAmt & (32 - 1);
8250 SDValue V = N->getOperand(0);
8254 MulAmt >>= ShiftAmt;
8257 if (isPowerOf2_32(MulAmt - 1)) {
8258 // (mul x, 2^N + 1) => (add (shl x, N), x)
8259 Res = DAG.getNode(ISD::ADD, DL, VT,
8261 DAG.getNode(ISD::SHL, DL, VT,
8263 DAG.getConstant(Log2_32(MulAmt - 1),
8265 } else if (isPowerOf2_32(MulAmt + 1)) {
8266 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8267 Res = DAG.getNode(ISD::SUB, DL, VT,
8268 DAG.getNode(ISD::SHL, DL, VT,
8270 DAG.getConstant(Log2_32(MulAmt + 1),
8276 uint64_t MulAmtAbs = -MulAmt;
8277 if (isPowerOf2_32(MulAmtAbs + 1)) {
8278 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8279 Res = DAG.getNode(ISD::SUB, DL, VT,
8281 DAG.getNode(ISD::SHL, DL, VT,
8283 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8285 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8286 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8287 Res = DAG.getNode(ISD::ADD, DL, VT,
8289 DAG.getNode(ISD::SHL, DL, VT,
8291 DAG.getConstant(Log2_32(MulAmtAbs-1),
8293 Res = DAG.getNode(ISD::SUB, DL, VT,
8294 DAG.getConstant(0, MVT::i32),Res);
8301 Res = DAG.getNode(ISD::SHL, DL, VT,
8302 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8304 // Do not add new nodes to DAG combiner worklist.
8305 DCI.CombineTo(N, Res, false);
8309 static SDValue PerformANDCombine(SDNode *N,
8310 TargetLowering::DAGCombinerInfo &DCI,
8311 const ARMSubtarget *Subtarget) {
8313 // Attempt to use immediate-form VBIC
8314 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8316 EVT VT = N->getValueType(0);
8317 SelectionDAG &DAG = DCI.DAG;
8319 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8322 APInt SplatBits, SplatUndef;
8323 unsigned SplatBitSize;
8326 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8327 if (SplatBitSize <= 64) {
8329 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8330 SplatUndef.getZExtValue(), SplatBitSize,
8331 DAG, VbicVT, VT.is128BitVector(),
8333 if (Val.getNode()) {
8335 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8336 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8337 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8342 if (!Subtarget->isThumb1Only()) {
8343 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8344 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8345 if (Result.getNode())
8352 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8353 static SDValue PerformORCombine(SDNode *N,
8354 TargetLowering::DAGCombinerInfo &DCI,
8355 const ARMSubtarget *Subtarget) {
8356 // Attempt to use immediate-form VORR
8357 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8359 EVT VT = N->getValueType(0);
8360 SelectionDAG &DAG = DCI.DAG;
8362 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8365 APInt SplatBits, SplatUndef;
8366 unsigned SplatBitSize;
8368 if (BVN && Subtarget->hasNEON() &&
8369 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8370 if (SplatBitSize <= 64) {
8372 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8373 SplatUndef.getZExtValue(), SplatBitSize,
8374 DAG, VorrVT, VT.is128BitVector(),
8376 if (Val.getNode()) {
8378 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8379 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8380 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8385 if (!Subtarget->isThumb1Only()) {
8386 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8387 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8388 if (Result.getNode())
8392 // The code below optimizes (or (and X, Y), Z).
8393 // The AND operand needs to have a single user to make these optimizations
8395 SDValue N0 = N->getOperand(0);
8396 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8398 SDValue N1 = N->getOperand(1);
8400 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8401 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8402 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8404 unsigned SplatBitSize;
8407 APInt SplatBits0, SplatBits1;
8408 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8409 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8410 // Ensure that the second operand of both ands are constants
8411 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8412 HasAnyUndefs) && !HasAnyUndefs) {
8413 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8414 HasAnyUndefs) && !HasAnyUndefs) {
8415 // Ensure that the bit width of the constants are the same and that
8416 // the splat arguments are logical inverses as per the pattern we
8417 // are trying to simplify.
8418 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8419 SplatBits0 == ~SplatBits1) {
8420 // Canonicalize the vector type to make instruction selection
8422 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8423 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8427 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8433 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8436 // BFI is only available on V6T2+
8437 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8441 // 1) or (and A, mask), val => ARMbfi A, val, mask
8442 // iff (val & mask) == val
8444 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8445 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8446 // && mask == ~mask2
8447 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8448 // && ~mask == mask2
8449 // (i.e., copy a bitfield value into another bitfield of the same width)
8454 SDValue N00 = N0.getOperand(0);
8456 // The value and the mask need to be constants so we can verify this is
8457 // actually a bitfield set. If the mask is 0xffff, we can do better
8458 // via a movt instruction, so don't use BFI in that case.
8459 SDValue MaskOp = N0.getOperand(1);
8460 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8463 unsigned Mask = MaskC->getZExtValue();
8467 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8468 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8470 unsigned Val = N1C->getZExtValue();
8471 if ((Val & ~Mask) != Val)
8474 if (ARM::isBitFieldInvertedMask(Mask)) {
8475 Val >>= countTrailingZeros(~Mask);
8477 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8478 DAG.getConstant(Val, MVT::i32),
8479 DAG.getConstant(Mask, MVT::i32));
8481 // Do not add new nodes to DAG combiner worklist.
8482 DCI.CombineTo(N, Res, false);
8485 } else if (N1.getOpcode() == ISD::AND) {
8486 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8487 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8490 unsigned Mask2 = N11C->getZExtValue();
8492 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8494 if (ARM::isBitFieldInvertedMask(Mask) &&
8496 // The pack halfword instruction works better for masks that fit it,
8497 // so use that when it's available.
8498 if (Subtarget->hasT2ExtractPack() &&
8499 (Mask == 0xffff || Mask == 0xffff0000))
8502 unsigned amt = countTrailingZeros(Mask2);
8503 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8504 DAG.getConstant(amt, MVT::i32));
8505 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8506 DAG.getConstant(Mask, MVT::i32));
8507 // Do not add new nodes to DAG combiner worklist.
8508 DCI.CombineTo(N, Res, false);
8510 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8512 // The pack halfword instruction works better for masks that fit it,
8513 // so use that when it's available.
8514 if (Subtarget->hasT2ExtractPack() &&
8515 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8518 unsigned lsb = countTrailingZeros(Mask);
8519 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8520 DAG.getConstant(lsb, MVT::i32));
8521 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8522 DAG.getConstant(Mask2, MVT::i32));
8523 // Do not add new nodes to DAG combiner worklist.
8524 DCI.CombineTo(N, Res, false);
8529 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8530 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8531 ARM::isBitFieldInvertedMask(~Mask)) {
8532 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8533 // where lsb(mask) == #shamt and masked bits of B are known zero.
8534 SDValue ShAmt = N00.getOperand(1);
8535 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8536 unsigned LSB = countTrailingZeros(Mask);
8540 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8541 DAG.getConstant(~Mask, MVT::i32));
8543 // Do not add new nodes to DAG combiner worklist.
8544 DCI.CombineTo(N, Res, false);
8550 static SDValue PerformXORCombine(SDNode *N,
8551 TargetLowering::DAGCombinerInfo &DCI,
8552 const ARMSubtarget *Subtarget) {
8553 EVT VT = N->getValueType(0);
8554 SelectionDAG &DAG = DCI.DAG;
8556 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8559 if (!Subtarget->isThumb1Only()) {
8560 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8561 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8562 if (Result.getNode())
8569 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8570 /// the bits being cleared by the AND are not demanded by the BFI.
8571 static SDValue PerformBFICombine(SDNode *N,
8572 TargetLowering::DAGCombinerInfo &DCI) {
8573 SDValue N1 = N->getOperand(1);
8574 if (N1.getOpcode() == ISD::AND) {
8575 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8578 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8579 unsigned LSB = countTrailingZeros(~InvMask);
8580 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8582 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8583 "undefined behavior");
8584 unsigned Mask = (1u << Width) - 1;
8585 unsigned Mask2 = N11C->getZExtValue();
8586 if ((Mask & (~Mask2)) == 0)
8587 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8588 N->getOperand(0), N1.getOperand(0),
8594 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8595 /// ARMISD::VMOVRRD.
8596 static SDValue PerformVMOVRRDCombine(SDNode *N,
8597 TargetLowering::DAGCombinerInfo &DCI,
8598 const ARMSubtarget *Subtarget) {
8599 // vmovrrd(vmovdrr x, y) -> x,y
8600 SDValue InDouble = N->getOperand(0);
8601 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8602 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8604 // vmovrrd(load f64) -> (load i32), (load i32)
8605 SDNode *InNode = InDouble.getNode();
8606 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8607 InNode->getValueType(0) == MVT::f64 &&
8608 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8609 !cast<LoadSDNode>(InNode)->isVolatile()) {
8610 // TODO: Should this be done for non-FrameIndex operands?
8611 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8613 SelectionDAG &DAG = DCI.DAG;
8615 SDValue BasePtr = LD->getBasePtr();
8616 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8617 LD->getPointerInfo(), LD->isVolatile(),
8618 LD->isNonTemporal(), LD->isInvariant(),
8619 LD->getAlignment());
8621 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8622 DAG.getConstant(4, MVT::i32));
8623 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8624 LD->getPointerInfo(), LD->isVolatile(),
8625 LD->isNonTemporal(), LD->isInvariant(),
8626 std::min(4U, LD->getAlignment() / 2));
8628 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8629 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8630 std::swap (NewLD1, NewLD2);
8631 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8638 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8639 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8640 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8641 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8642 SDValue Op0 = N->getOperand(0);
8643 SDValue Op1 = N->getOperand(1);
8644 if (Op0.getOpcode() == ISD::BITCAST)
8645 Op0 = Op0.getOperand(0);
8646 if (Op1.getOpcode() == ISD::BITCAST)
8647 Op1 = Op1.getOperand(0);
8648 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8649 Op0.getNode() == Op1.getNode() &&
8650 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8651 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8652 N->getValueType(0), Op0.getOperand(0));
8656 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8657 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8658 /// i64 vector to have f64 elements, since the value can then be loaded
8659 /// directly into a VFP register.
8660 static bool hasNormalLoadOperand(SDNode *N) {
8661 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8662 for (unsigned i = 0; i < NumElts; ++i) {
8663 SDNode *Elt = N->getOperand(i).getNode();
8664 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8670 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8671 /// ISD::BUILD_VECTOR.
8672 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8673 TargetLowering::DAGCombinerInfo &DCI,
8674 const ARMSubtarget *Subtarget) {
8675 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8676 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8677 // into a pair of GPRs, which is fine when the value is used as a scalar,
8678 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8679 SelectionDAG &DAG = DCI.DAG;
8680 if (N->getNumOperands() == 2) {
8681 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8686 // Load i64 elements as f64 values so that type legalization does not split
8687 // them up into i32 values.
8688 EVT VT = N->getValueType(0);
8689 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8692 SmallVector<SDValue, 8> Ops;
8693 unsigned NumElts = VT.getVectorNumElements();
8694 for (unsigned i = 0; i < NumElts; ++i) {
8695 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8697 // Make the DAGCombiner fold the bitcast.
8698 DCI.AddToWorklist(V.getNode());
8700 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8701 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8702 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8705 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8707 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8708 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8709 // At that time, we may have inserted bitcasts from integer to float.
8710 // If these bitcasts have survived DAGCombine, change the lowering of this
8711 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8712 // force to use floating point types.
8714 // Make sure we can change the type of the vector.
8715 // This is possible iff:
8716 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8717 // 1.1. Vector is used only once.
8718 // 1.2. Use is a bit convert to an integer type.
8719 // 2. The size of its operands are 32-bits (64-bits are not legal).
8720 EVT VT = N->getValueType(0);
8721 EVT EltVT = VT.getVectorElementType();
8723 // Check 1.1. and 2.
8724 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8727 // By construction, the input type must be float.
8728 assert(EltVT == MVT::f32 && "Unexpected type!");
8731 SDNode *Use = *N->use_begin();
8732 if (Use->getOpcode() != ISD::BITCAST ||
8733 Use->getValueType(0).isFloatingPoint())
8736 // Check profitability.
8737 // Model is, if more than half of the relevant operands are bitcast from
8738 // i32, turn the build_vector into a sequence of insert_vector_elt.
8739 // Relevant operands are everything that is not statically
8740 // (i.e., at compile time) bitcasted.
8741 unsigned NumOfBitCastedElts = 0;
8742 unsigned NumElts = VT.getVectorNumElements();
8743 unsigned NumOfRelevantElts = NumElts;
8744 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8745 SDValue Elt = N->getOperand(Idx);
8746 if (Elt->getOpcode() == ISD::BITCAST) {
8747 // Assume only bit cast to i32 will go away.
8748 if (Elt->getOperand(0).getValueType() == MVT::i32)
8749 ++NumOfBitCastedElts;
8750 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8751 // Constants are statically casted, thus do not count them as
8752 // relevant operands.
8753 --NumOfRelevantElts;
8756 // Check if more than half of the elements require a non-free bitcast.
8757 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8760 SelectionDAG &DAG = DCI.DAG;
8761 // Create the new vector type.
8762 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8763 // Check if the type is legal.
8764 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8765 if (!TLI.isTypeLegal(VecVT))
8769 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8770 // => BITCAST INSERT_VECTOR_ELT
8771 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8773 SDValue Vec = DAG.getUNDEF(VecVT);
8775 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8776 SDValue V = N->getOperand(Idx);
8777 if (V.getOpcode() == ISD::UNDEF)
8779 if (V.getOpcode() == ISD::BITCAST &&
8780 V->getOperand(0).getValueType() == MVT::i32)
8781 // Fold obvious case.
8782 V = V.getOperand(0);
8784 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8785 // Make the DAGCombiner fold the bitcasts.
8786 DCI.AddToWorklist(V.getNode());
8788 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8789 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8791 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8792 // Make the DAGCombiner fold the bitcasts.
8793 DCI.AddToWorklist(Vec.getNode());
8797 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8798 /// ISD::INSERT_VECTOR_ELT.
8799 static SDValue PerformInsertEltCombine(SDNode *N,
8800 TargetLowering::DAGCombinerInfo &DCI) {
8801 // Bitcast an i64 load inserted into a vector to f64.
8802 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8803 EVT VT = N->getValueType(0);
8804 SDNode *Elt = N->getOperand(1).getNode();
8805 if (VT.getVectorElementType() != MVT::i64 ||
8806 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8809 SelectionDAG &DAG = DCI.DAG;
8811 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8812 VT.getVectorNumElements());
8813 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8814 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8815 // Make the DAGCombiner fold the bitcasts.
8816 DCI.AddToWorklist(Vec.getNode());
8817 DCI.AddToWorklist(V.getNode());
8818 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8819 Vec, V, N->getOperand(2));
8820 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8823 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8824 /// ISD::VECTOR_SHUFFLE.
8825 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8826 // The LLVM shufflevector instruction does not require the shuffle mask
8827 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8828 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8829 // operands do not match the mask length, they are extended by concatenating
8830 // them with undef vectors. That is probably the right thing for other
8831 // targets, but for NEON it is better to concatenate two double-register
8832 // size vector operands into a single quad-register size vector. Do that
8833 // transformation here:
8834 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8835 // shuffle(concat(v1, v2), undef)
8836 SDValue Op0 = N->getOperand(0);
8837 SDValue Op1 = N->getOperand(1);
8838 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8839 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8840 Op0.getNumOperands() != 2 ||
8841 Op1.getNumOperands() != 2)
8843 SDValue Concat0Op1 = Op0.getOperand(1);
8844 SDValue Concat1Op1 = Op1.getOperand(1);
8845 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8846 Concat1Op1.getOpcode() != ISD::UNDEF)
8848 // Skip the transformation if any of the types are illegal.
8849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8850 EVT VT = N->getValueType(0);
8851 if (!TLI.isTypeLegal(VT) ||
8852 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8853 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8856 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8857 Op0.getOperand(0), Op1.getOperand(0));
8858 // Translate the shuffle mask.
8859 SmallVector<int, 16> NewMask;
8860 unsigned NumElts = VT.getVectorNumElements();
8861 unsigned HalfElts = NumElts/2;
8862 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8863 for (unsigned n = 0; n < NumElts; ++n) {
8864 int MaskElt = SVN->getMaskElt(n);
8866 if (MaskElt < (int)HalfElts)
8868 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8869 NewElt = HalfElts + MaskElt - NumElts;
8870 NewMask.push_back(NewElt);
8872 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8873 DAG.getUNDEF(VT), NewMask.data());
8876 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8877 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8878 /// base address updates.
8879 /// For generic load/stores, the memory type is assumed to be a vector.
8880 /// The caller is assumed to have checked legality.
8881 static SDValue CombineBaseUpdate(SDNode *N,
8882 TargetLowering::DAGCombinerInfo &DCI) {
8883 SelectionDAG &DAG = DCI.DAG;
8884 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8885 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8886 const bool isStore = N->getOpcode() == ISD::STORE;
8887 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8888 SDValue Addr = N->getOperand(AddrOpIdx);
8889 MemSDNode *MemN = cast<MemSDNode>(N);
8891 // Search for a use of the address operand that is an increment.
8892 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8893 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8895 if (User->getOpcode() != ISD::ADD ||
8896 UI.getUse().getResNo() != Addr.getResNo())
8899 // Check that the add is independent of the load/store. Otherwise, folding
8900 // it would create a cycle.
8901 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8904 // Find the new opcode for the updating load/store.
8905 bool isLoadOp = true;
8906 bool isLaneOp = false;
8907 unsigned NewOpc = 0;
8908 unsigned NumVecs = 0;
8910 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8912 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8913 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8915 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8917 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8919 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8921 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8922 NumVecs = 2; isLaneOp = true; break;
8923 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8924 NumVecs = 3; isLaneOp = true; break;
8925 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8926 NumVecs = 4; isLaneOp = true; break;
8927 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8928 NumVecs = 1; isLoadOp = false; break;
8929 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8930 NumVecs = 2; isLoadOp = false; break;
8931 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8932 NumVecs = 3; isLoadOp = false; break;
8933 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8934 NumVecs = 4; isLoadOp = false; break;
8935 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8936 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8937 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8938 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8939 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8940 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8944 switch (N->getOpcode()) {
8945 default: llvm_unreachable("unexpected opcode for Neon base update");
8946 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8947 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8948 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8949 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8950 NumVecs = 1; isLaneOp = false; break;
8951 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8952 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8956 // Find the size of memory referenced by the load/store.
8959 VecTy = N->getValueType(0);
8960 } else if (isIntrinsic) {
8961 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8963 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8964 VecTy = N->getOperand(1).getValueType();
8967 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8969 NumBytes /= VecTy.getVectorNumElements();
8971 // If the increment is a constant, it must match the memory ref size.
8972 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8973 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8974 uint64_t IncVal = CInc->getZExtValue();
8975 if (IncVal != NumBytes)
8977 } else if (NumBytes >= 3 * 16) {
8978 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8979 // separate instructions that make it harder to use a non-constant update.
8983 // OK, we found an ADD we can fold into the base update.
8984 // Now, create a _UPD node, taking care of not breaking alignment.
8986 EVT AlignedVecTy = VecTy;
8987 unsigned Alignment = MemN->getAlignment();
8989 // If this is a less-than-standard-aligned load/store, change the type to
8990 // match the standard alignment.
8991 // The alignment is overlooked when selecting _UPD variants; and it's
8992 // easier to introduce bitcasts here than fix that.
8993 // There are 3 ways to get to this base-update combine:
8994 // - intrinsics: they are assumed to be properly aligned (to the standard
8995 // alignment of the memory type), so we don't need to do anything.
8996 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
8997 // intrinsics, so, likewise, there's nothing to do.
8998 // - generic load/store instructions: the alignment is specified as an
8999 // explicit operand, rather than implicitly as the standard alignment
9000 // of the memory type (like the intrisics). We need to change the
9001 // memory type to match the explicit alignment. That way, we don't
9002 // generate non-standard-aligned ARMISD::VLDx nodes.
9003 if (isa<LSBaseSDNode>(N)) {
9006 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9007 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9008 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9009 assert(!isLaneOp && "Unexpected generic load/store lane.");
9010 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9011 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9013 // Don't set an explicit alignment on regular load/stores that we want
9014 // to transform to VLD/VST 1_UPD nodes.
9015 // This matches the behavior of regular load/stores, which only get an
9016 // explicit alignment if the MMO alignment is larger than the standard
9017 // alignment of the memory type.
9018 // Intrinsics, however, always get an explicit alignment, set to the
9019 // alignment of the MMO.
9023 // Create the new updating load/store node.
9024 // First, create an SDVTList for the new updating node's results.
9026 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9028 for (n = 0; n < NumResultVecs; ++n)
9029 Tys[n] = AlignedVecTy;
9030 Tys[n++] = MVT::i32;
9031 Tys[n] = MVT::Other;
9032 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9034 // Then, gather the new node's operands.
9035 SmallVector<SDValue, 8> Ops;
9036 Ops.push_back(N->getOperand(0)); // incoming chain
9037 Ops.push_back(N->getOperand(AddrOpIdx));
9040 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9041 // Try to match the intrinsic's signature
9042 Ops.push_back(StN->getValue());
9044 // Loads (and of course intrinsics) match the intrinsics' signature,
9045 // so just add all but the alignment operand.
9046 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9047 Ops.push_back(N->getOperand(i));
9050 // For all node types, the alignment operand is always the last one.
9051 Ops.push_back(DAG.getConstant(Alignment, MVT::i32));
9053 // If this is a non-standard-aligned STORE, the penultimate operand is the
9054 // stored value. Bitcast it to the aligned type.
9055 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9056 SDValue &StVal = Ops[Ops.size()-2];
9057 StVal = DAG.getNode(ISD::BITCAST, SDLoc(N), AlignedVecTy, StVal);
9060 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9062 MemN->getMemOperand());
9065 SmallVector<SDValue, 5> NewResults;
9066 for (unsigned i = 0; i < NumResultVecs; ++i)
9067 NewResults.push_back(SDValue(UpdN.getNode(), i));
9069 // If this is an non-standard-aligned LOAD, the first result is the loaded
9070 // value. Bitcast it to the expected result type.
9071 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9072 SDValue &LdVal = NewResults[0];
9073 LdVal = DAG.getNode(ISD::BITCAST, SDLoc(N), VecTy, LdVal);
9076 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9077 DCI.CombineTo(N, NewResults);
9078 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9085 static SDValue PerformVLDCombine(SDNode *N,
9086 TargetLowering::DAGCombinerInfo &DCI) {
9087 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9090 return CombineBaseUpdate(N, DCI);
9093 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9094 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9095 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9097 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9098 SelectionDAG &DAG = DCI.DAG;
9099 EVT VT = N->getValueType(0);
9100 // vldN-dup instructions only support 64-bit vectors for N > 1.
9101 if (!VT.is64BitVector())
9104 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9105 SDNode *VLD = N->getOperand(0).getNode();
9106 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9108 unsigned NumVecs = 0;
9109 unsigned NewOpc = 0;
9110 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9111 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9113 NewOpc = ARMISD::VLD2DUP;
9114 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9116 NewOpc = ARMISD::VLD3DUP;
9117 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9119 NewOpc = ARMISD::VLD4DUP;
9124 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9125 // numbers match the load.
9126 unsigned VLDLaneNo =
9127 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9128 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9130 // Ignore uses of the chain result.
9131 if (UI.getUse().getResNo() == NumVecs)
9134 if (User->getOpcode() != ARMISD::VDUPLANE ||
9135 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9139 // Create the vldN-dup node.
9142 for (n = 0; n < NumVecs; ++n)
9144 Tys[n] = MVT::Other;
9145 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9146 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9147 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9148 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9149 Ops, VLDMemInt->getMemoryVT(),
9150 VLDMemInt->getMemOperand());
9153 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9155 unsigned ResNo = UI.getUse().getResNo();
9156 // Ignore uses of the chain result.
9157 if (ResNo == NumVecs)
9160 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9163 // Now the vldN-lane intrinsic is dead except for its chain result.
9164 // Update uses of the chain.
9165 std::vector<SDValue> VLDDupResults;
9166 for (unsigned n = 0; n < NumVecs; ++n)
9167 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9168 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9169 DCI.CombineTo(VLD, VLDDupResults);
9174 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9175 /// ARMISD::VDUPLANE.
9176 static SDValue PerformVDUPLANECombine(SDNode *N,
9177 TargetLowering::DAGCombinerInfo &DCI) {
9178 SDValue Op = N->getOperand(0);
9180 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9181 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9182 if (CombineVLDDUP(N, DCI))
9183 return SDValue(N, 0);
9185 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9186 // redundant. Ignore bit_converts for now; element sizes are checked below.
9187 while (Op.getOpcode() == ISD::BITCAST)
9188 Op = Op.getOperand(0);
9189 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9192 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9193 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9194 // The canonical VMOV for a zero vector uses a 32-bit element size.
9195 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9197 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9199 EVT VT = N->getValueType(0);
9200 if (EltSize > VT.getVectorElementType().getSizeInBits())
9203 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9206 static SDValue PerformLOADCombine(SDNode *N,
9207 TargetLowering::DAGCombinerInfo &DCI) {
9208 EVT VT = N->getValueType(0);
9210 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9211 if (ISD::isNormalLoad(N) && VT.isVector() &&
9212 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9213 return CombineBaseUpdate(N, DCI);
9218 /// PerformSTORECombine - Target-specific dag combine xforms for
9220 static SDValue PerformSTORECombine(SDNode *N,
9221 TargetLowering::DAGCombinerInfo &DCI) {
9222 StoreSDNode *St = cast<StoreSDNode>(N);
9223 if (St->isVolatile())
9226 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9227 // pack all of the elements in one place. Next, store to memory in fewer
9229 SDValue StVal = St->getValue();
9230 EVT VT = StVal.getValueType();
9231 if (St->isTruncatingStore() && VT.isVector()) {
9232 SelectionDAG &DAG = DCI.DAG;
9233 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9234 EVT StVT = St->getMemoryVT();
9235 unsigned NumElems = VT.getVectorNumElements();
9236 assert(StVT != VT && "Cannot truncate to the same type");
9237 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9238 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9240 // From, To sizes and ElemCount must be pow of two
9241 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9243 // We are going to use the original vector elt for storing.
9244 // Accumulated smaller vector elements must be a multiple of the store size.
9245 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9247 unsigned SizeRatio = FromEltSz / ToEltSz;
9248 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9250 // Create a type on which we perform the shuffle.
9251 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9252 NumElems*SizeRatio);
9253 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9256 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9257 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9258 for (unsigned i = 0; i < NumElems; ++i)
9259 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9261 // Can't shuffle using an illegal type.
9262 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9264 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9265 DAG.getUNDEF(WideVec.getValueType()),
9267 // At this point all of the data is stored at the bottom of the
9268 // register. We now need to save it to mem.
9270 // Find the largest store unit
9271 MVT StoreType = MVT::i8;
9272 for (MVT Tp : MVT::integer_valuetypes()) {
9273 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9276 // Didn't find a legal store type.
9277 if (!TLI.isTypeLegal(StoreType))
9280 // Bitcast the original vector into a vector of store-size units
9281 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9282 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9283 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9284 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9285 SmallVector<SDValue, 8> Chains;
9286 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9287 TLI.getPointerTy());
9288 SDValue BasePtr = St->getBasePtr();
9290 // Perform one or more big stores into memory.
9291 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9292 for (unsigned I = 0; I < E; I++) {
9293 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9294 StoreType, ShuffWide,
9295 DAG.getIntPtrConstant(I));
9296 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9297 St->getPointerInfo(), St->isVolatile(),
9298 St->isNonTemporal(), St->getAlignment());
9299 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9301 Chains.push_back(Ch);
9303 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9306 if (!ISD::isNormalStore(St))
9309 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9310 // ARM stores of arguments in the same cache line.
9311 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9312 StVal.getNode()->hasOneUse()) {
9313 SelectionDAG &DAG = DCI.DAG;
9314 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9316 SDValue BasePtr = St->getBasePtr();
9317 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9318 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9319 BasePtr, St->getPointerInfo(), St->isVolatile(),
9320 St->isNonTemporal(), St->getAlignment());
9322 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9323 DAG.getConstant(4, MVT::i32));
9324 return DAG.getStore(NewST1.getValue(0), DL,
9325 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9326 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9327 St->isNonTemporal(),
9328 std::min(4U, St->getAlignment() / 2));
9331 if (StVal.getValueType() == MVT::i64 &&
9332 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9334 // Bitcast an i64 store extracted from a vector to f64.
9335 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9336 SelectionDAG &DAG = DCI.DAG;
9338 SDValue IntVec = StVal.getOperand(0);
9339 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9340 IntVec.getValueType().getVectorNumElements());
9341 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9342 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9343 Vec, StVal.getOperand(1));
9345 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9346 // Make the DAGCombiner fold the bitcasts.
9347 DCI.AddToWorklist(Vec.getNode());
9348 DCI.AddToWorklist(ExtElt.getNode());
9349 DCI.AddToWorklist(V.getNode());
9350 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9351 St->getPointerInfo(), St->isVolatile(),
9352 St->isNonTemporal(), St->getAlignment(),
9356 // If this is a legal vector store, try to combine it into a VST1_UPD.
9357 if (ISD::isNormalStore(N) && VT.isVector() &&
9358 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9359 return CombineBaseUpdate(N, DCI);
9364 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9365 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9366 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9370 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9372 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9377 APFloat APF = C->getValueAPF();
9378 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9379 != APFloat::opOK || !isExact)
9382 c0 = (I == 0) ? cN : c0;
9383 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9390 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9391 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9392 /// when the VMUL has a constant operand that is a power of 2.
9394 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9395 /// vmul.f32 d16, d17, d16
9396 /// vcvt.s32.f32 d16, d16
9398 /// vcvt.s32.f32 d16, d16, #3
9399 static SDValue PerformVCVTCombine(SDNode *N,
9400 TargetLowering::DAGCombinerInfo &DCI,
9401 const ARMSubtarget *Subtarget) {
9402 SelectionDAG &DAG = DCI.DAG;
9403 SDValue Op = N->getOperand(0);
9405 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9406 Op.getOpcode() != ISD::FMUL)
9410 SDValue N0 = Op->getOperand(0);
9411 SDValue ConstVec = Op->getOperand(1);
9412 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9414 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9415 !isConstVecPow2(ConstVec, isSigned, C))
9418 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9419 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9420 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9421 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9423 // These instructions only exist converting from f32 to i32. We can handle
9424 // smaller integers by generating an extra truncate, but larger ones would
9425 // be lossy. We also can't handle more then 4 lanes, since these intructions
9426 // only support v2i32/v4i32 types.
9430 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9431 Intrinsic::arm_neon_vcvtfp2fxu;
9432 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9433 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9434 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9435 DAG.getConstant(Log2_64(C), MVT::i32));
9437 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9438 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9443 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9444 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9445 /// when the VDIV has a constant operand that is a power of 2.
9447 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9448 /// vcvt.f32.s32 d16, d16
9449 /// vdiv.f32 d16, d17, d16
9451 /// vcvt.f32.s32 d16, d16, #3
9452 static SDValue PerformVDIVCombine(SDNode *N,
9453 TargetLowering::DAGCombinerInfo &DCI,
9454 const ARMSubtarget *Subtarget) {
9455 SelectionDAG &DAG = DCI.DAG;
9456 SDValue Op = N->getOperand(0);
9457 unsigned OpOpcode = Op.getNode()->getOpcode();
9459 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9460 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9464 SDValue ConstVec = N->getOperand(1);
9465 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9467 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9468 !isConstVecPow2(ConstVec, isSigned, C))
9471 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9472 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9473 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9474 // These instructions only exist converting from i32 to f32. We can handle
9475 // smaller integers by generating an extra extend, but larger ones would
9480 SDValue ConvInput = Op.getOperand(0);
9481 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9482 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9483 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9484 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9487 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9488 Intrinsic::arm_neon_vcvtfxu2fp;
9489 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9491 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9492 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9495 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9496 /// operand of a vector shift operation, where all the elements of the
9497 /// build_vector must have the same constant integer value.
9498 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9499 // Ignore bit_converts.
9500 while (Op.getOpcode() == ISD::BITCAST)
9501 Op = Op.getOperand(0);
9502 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9503 APInt SplatBits, SplatUndef;
9504 unsigned SplatBitSize;
9506 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9507 HasAnyUndefs, ElementBits) ||
9508 SplatBitSize > ElementBits)
9510 Cnt = SplatBits.getSExtValue();
9514 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9515 /// operand of a vector shift left operation. That value must be in the range:
9516 /// 0 <= Value < ElementBits for a left shift; or
9517 /// 0 <= Value <= ElementBits for a long left shift.
9518 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9519 assert(VT.isVector() && "vector shift count is not a vector type");
9520 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9521 if (! getVShiftImm(Op, ElementBits, Cnt))
9523 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9526 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9527 /// operand of a vector shift right operation. For a shift opcode, the value
9528 /// is positive, but for an intrinsic the value count must be negative. The
9529 /// absolute value must be in the range:
9530 /// 1 <= |Value| <= ElementBits for a right shift; or
9531 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9532 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9534 assert(VT.isVector() && "vector shift count is not a vector type");
9535 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9536 if (! getVShiftImm(Op, ElementBits, Cnt))
9540 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9543 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9544 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9545 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9548 // Don't do anything for most intrinsics.
9551 // Vector shifts: check for immediate versions and lower them.
9552 // Note: This is done during DAG combining instead of DAG legalizing because
9553 // the build_vectors for 64-bit vector element shift counts are generally
9554 // not legal, and it is hard to see their values after they get legalized to
9555 // loads from a constant pool.
9556 case Intrinsic::arm_neon_vshifts:
9557 case Intrinsic::arm_neon_vshiftu:
9558 case Intrinsic::arm_neon_vrshifts:
9559 case Intrinsic::arm_neon_vrshiftu:
9560 case Intrinsic::arm_neon_vrshiftn:
9561 case Intrinsic::arm_neon_vqshifts:
9562 case Intrinsic::arm_neon_vqshiftu:
9563 case Intrinsic::arm_neon_vqshiftsu:
9564 case Intrinsic::arm_neon_vqshiftns:
9565 case Intrinsic::arm_neon_vqshiftnu:
9566 case Intrinsic::arm_neon_vqshiftnsu:
9567 case Intrinsic::arm_neon_vqrshiftns:
9568 case Intrinsic::arm_neon_vqrshiftnu:
9569 case Intrinsic::arm_neon_vqrshiftnsu: {
9570 EVT VT = N->getOperand(1).getValueType();
9572 unsigned VShiftOpc = 0;
9575 case Intrinsic::arm_neon_vshifts:
9576 case Intrinsic::arm_neon_vshiftu:
9577 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9578 VShiftOpc = ARMISD::VSHL;
9581 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9582 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9583 ARMISD::VSHRs : ARMISD::VSHRu);
9588 case Intrinsic::arm_neon_vrshifts:
9589 case Intrinsic::arm_neon_vrshiftu:
9590 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9594 case Intrinsic::arm_neon_vqshifts:
9595 case Intrinsic::arm_neon_vqshiftu:
9596 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9600 case Intrinsic::arm_neon_vqshiftsu:
9601 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9603 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9605 case Intrinsic::arm_neon_vrshiftn:
9606 case Intrinsic::arm_neon_vqshiftns:
9607 case Intrinsic::arm_neon_vqshiftnu:
9608 case Intrinsic::arm_neon_vqshiftnsu:
9609 case Intrinsic::arm_neon_vqrshiftns:
9610 case Intrinsic::arm_neon_vqrshiftnu:
9611 case Intrinsic::arm_neon_vqrshiftnsu:
9612 // Narrowing shifts require an immediate right shift.
9613 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9615 llvm_unreachable("invalid shift count for narrowing vector shift "
9619 llvm_unreachable("unhandled vector shift");
9623 case Intrinsic::arm_neon_vshifts:
9624 case Intrinsic::arm_neon_vshiftu:
9625 // Opcode already set above.
9627 case Intrinsic::arm_neon_vrshifts:
9628 VShiftOpc = ARMISD::VRSHRs; break;
9629 case Intrinsic::arm_neon_vrshiftu:
9630 VShiftOpc = ARMISD::VRSHRu; break;
9631 case Intrinsic::arm_neon_vrshiftn:
9632 VShiftOpc = ARMISD::VRSHRN; break;
9633 case Intrinsic::arm_neon_vqshifts:
9634 VShiftOpc = ARMISD::VQSHLs; break;
9635 case Intrinsic::arm_neon_vqshiftu:
9636 VShiftOpc = ARMISD::VQSHLu; break;
9637 case Intrinsic::arm_neon_vqshiftsu:
9638 VShiftOpc = ARMISD::VQSHLsu; break;
9639 case Intrinsic::arm_neon_vqshiftns:
9640 VShiftOpc = ARMISD::VQSHRNs; break;
9641 case Intrinsic::arm_neon_vqshiftnu:
9642 VShiftOpc = ARMISD::VQSHRNu; break;
9643 case Intrinsic::arm_neon_vqshiftnsu:
9644 VShiftOpc = ARMISD::VQSHRNsu; break;
9645 case Intrinsic::arm_neon_vqrshiftns:
9646 VShiftOpc = ARMISD::VQRSHRNs; break;
9647 case Intrinsic::arm_neon_vqrshiftnu:
9648 VShiftOpc = ARMISD::VQRSHRNu; break;
9649 case Intrinsic::arm_neon_vqrshiftnsu:
9650 VShiftOpc = ARMISD::VQRSHRNsu; break;
9653 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9654 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9657 case Intrinsic::arm_neon_vshiftins: {
9658 EVT VT = N->getOperand(1).getValueType();
9660 unsigned VShiftOpc = 0;
9662 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9663 VShiftOpc = ARMISD::VSLI;
9664 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9665 VShiftOpc = ARMISD::VSRI;
9667 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9670 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9671 N->getOperand(1), N->getOperand(2),
9672 DAG.getConstant(Cnt, MVT::i32));
9675 case Intrinsic::arm_neon_vqrshifts:
9676 case Intrinsic::arm_neon_vqrshiftu:
9677 // No immediate versions of these to check for.
9684 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9685 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9686 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9687 /// vector element shift counts are generally not legal, and it is hard to see
9688 /// their values after they get legalized to loads from a constant pool.
9689 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9690 const ARMSubtarget *ST) {
9691 EVT VT = N->getValueType(0);
9692 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9693 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9694 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9695 SDValue N1 = N->getOperand(1);
9696 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9697 SDValue N0 = N->getOperand(0);
9698 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9699 DAG.MaskedValueIsZero(N0.getOperand(0),
9700 APInt::getHighBitsSet(32, 16)))
9701 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9705 // Nothing to be done for scalar shifts.
9706 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9707 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9710 assert(ST->hasNEON() && "unexpected vector shift");
9713 switch (N->getOpcode()) {
9714 default: llvm_unreachable("unexpected shift opcode");
9717 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9718 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9719 DAG.getConstant(Cnt, MVT::i32));
9724 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9725 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9726 ARMISD::VSHRs : ARMISD::VSHRu);
9727 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9728 DAG.getConstant(Cnt, MVT::i32));
9734 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9735 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9736 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9737 const ARMSubtarget *ST) {
9738 SDValue N0 = N->getOperand(0);
9740 // Check for sign- and zero-extensions of vector extract operations of 8-
9741 // and 16-bit vector elements. NEON supports these directly. They are
9742 // handled during DAG combining because type legalization will promote them
9743 // to 32-bit types and it is messy to recognize the operations after that.
9744 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9745 SDValue Vec = N0.getOperand(0);
9746 SDValue Lane = N0.getOperand(1);
9747 EVT VT = N->getValueType(0);
9748 EVT EltVT = N0.getValueType();
9749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9751 if (VT == MVT::i32 &&
9752 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9753 TLI.isTypeLegal(Vec.getValueType()) &&
9754 isa<ConstantSDNode>(Lane)) {
9757 switch (N->getOpcode()) {
9758 default: llvm_unreachable("unexpected opcode");
9759 case ISD::SIGN_EXTEND:
9760 Opc = ARMISD::VGETLANEs;
9762 case ISD::ZERO_EXTEND:
9763 case ISD::ANY_EXTEND:
9764 Opc = ARMISD::VGETLANEu;
9767 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9774 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9775 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9776 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9777 const ARMSubtarget *ST) {
9778 // If the target supports NEON, try to use vmax/vmin instructions for f32
9779 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9780 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9781 // a NaN; only do the transformation when it matches that behavior.
9783 // For now only do this when using NEON for FP operations; if using VFP, it
9784 // is not obvious that the benefit outweighs the cost of switching to the
9786 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9787 N->getValueType(0) != MVT::f32)
9790 SDValue CondLHS = N->getOperand(0);
9791 SDValue CondRHS = N->getOperand(1);
9792 SDValue LHS = N->getOperand(2);
9793 SDValue RHS = N->getOperand(3);
9794 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9796 unsigned Opcode = 0;
9798 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9799 IsReversed = false; // x CC y ? x : y
9800 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9801 IsReversed = true ; // x CC y ? y : x
9815 // If LHS is NaN, an ordered comparison will be false and the result will
9816 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9817 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9818 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9819 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9821 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9822 // will return -0, so vmin can only be used for unsafe math or if one of
9823 // the operands is known to be nonzero.
9824 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9825 !DAG.getTarget().Options.UnsafeFPMath &&
9826 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9828 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9837 // If LHS is NaN, an ordered comparison will be false and the result will
9838 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9839 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9840 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9841 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9843 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9844 // will return +0, so vmax can only be used for unsafe math or if one of
9845 // the operands is known to be nonzero.
9846 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9847 !DAG.getTarget().Options.UnsafeFPMath &&
9848 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9850 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9856 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9859 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9861 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9862 SDValue Cmp = N->getOperand(4);
9863 if (Cmp.getOpcode() != ARMISD::CMPZ)
9864 // Only looking at EQ and NE cases.
9867 EVT VT = N->getValueType(0);
9869 SDValue LHS = Cmp.getOperand(0);
9870 SDValue RHS = Cmp.getOperand(1);
9871 SDValue FalseVal = N->getOperand(0);
9872 SDValue TrueVal = N->getOperand(1);
9873 SDValue ARMcc = N->getOperand(2);
9874 ARMCC::CondCodes CC =
9875 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9893 /// FIXME: Turn this into a target neutral optimization?
9895 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9896 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9897 N->getOperand(3), Cmp);
9898 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9900 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9901 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9902 N->getOperand(3), NewCmp);
9905 if (Res.getNode()) {
9906 APInt KnownZero, KnownOne;
9907 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9908 // Capture demanded bits information that would be otherwise lost.
9909 if (KnownZero == 0xfffffffe)
9910 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9911 DAG.getValueType(MVT::i1));
9912 else if (KnownZero == 0xffffff00)
9913 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9914 DAG.getValueType(MVT::i8));
9915 else if (KnownZero == 0xffff0000)
9916 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9917 DAG.getValueType(MVT::i16));
9923 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9924 DAGCombinerInfo &DCI) const {
9925 switch (N->getOpcode()) {
9927 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9928 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9929 case ISD::SUB: return PerformSUBCombine(N, DCI);
9930 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9931 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9932 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9933 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9934 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9935 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9936 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9937 case ISD::STORE: return PerformSTORECombine(N, DCI);
9938 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9939 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9940 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9941 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9942 case ISD::FP_TO_SINT:
9943 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9944 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9945 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9948 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9949 case ISD::SIGN_EXTEND:
9950 case ISD::ZERO_EXTEND:
9951 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9952 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9953 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9954 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9955 case ARMISD::VLD2DUP:
9956 case ARMISD::VLD3DUP:
9957 case ARMISD::VLD4DUP:
9958 return PerformVLDCombine(N, DCI);
9959 case ARMISD::BUILD_VECTOR:
9960 return PerformARMBUILD_VECTORCombine(N, DCI);
9961 case ISD::INTRINSIC_VOID:
9962 case ISD::INTRINSIC_W_CHAIN:
9963 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9964 case Intrinsic::arm_neon_vld1:
9965 case Intrinsic::arm_neon_vld2:
9966 case Intrinsic::arm_neon_vld3:
9967 case Intrinsic::arm_neon_vld4:
9968 case Intrinsic::arm_neon_vld2lane:
9969 case Intrinsic::arm_neon_vld3lane:
9970 case Intrinsic::arm_neon_vld4lane:
9971 case Intrinsic::arm_neon_vst1:
9972 case Intrinsic::arm_neon_vst2:
9973 case Intrinsic::arm_neon_vst3:
9974 case Intrinsic::arm_neon_vst4:
9975 case Intrinsic::arm_neon_vst2lane:
9976 case Intrinsic::arm_neon_vst3lane:
9977 case Intrinsic::arm_neon_vst4lane:
9978 return PerformVLDCombine(N, DCI);
9986 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9988 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9991 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9995 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9996 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9998 switch (VT.getSimpleVT().SimpleTy) {
10004 // Unaligned access can use (for example) LRDB, LRDH, LDR
10005 if (AllowsUnaligned) {
10007 *Fast = Subtarget->hasV7Ops();
10014 // For any little-endian targets with neon, we can support unaligned ld/st
10015 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10016 // A big-endian target may also explicitly support unaligned accesses
10017 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10027 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10028 unsigned AlignCheck) {
10029 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10030 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10033 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10034 unsigned DstAlign, unsigned SrcAlign,
10035 bool IsMemset, bool ZeroMemset,
10037 MachineFunction &MF) const {
10038 const Function *F = MF.getFunction();
10040 // See if we can use NEON instructions for this...
10041 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10042 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10045 (memOpAlign(SrcAlign, DstAlign, 16) ||
10046 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10048 } else if (Size >= 8 &&
10049 (memOpAlign(SrcAlign, DstAlign, 8) ||
10050 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10056 // Lowering to i32/i16 if the size permits.
10059 else if (Size >= 2)
10062 // Let the target-independent logic figure it out.
10066 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10067 if (Val.getOpcode() != ISD::LOAD)
10070 EVT VT1 = Val.getValueType();
10071 if (!VT1.isSimple() || !VT1.isInteger() ||
10072 !VT2.isSimple() || !VT2.isInteger())
10075 switch (VT1.getSimpleVT().SimpleTy) {
10080 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10087 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10088 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10091 if (!isTypeLegal(EVT::getEVT(Ty1)))
10094 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10096 // Assuming the caller doesn't have a zeroext or signext return parameter,
10097 // truncation all the way down to i1 is valid.
10102 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10106 unsigned Scale = 1;
10107 switch (VT.getSimpleVT().SimpleTy) {
10108 default: return false;
10123 if ((V & (Scale - 1)) != 0)
10126 return V == (V & ((1LL << 5) - 1));
10129 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10130 const ARMSubtarget *Subtarget) {
10131 bool isNeg = false;
10137 switch (VT.getSimpleVT().SimpleTy) {
10138 default: return false;
10143 // + imm12 or - imm8
10145 return V == (V & ((1LL << 8) - 1));
10146 return V == (V & ((1LL << 12) - 1));
10149 // Same as ARM mode. FIXME: NEON?
10150 if (!Subtarget->hasVFP2())
10155 return V == (V & ((1LL << 8) - 1));
10159 /// isLegalAddressImmediate - Return true if the integer value can be used
10160 /// as the offset of the target addressing mode for load / store of the
10162 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10163 const ARMSubtarget *Subtarget) {
10167 if (!VT.isSimple())
10170 if (Subtarget->isThumb1Only())
10171 return isLegalT1AddressImmediate(V, VT);
10172 else if (Subtarget->isThumb2())
10173 return isLegalT2AddressImmediate(V, VT, Subtarget);
10178 switch (VT.getSimpleVT().SimpleTy) {
10179 default: return false;
10184 return V == (V & ((1LL << 12) - 1));
10187 return V == (V & ((1LL << 8) - 1));
10190 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10195 return V == (V & ((1LL << 8) - 1));
10199 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10201 int Scale = AM.Scale;
10205 switch (VT.getSimpleVT().SimpleTy) {
10206 default: return false;
10214 Scale = Scale & ~1;
10215 return Scale == 2 || Scale == 4 || Scale == 8;
10218 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10222 // Note, we allow "void" uses (basically, uses that aren't loads or
10223 // stores), because arm allows folding a scale into many arithmetic
10224 // operations. This should be made more precise and revisited later.
10226 // Allow r << imm, but the imm has to be a multiple of two.
10227 if (Scale & 1) return false;
10228 return isPowerOf2_32(Scale);
10232 /// isLegalAddressingMode - Return true if the addressing mode represented
10233 /// by AM is legal for this target, for a load/store of the specified type.
10234 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10236 EVT VT = getValueType(Ty, true);
10237 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10240 // Can never fold addr of global into load/store.
10244 switch (AM.Scale) {
10245 case 0: // no scale reg, must be "r+i" or "r", or "i".
10248 if (Subtarget->isThumb1Only())
10252 // ARM doesn't support any R+R*scale+imm addr modes.
10256 if (!VT.isSimple())
10259 if (Subtarget->isThumb2())
10260 return isLegalT2ScaledAddressingMode(AM, VT);
10262 int Scale = AM.Scale;
10263 switch (VT.getSimpleVT().SimpleTy) {
10264 default: return false;
10268 if (Scale < 0) Scale = -Scale;
10272 return isPowerOf2_32(Scale & ~1);
10276 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10281 // Note, we allow "void" uses (basically, uses that aren't loads or
10282 // stores), because arm allows folding a scale into many arithmetic
10283 // operations. This should be made more precise and revisited later.
10285 // Allow r << imm, but the imm has to be a multiple of two.
10286 if (Scale & 1) return false;
10287 return isPowerOf2_32(Scale);
10293 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10294 /// icmp immediate, that is the target has icmp instructions which can compare
10295 /// a register against the immediate without having to materialize the
10296 /// immediate into a register.
10297 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10298 // Thumb2 and ARM modes can use cmn for negative immediates.
10299 if (!Subtarget->isThumb())
10300 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10301 if (Subtarget->isThumb2())
10302 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10303 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10304 return Imm >= 0 && Imm <= 255;
10307 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10308 /// *or sub* immediate, that is the target has add or sub instructions which can
10309 /// add a register with the immediate without having to materialize the
10310 /// immediate into a register.
10311 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10312 // Same encoding for add/sub, just flip the sign.
10313 int64_t AbsImm = llvm::abs64(Imm);
10314 if (!Subtarget->isThumb())
10315 return ARM_AM::getSOImmVal(AbsImm) != -1;
10316 if (Subtarget->isThumb2())
10317 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10318 // Thumb1 only has 8-bit unsigned immediate.
10319 return AbsImm >= 0 && AbsImm <= 255;
10322 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10323 bool isSEXTLoad, SDValue &Base,
10324 SDValue &Offset, bool &isInc,
10325 SelectionDAG &DAG) {
10326 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10329 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10330 // AddressingMode 3
10331 Base = Ptr->getOperand(0);
10332 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10333 int RHSC = (int)RHS->getZExtValue();
10334 if (RHSC < 0 && RHSC > -256) {
10335 assert(Ptr->getOpcode() == ISD::ADD);
10337 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10341 isInc = (Ptr->getOpcode() == ISD::ADD);
10342 Offset = Ptr->getOperand(1);
10344 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10345 // AddressingMode 2
10346 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10347 int RHSC = (int)RHS->getZExtValue();
10348 if (RHSC < 0 && RHSC > -0x1000) {
10349 assert(Ptr->getOpcode() == ISD::ADD);
10351 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10352 Base = Ptr->getOperand(0);
10357 if (Ptr->getOpcode() == ISD::ADD) {
10359 ARM_AM::ShiftOpc ShOpcVal=
10360 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10361 if (ShOpcVal != ARM_AM::no_shift) {
10362 Base = Ptr->getOperand(1);
10363 Offset = Ptr->getOperand(0);
10365 Base = Ptr->getOperand(0);
10366 Offset = Ptr->getOperand(1);
10371 isInc = (Ptr->getOpcode() == ISD::ADD);
10372 Base = Ptr->getOperand(0);
10373 Offset = Ptr->getOperand(1);
10377 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10381 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10382 bool isSEXTLoad, SDValue &Base,
10383 SDValue &Offset, bool &isInc,
10384 SelectionDAG &DAG) {
10385 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10388 Base = Ptr->getOperand(0);
10389 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10390 int RHSC = (int)RHS->getZExtValue();
10391 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10392 assert(Ptr->getOpcode() == ISD::ADD);
10394 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10396 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10397 isInc = Ptr->getOpcode() == ISD::ADD;
10398 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10406 /// getPreIndexedAddressParts - returns true by value, base pointer and
10407 /// offset pointer and addressing mode by reference if the node's address
10408 /// can be legally represented as pre-indexed load / store address.
10410 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10412 ISD::MemIndexedMode &AM,
10413 SelectionDAG &DAG) const {
10414 if (Subtarget->isThumb1Only())
10419 bool isSEXTLoad = false;
10420 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10421 Ptr = LD->getBasePtr();
10422 VT = LD->getMemoryVT();
10423 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10424 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10425 Ptr = ST->getBasePtr();
10426 VT = ST->getMemoryVT();
10431 bool isLegal = false;
10432 if (Subtarget->isThumb2())
10433 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10434 Offset, isInc, DAG);
10436 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10437 Offset, isInc, DAG);
10441 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10445 /// getPostIndexedAddressParts - returns true by value, base pointer and
10446 /// offset pointer and addressing mode by reference if this node can be
10447 /// combined with a load / store to form a post-indexed load / store.
10448 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10451 ISD::MemIndexedMode &AM,
10452 SelectionDAG &DAG) const {
10453 if (Subtarget->isThumb1Only())
10458 bool isSEXTLoad = false;
10459 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10460 VT = LD->getMemoryVT();
10461 Ptr = LD->getBasePtr();
10462 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10463 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10464 VT = ST->getMemoryVT();
10465 Ptr = ST->getBasePtr();
10470 bool isLegal = false;
10471 if (Subtarget->isThumb2())
10472 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10475 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10481 // Swap base ptr and offset to catch more post-index load / store when
10482 // it's legal. In Thumb2 mode, offset must be an immediate.
10483 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10484 !Subtarget->isThumb2())
10485 std::swap(Base, Offset);
10487 // Post-indexed load / store update the base pointer.
10492 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10496 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10499 const SelectionDAG &DAG,
10500 unsigned Depth) const {
10501 unsigned BitWidth = KnownOne.getBitWidth();
10502 KnownZero = KnownOne = APInt(BitWidth, 0);
10503 switch (Op.getOpcode()) {
10509 // These nodes' second result is a boolean
10510 if (Op.getResNo() == 0)
10512 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10514 case ARMISD::CMOV: {
10515 // Bits are known zero/one if known on the LHS and RHS.
10516 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10517 if (KnownZero == 0 && KnownOne == 0) return;
10519 APInt KnownZeroRHS, KnownOneRHS;
10520 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10521 KnownZero &= KnownZeroRHS;
10522 KnownOne &= KnownOneRHS;
10525 case ISD::INTRINSIC_W_CHAIN: {
10526 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10527 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10530 case Intrinsic::arm_ldaex:
10531 case Intrinsic::arm_ldrex: {
10532 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10533 unsigned MemBits = VT.getScalarType().getSizeInBits();
10534 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10542 //===----------------------------------------------------------------------===//
10543 // ARM Inline Assembly Support
10544 //===----------------------------------------------------------------------===//
10546 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10547 // Looking for "rev" which is V6+.
10548 if (!Subtarget->hasV6Ops())
10551 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10552 std::string AsmStr = IA->getAsmString();
10553 SmallVector<StringRef, 4> AsmPieces;
10554 SplitString(AsmStr, AsmPieces, ";\n");
10556 switch (AsmPieces.size()) {
10557 default: return false;
10559 AsmStr = AsmPieces[0];
10561 SplitString(AsmStr, AsmPieces, " \t,");
10564 if (AsmPieces.size() == 3 &&
10565 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10566 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10567 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10568 if (Ty && Ty->getBitWidth() == 32)
10569 return IntrinsicLowering::LowerToByteSwap(CI);
10577 /// getConstraintType - Given a constraint letter, return the type of
10578 /// constraint it is for this target.
10579 ARMTargetLowering::ConstraintType
10580 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10581 if (Constraint.size() == 1) {
10582 switch (Constraint[0]) {
10584 case 'l': return C_RegisterClass;
10585 case 'w': return C_RegisterClass;
10586 case 'h': return C_RegisterClass;
10587 case 'x': return C_RegisterClass;
10588 case 't': return C_RegisterClass;
10589 case 'j': return C_Other; // Constant for movw.
10590 // An address with a single base register. Due to the way we
10591 // currently handle addresses it is the same as an 'r' memory constraint.
10592 case 'Q': return C_Memory;
10594 } else if (Constraint.size() == 2) {
10595 switch (Constraint[0]) {
10597 // All 'U+' constraints are addresses.
10598 case 'U': return C_Memory;
10601 return TargetLowering::getConstraintType(Constraint);
10604 /// Examine constraint type and operand type and determine a weight value.
10605 /// This object must already have been set up with the operand type
10606 /// and the current alternative constraint selected.
10607 TargetLowering::ConstraintWeight
10608 ARMTargetLowering::getSingleConstraintMatchWeight(
10609 AsmOperandInfo &info, const char *constraint) const {
10610 ConstraintWeight weight = CW_Invalid;
10611 Value *CallOperandVal = info.CallOperandVal;
10612 // If we don't have a value, we can't do a match,
10613 // but allow it at the lowest weight.
10614 if (!CallOperandVal)
10616 Type *type = CallOperandVal->getType();
10617 // Look at the constraint type.
10618 switch (*constraint) {
10620 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10623 if (type->isIntegerTy()) {
10624 if (Subtarget->isThumb())
10625 weight = CW_SpecificReg;
10627 weight = CW_Register;
10631 if (type->isFloatingPointTy())
10632 weight = CW_Register;
10638 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10640 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10642 if (Constraint.size() == 1) {
10643 // GCC ARM Constraint Letters
10644 switch (Constraint[0]) {
10645 case 'l': // Low regs or general regs.
10646 if (Subtarget->isThumb())
10647 return RCPair(0U, &ARM::tGPRRegClass);
10648 return RCPair(0U, &ARM::GPRRegClass);
10649 case 'h': // High regs or no regs.
10650 if (Subtarget->isThumb())
10651 return RCPair(0U, &ARM::hGPRRegClass);
10654 if (Subtarget->isThumb1Only())
10655 return RCPair(0U, &ARM::tGPRRegClass);
10656 return RCPair(0U, &ARM::GPRRegClass);
10658 if (VT == MVT::Other)
10660 if (VT == MVT::f32)
10661 return RCPair(0U, &ARM::SPRRegClass);
10662 if (VT.getSizeInBits() == 64)
10663 return RCPair(0U, &ARM::DPRRegClass);
10664 if (VT.getSizeInBits() == 128)
10665 return RCPair(0U, &ARM::QPRRegClass);
10668 if (VT == MVT::Other)
10670 if (VT == MVT::f32)
10671 return RCPair(0U, &ARM::SPR_8RegClass);
10672 if (VT.getSizeInBits() == 64)
10673 return RCPair(0U, &ARM::DPR_8RegClass);
10674 if (VT.getSizeInBits() == 128)
10675 return RCPair(0U, &ARM::QPR_8RegClass);
10678 if (VT == MVT::f32)
10679 return RCPair(0U, &ARM::SPRRegClass);
10683 if (StringRef("{cc}").equals_lower(Constraint))
10684 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10686 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10689 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10690 /// vector. If it is invalid, don't add anything to Ops.
10691 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10692 std::string &Constraint,
10693 std::vector<SDValue>&Ops,
10694 SelectionDAG &DAG) const {
10697 // Currently only support length 1 constraints.
10698 if (Constraint.length() != 1) return;
10700 char ConstraintLetter = Constraint[0];
10701 switch (ConstraintLetter) {
10704 case 'I': case 'J': case 'K': case 'L':
10705 case 'M': case 'N': case 'O':
10706 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10710 int64_t CVal64 = C->getSExtValue();
10711 int CVal = (int) CVal64;
10712 // None of these constraints allow values larger than 32 bits. Check
10713 // that the value fits in an int.
10714 if (CVal != CVal64)
10717 switch (ConstraintLetter) {
10719 // Constant suitable for movw, must be between 0 and
10721 if (Subtarget->hasV6T2Ops())
10722 if (CVal >= 0 && CVal <= 65535)
10726 if (Subtarget->isThumb1Only()) {
10727 // This must be a constant between 0 and 255, for ADD
10729 if (CVal >= 0 && CVal <= 255)
10731 } else if (Subtarget->isThumb2()) {
10732 // A constant that can be used as an immediate value in a
10733 // data-processing instruction.
10734 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10737 // A constant that can be used as an immediate value in a
10738 // data-processing instruction.
10739 if (ARM_AM::getSOImmVal(CVal) != -1)
10745 if (Subtarget->isThumb()) { // FIXME thumb2
10746 // This must be a constant between -255 and -1, for negated ADD
10747 // immediates. This can be used in GCC with an "n" modifier that
10748 // prints the negated value, for use with SUB instructions. It is
10749 // not useful otherwise but is implemented for compatibility.
10750 if (CVal >= -255 && CVal <= -1)
10753 // This must be a constant between -4095 and 4095. It is not clear
10754 // what this constraint is intended for. Implemented for
10755 // compatibility with GCC.
10756 if (CVal >= -4095 && CVal <= 4095)
10762 if (Subtarget->isThumb1Only()) {
10763 // A 32-bit value where only one byte has a nonzero value. Exclude
10764 // zero to match GCC. This constraint is used by GCC internally for
10765 // constants that can be loaded with a move/shift combination.
10766 // It is not useful otherwise but is implemented for compatibility.
10767 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10769 } else if (Subtarget->isThumb2()) {
10770 // A constant whose bitwise inverse can be used as an immediate
10771 // value in a data-processing instruction. This can be used in GCC
10772 // with a "B" modifier that prints the inverted value, for use with
10773 // BIC and MVN instructions. It is not useful otherwise but is
10774 // implemented for compatibility.
10775 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10778 // A constant whose bitwise inverse can be used as an immediate
10779 // value in a data-processing instruction. This can be used in GCC
10780 // with a "B" modifier that prints the inverted value, for use with
10781 // BIC and MVN instructions. It is not useful otherwise but is
10782 // implemented for compatibility.
10783 if (ARM_AM::getSOImmVal(~CVal) != -1)
10789 if (Subtarget->isThumb1Only()) {
10790 // This must be a constant between -7 and 7,
10791 // for 3-operand ADD/SUB immediate instructions.
10792 if (CVal >= -7 && CVal < 7)
10794 } else if (Subtarget->isThumb2()) {
10795 // A constant whose negation can be used as an immediate value in a
10796 // data-processing instruction. This can be used in GCC with an "n"
10797 // modifier that prints the negated value, for use with SUB
10798 // instructions. It is not useful otherwise but is implemented for
10800 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10803 // A constant whose negation can be used as an immediate value in a
10804 // data-processing instruction. This can be used in GCC with an "n"
10805 // modifier that prints the negated value, for use with SUB
10806 // instructions. It is not useful otherwise but is implemented for
10808 if (ARM_AM::getSOImmVal(-CVal) != -1)
10814 if (Subtarget->isThumb()) { // FIXME thumb2
10815 // This must be a multiple of 4 between 0 and 1020, for
10816 // ADD sp + immediate.
10817 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10820 // A power of two or a constant between 0 and 32. This is used in
10821 // GCC for the shift amount on shifted register operands, but it is
10822 // useful in general for any shift amounts.
10823 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10829 if (Subtarget->isThumb()) { // FIXME thumb2
10830 // This must be a constant between 0 and 31, for shift amounts.
10831 if (CVal >= 0 && CVal <= 31)
10837 if (Subtarget->isThumb()) { // FIXME thumb2
10838 // This must be a multiple of 4 between -508 and 508, for
10839 // ADD/SUB sp = sp + immediate.
10840 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10845 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10849 if (Result.getNode()) {
10850 Ops.push_back(Result);
10853 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10856 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10857 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10858 unsigned Opcode = Op->getOpcode();
10859 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10860 "Invalid opcode for Div/Rem lowering");
10861 bool isSigned = (Opcode == ISD::SDIVREM);
10862 EVT VT = Op->getValueType(0);
10863 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10866 switch (VT.getSimpleVT().SimpleTy) {
10867 default: llvm_unreachable("Unexpected request for libcall!");
10868 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10869 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10870 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10871 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10874 SDValue InChain = DAG.getEntryNode();
10876 TargetLowering::ArgListTy Args;
10877 TargetLowering::ArgListEntry Entry;
10878 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10879 EVT ArgVT = Op->getOperand(i).getValueType();
10880 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10881 Entry.Node = Op->getOperand(i);
10883 Entry.isSExt = isSigned;
10884 Entry.isZExt = !isSigned;
10885 Args.push_back(Entry);
10888 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10891 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10894 TargetLowering::CallLoweringInfo CLI(DAG);
10895 CLI.setDebugLoc(dl).setChain(InChain)
10896 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10897 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10899 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10900 return CallInfo.first;
10904 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10905 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10909 SDValue Chain = Op.getOperand(0);
10910 SDValue Size = Op.getOperand(1);
10912 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10913 DAG.getConstant(2, MVT::i32));
10916 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10917 Flag = Chain.getValue(1);
10919 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10920 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10922 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10923 Chain = NewSP.getValue(1);
10925 SDValue Ops[2] = { NewSP, Chain };
10926 return DAG.getMergeValues(Ops, DL);
10929 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10930 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10931 "Unexpected type for custom-lowering FP_EXTEND");
10934 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10936 SDValue SrcVal = Op.getOperand(0);
10937 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10938 /*isSigned*/ false, SDLoc(Op)).first;
10941 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10942 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10943 Subtarget->isFPOnlySP() &&
10944 "Unexpected type for custom-lowering FP_ROUND");
10947 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10949 SDValue SrcVal = Op.getOperand(0);
10950 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10951 /*isSigned*/ false, SDLoc(Op)).first;
10955 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10956 // The ARM target isn't yet aware of offsets.
10960 bool ARM::isBitFieldInvertedMask(unsigned v) {
10961 if (v == 0xffffffff)
10964 // there can be 1's on either or both "outsides", all the "inside"
10965 // bits must be 0's
10966 return isShiftedMask_32(~v);
10969 /// isFPImmLegal - Returns true if the target can instruction select the
10970 /// specified FP immediate natively. If false, the legalizer will
10971 /// materialize the FP immediate as a load from a constant pool.
10972 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10973 if (!Subtarget->hasVFP3())
10975 if (VT == MVT::f32)
10976 return ARM_AM::getFP32Imm(Imm) != -1;
10977 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10978 return ARM_AM::getFP64Imm(Imm) != -1;
10982 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10983 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10984 /// specified in the intrinsic calls.
10985 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10987 unsigned Intrinsic) const {
10988 switch (Intrinsic) {
10989 case Intrinsic::arm_neon_vld1:
10990 case Intrinsic::arm_neon_vld2:
10991 case Intrinsic::arm_neon_vld3:
10992 case Intrinsic::arm_neon_vld4:
10993 case Intrinsic::arm_neon_vld2lane:
10994 case Intrinsic::arm_neon_vld3lane:
10995 case Intrinsic::arm_neon_vld4lane: {
10996 Info.opc = ISD::INTRINSIC_W_CHAIN;
10997 // Conservatively set memVT to the entire set of vectors loaded.
10998 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10999 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11000 Info.ptrVal = I.getArgOperand(0);
11002 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11003 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11004 Info.vol = false; // volatile loads with NEON intrinsics not supported
11005 Info.readMem = true;
11006 Info.writeMem = false;
11009 case Intrinsic::arm_neon_vst1:
11010 case Intrinsic::arm_neon_vst2:
11011 case Intrinsic::arm_neon_vst3:
11012 case Intrinsic::arm_neon_vst4:
11013 case Intrinsic::arm_neon_vst2lane:
11014 case Intrinsic::arm_neon_vst3lane:
11015 case Intrinsic::arm_neon_vst4lane: {
11016 Info.opc = ISD::INTRINSIC_VOID;
11017 // Conservatively set memVT to the entire set of vectors stored.
11018 unsigned NumElts = 0;
11019 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11020 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11021 if (!ArgTy->isVectorTy())
11023 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11025 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11026 Info.ptrVal = I.getArgOperand(0);
11028 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11029 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11030 Info.vol = false; // volatile stores with NEON intrinsics not supported
11031 Info.readMem = false;
11032 Info.writeMem = true;
11035 case Intrinsic::arm_ldaex:
11036 case Intrinsic::arm_ldrex: {
11037 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11038 Info.opc = ISD::INTRINSIC_W_CHAIN;
11039 Info.memVT = MVT::getVT(PtrTy->getElementType());
11040 Info.ptrVal = I.getArgOperand(0);
11042 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11044 Info.readMem = true;
11045 Info.writeMem = false;
11048 case Intrinsic::arm_stlex:
11049 case Intrinsic::arm_strex: {
11050 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11051 Info.opc = ISD::INTRINSIC_W_CHAIN;
11052 Info.memVT = MVT::getVT(PtrTy->getElementType());
11053 Info.ptrVal = I.getArgOperand(1);
11055 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11057 Info.readMem = false;
11058 Info.writeMem = true;
11061 case Intrinsic::arm_stlexd:
11062 case Intrinsic::arm_strexd: {
11063 Info.opc = ISD::INTRINSIC_W_CHAIN;
11064 Info.memVT = MVT::i64;
11065 Info.ptrVal = I.getArgOperand(2);
11069 Info.readMem = false;
11070 Info.writeMem = true;
11073 case Intrinsic::arm_ldaexd:
11074 case Intrinsic::arm_ldrexd: {
11075 Info.opc = ISD::INTRINSIC_W_CHAIN;
11076 Info.memVT = MVT::i64;
11077 Info.ptrVal = I.getArgOperand(0);
11081 Info.readMem = true;
11082 Info.writeMem = false;
11092 /// \brief Returns true if it is beneficial to convert a load of a constant
11093 /// to just the constant itself.
11094 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11096 assert(Ty->isIntegerTy());
11098 unsigned Bits = Ty->getPrimitiveSizeInBits();
11099 if (Bits == 0 || Bits > 32)
11104 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11106 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11107 ARM_MB::MemBOpt Domain) const {
11108 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11110 // First, if the target has no DMB, see what fallback we can use.
11111 if (!Subtarget->hasDataBarrier()) {
11112 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11113 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11115 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11116 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11117 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11118 Builder.getInt32(0), Builder.getInt32(7),
11119 Builder.getInt32(10), Builder.getInt32(5)};
11120 return Builder.CreateCall(MCR, args);
11122 // Instead of using barriers, atomic accesses on these subtargets use
11124 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11127 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11128 // Only a full system barrier exists in the M-class architectures.
11129 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11130 Constant *CDomain = Builder.getInt32(Domain);
11131 return Builder.CreateCall(DMB, CDomain);
11135 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11136 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11137 AtomicOrdering Ord, bool IsStore,
11138 bool IsLoad) const {
11139 if (!getInsertFencesForAtomic())
11145 llvm_unreachable("Invalid fence: unordered/non-atomic");
11148 return nullptr; // Nothing to do
11149 case SequentiallyConsistent:
11151 return nullptr; // Nothing to do
11154 case AcquireRelease:
11155 if (Subtarget->isSwift())
11156 return makeDMB(Builder, ARM_MB::ISHST);
11157 // FIXME: add a comment with a link to documentation justifying this.
11159 return makeDMB(Builder, ARM_MB::ISH);
11161 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11164 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11165 AtomicOrdering Ord, bool IsStore,
11166 bool IsLoad) const {
11167 if (!getInsertFencesForAtomic())
11173 llvm_unreachable("Invalid fence: unordered/not-atomic");
11176 return nullptr; // Nothing to do
11178 case AcquireRelease:
11179 case SequentiallyConsistent:
11180 return makeDMB(Builder, ARM_MB::ISH);
11182 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11185 // Loads and stores less than 64-bits are already atomic; ones above that
11186 // are doomed anyway, so defer to the default libcall and blame the OS when
11187 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11188 // anything for those.
11189 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11190 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11191 return (Size == 64) && !Subtarget->isMClass();
11194 // Loads and stores less than 64-bits are already atomic; ones above that
11195 // are doomed anyway, so defer to the default libcall and blame the OS when
11196 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11197 // anything for those.
11198 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11199 // guarantee, see DDI0406C ARM architecture reference manual,
11200 // sections A8.8.72-74 LDRD)
11201 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11202 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11203 return (Size == 64) && !Subtarget->isMClass();
11206 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11207 // and up to 64 bits on the non-M profiles
11208 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11209 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11210 return Size <= (Subtarget->isMClass() ? 32U : 64U);
11213 // This has so far only been implemented for MachO.
11214 bool ARMTargetLowering::useLoadStackGuardNode() const {
11215 return Subtarget->isTargetMachO();
11218 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11219 unsigned &Cost) const {
11220 // If we do not have NEON, vector types are not natively supported.
11221 if (!Subtarget->hasNEON())
11224 // Floating point values and vector values map to the same register file.
11225 // Therefore, althought we could do a store extract of a vector type, this is
11226 // better to leave at float as we have more freedom in the addressing mode for
11228 if (VectorTy->isFPOrFPVectorTy())
11231 // If the index is unknown at compile time, this is very expensive to lower
11232 // and it is not possible to combine the store with the extract.
11233 if (!isa<ConstantInt>(Idx))
11236 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11237 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11238 // We can do a store + vector extract on any vector that fits perfectly in a D
11240 if (BitWidth == 64 || BitWidth == 128) {
11247 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11248 AtomicOrdering Ord) const {
11249 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11250 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11251 bool IsAcquire = isAtLeastAcquire(Ord);
11253 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11254 // intrinsic must return {i32, i32} and we have to recombine them into a
11255 // single i64 here.
11256 if (ValTy->getPrimitiveSizeInBits() == 64) {
11257 Intrinsic::ID Int =
11258 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11259 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11261 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11262 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11264 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11265 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11266 if (!Subtarget->isLittle())
11267 std::swap (Lo, Hi);
11268 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11269 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11270 return Builder.CreateOr(
11271 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11274 Type *Tys[] = { Addr->getType() };
11275 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11276 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11278 return Builder.CreateTruncOrBitCast(
11279 Builder.CreateCall(Ldrex, Addr),
11280 cast<PointerType>(Addr->getType())->getElementType());
11283 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11285 AtomicOrdering Ord) const {
11286 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11287 bool IsRelease = isAtLeastRelease(Ord);
11289 // Since the intrinsics must have legal type, the i64 intrinsics take two
11290 // parameters: "i32, i32". We must marshal Val into the appropriate form
11291 // before the call.
11292 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11293 Intrinsic::ID Int =
11294 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11295 Function *Strex = Intrinsic::getDeclaration(M, Int);
11296 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11298 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11299 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11300 if (!Subtarget->isLittle())
11301 std::swap (Lo, Hi);
11302 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11303 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11306 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11307 Type *Tys[] = { Addr->getType() };
11308 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11310 return Builder.CreateCall2(
11311 Strex, Builder.CreateZExtOrBitCast(
11312 Val, Strex->getFunctionType()->getParamType(0)),
11324 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11325 uint64_t &Members) {
11326 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11327 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11328 uint64_t SubMembers = 0;
11329 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11331 Members += SubMembers;
11333 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11334 uint64_t SubMembers = 0;
11335 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11337 Members += SubMembers * AT->getNumElements();
11338 } else if (Ty->isFloatTy()) {
11339 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11343 } else if (Ty->isDoubleTy()) {
11344 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11348 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11355 return VT->getBitWidth() == 64;
11357 return VT->getBitWidth() == 128;
11359 switch (VT->getBitWidth()) {
11372 return (Members > 0 && Members <= 4);
11375 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11376 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11377 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11378 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11379 CallingConv::ARM_AAPCS_VFP)
11382 HABaseType Base = HA_UNKNOWN;
11383 uint64_t Members = 0;
11384 bool result = isHomogeneousAggregate(Ty, Base, Members);
11385 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());