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/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "arm-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
64 EnableARMLongCalls("arm-long-calls", cl::Hidden,
65 cl::desc("Generate calls via indirect call instructions"),
69 ARMInterworking("arm-interworking", cl::Hidden,
70 cl::desc("Enable / disable ARM interworking (for debugging only)"),
74 class ARMCCState : public CCState {
76 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
77 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
79 : CCState(CC, isVarArg, MF, locs, C) {
80 assert(((PC == Call) || (PC == Prologue)) &&
81 "ARMCCState users must specify whether their context is call"
82 "or prologue generation.");
88 // The APCS parameter registers.
89 static const MCPhysReg GPRArgRegs[] = {
90 ARM::R0, ARM::R1, ARM::R2, ARM::R3
93 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
94 MVT PromotedBitwiseVT) {
95 if (VT != PromotedLdStVT) {
96 setOperationAction(ISD::LOAD, VT, Promote);
97 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
99 setOperationAction(ISD::STORE, VT, Promote);
100 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
103 MVT ElemTy = VT.getVectorElementType();
104 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
105 setOperationAction(ISD::SETCC, VT, Custom);
106 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
107 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
108 if (ElemTy == MVT::i32) {
109 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
110 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
112 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
114 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
115 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
117 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
119 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
120 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
121 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
122 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
123 setOperationAction(ISD::SELECT, VT, Expand);
124 setOperationAction(ISD::SELECT_CC, VT, Expand);
125 setOperationAction(ISD::VSELECT, VT, Expand);
126 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
127 if (VT.isInteger()) {
128 setOperationAction(ISD::SHL, VT, Custom);
129 setOperationAction(ISD::SRA, VT, Custom);
130 setOperationAction(ISD::SRL, VT, Custom);
133 // Promote all bit-wise operations.
134 if (VT.isInteger() && VT != PromotedBitwiseVT) {
135 setOperationAction(ISD::AND, VT, Promote);
136 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
137 setOperationAction(ISD::OR, VT, Promote);
138 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
139 setOperationAction(ISD::XOR, VT, Promote);
140 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
143 // Neon does not support vector divide/remainder operations.
144 setOperationAction(ISD::SDIV, VT, Expand);
145 setOperationAction(ISD::UDIV, VT, Expand);
146 setOperationAction(ISD::FDIV, VT, Expand);
147 setOperationAction(ISD::SREM, VT, Expand);
148 setOperationAction(ISD::UREM, VT, Expand);
149 setOperationAction(ISD::FREM, VT, Expand);
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPRRegClass);
154 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158 addRegisterClass(VT, &ARM::DPairRegClass);
159 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163 const ARMSubtarget &STI)
164 : TargetLowering(TM), Subtarget(&STI) {
165 RegInfo = Subtarget->getRegisterInfo();
166 Itins = Subtarget->getInstrItineraryData();
168 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
170 if (Subtarget->isTargetMachO()) {
171 // Uses VFP for Thumb libfuncs if available.
172 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173 Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174 // Single-precision floating-point arithmetic.
175 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
180 // Double-precision floating-point arithmetic.
181 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
186 // Single-precision comparisons.
187 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
194 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
196 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
205 // Double-precision comparisons.
206 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
213 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
215 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
224 // Floating-point to integer conversions.
225 // i64 conversions are done via library routines even when generating VFP
226 // instructions, so use the same ones.
227 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
232 // Conversions between floating types.
233 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
236 // Integer to floating-point conversions.
237 // i64 conversions are done via library routines even when generating VFP
238 // instructions, so use the same ones.
239 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240 // e.g., __floatunsidf vs. __floatunssidfvfp.
241 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
248 // These libcalls are not available in 32-bit.
249 setLibcallName(RTLIB::SHL_I128, nullptr);
250 setLibcallName(RTLIB::SRL_I128, nullptr);
251 setLibcallName(RTLIB::SRA_I128, nullptr);
253 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254 !Subtarget->isTargetWindows()) {
255 static const struct {
256 const RTLIB::Libcall Op;
257 const char * const Name;
258 const CallingConv::ID CC;
259 const ISD::CondCode Cond;
261 // Double-precision floating-point arithmetic helper functions
262 // RTABI chapter 4.1.2, Table 2
263 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
264 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
266 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 // Double-precision floating-point comparison helper functions
269 // RTABI chapter 4.1.2, Table 3
270 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
272 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
279 // Single-precision floating-point arithmetic helper functions
280 // RTABI chapter 4.1.2, Table 4
281 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
282 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
284 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 // Single-precision floating-point comparison helper functions
287 // RTABI chapter 4.1.2, Table 5
288 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
290 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
297 // Floating-point to integer conversions.
298 // RTABI chapter 4.1.2, Table 6
299 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 // Conversions between floating types.
309 // RTABI chapter 4.1.2, Table 7
310 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 // Integer to floating-point conversions.
315 // RTABI chapter 4.1.2, Table 8
316 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 // Long long helper functions
326 // RTABI chapter 4.2, Table 9
327 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 // Integer division functions
333 // RTABI chapter 4.3.1
334 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 // RTABI chapter 4.3.4
345 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 for (const auto &LC : LibraryCalls) {
351 setLibcallName(LC.Op, LC.Name);
352 setLibcallCallingConv(LC.Op, LC.CC);
353 if (LC.Cond != ISD::SETCC_INVALID)
354 setCmpLibcallCC(LC.Op, LC.Cond);
358 if (Subtarget->isTargetWindows()) {
359 static const struct {
360 const RTLIB::Libcall Op;
361 const char * const Name;
362 const CallingConv::ID CC;
364 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
374 for (const auto &LC : LibraryCalls) {
375 setLibcallName(LC.Op, LC.Name);
376 setLibcallCallingConv(LC.Op, LC.CC);
380 // Use divmod compiler-rt calls for iOS 5.0 and later.
381 if (Subtarget->getTargetTriple().isiOS() &&
382 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
383 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
384 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
387 // The half <-> float conversion functions are always soft-float, but are
388 // needed for some targets which use a hard-float calling convention by
390 if (Subtarget->isAAPCS_ABI()) {
391 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
395 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
396 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
397 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
400 if (Subtarget->isThumb1Only())
401 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
403 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
404 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
405 !Subtarget->isThumb1Only()) {
406 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
407 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
410 for (MVT VT : MVT::vector_valuetypes()) {
411 for (MVT InnerVT : MVT::vector_valuetypes()) {
412 setTruncStoreAction(VT, InnerVT, Expand);
413 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
414 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
415 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
418 setOperationAction(ISD::MULHS, VT, Expand);
419 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
420 setOperationAction(ISD::MULHU, VT, Expand);
421 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
423 setOperationAction(ISD::BSWAP, VT, Expand);
426 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
427 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
429 setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
430 setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
432 if (Subtarget->hasNEON()) {
433 addDRTypeForNEON(MVT::v2f32);
434 addDRTypeForNEON(MVT::v8i8);
435 addDRTypeForNEON(MVT::v4i16);
436 addDRTypeForNEON(MVT::v2i32);
437 addDRTypeForNEON(MVT::v1i64);
439 addQRTypeForNEON(MVT::v4f32);
440 addQRTypeForNEON(MVT::v2f64);
441 addQRTypeForNEON(MVT::v16i8);
442 addQRTypeForNEON(MVT::v8i16);
443 addQRTypeForNEON(MVT::v4i32);
444 addQRTypeForNEON(MVT::v2i64);
446 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
447 // neither Neon nor VFP support any arithmetic operations on it.
448 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
449 // supported for v4f32.
450 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
451 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
452 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
453 // FIXME: Code duplication: FDIV and FREM are expanded always, see
454 // ARMTargetLowering::addTypeForNEON method for details.
455 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
456 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
457 // FIXME: Create unittest.
458 // In another words, find a way when "copysign" appears in DAG with vector
460 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
461 // FIXME: Code duplication: SETCC has custom operation action, see
462 // ARMTargetLowering::addTypeForNEON method for details.
463 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
464 // FIXME: Create unittest for FNEG and for FABS.
465 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
466 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
467 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
468 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
469 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
470 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
471 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
472 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
473 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
474 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
475 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
476 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
477 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
478 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
479 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
480 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
481 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
482 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
483 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
485 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
486 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
487 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
488 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
489 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
490 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
491 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
492 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
493 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
494 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
495 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
496 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
497 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
498 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
499 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
501 // Mark v2f32 intrinsics.
502 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
503 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
504 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
505 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
506 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
507 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
508 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
509 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
510 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
511 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
512 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
513 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
514 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
515 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
516 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
518 // Neon does not support some operations on v1i64 and v2i64 types.
519 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
520 // Custom handling for some quad-vector types to detect VMULL.
521 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
523 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
524 // Custom handling for some vector types to avoid expensive expansions
525 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
526 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
527 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
528 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
529 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
530 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
531 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
532 // a destination type that is wider than the source, and nor does
533 // it have a FP_TO_[SU]INT instruction with a narrower destination than
535 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
537 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
538 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
540 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
541 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
543 // NEON does not have single instruction CTPOP for vectors with element
544 // types wider than 8-bits. However, custom lowering can leverage the
545 // v8i8/v16i8 vcnt instruction.
546 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
547 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
548 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
549 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
551 // NEON only has FMA instructions as of VFP4.
552 if (!Subtarget->hasVFP4()) {
553 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
554 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
557 setTargetDAGCombine(ISD::INTRINSIC_VOID);
558 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
559 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
560 setTargetDAGCombine(ISD::SHL);
561 setTargetDAGCombine(ISD::SRL);
562 setTargetDAGCombine(ISD::SRA);
563 setTargetDAGCombine(ISD::SIGN_EXTEND);
564 setTargetDAGCombine(ISD::ZERO_EXTEND);
565 setTargetDAGCombine(ISD::ANY_EXTEND);
566 setTargetDAGCombine(ISD::SELECT_CC);
567 setTargetDAGCombine(ISD::BUILD_VECTOR);
568 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
569 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570 setTargetDAGCombine(ISD::STORE);
571 setTargetDAGCombine(ISD::FP_TO_SINT);
572 setTargetDAGCombine(ISD::FP_TO_UINT);
573 setTargetDAGCombine(ISD::FDIV);
574 setTargetDAGCombine(ISD::LOAD);
576 // It is legal to extload from v4i8 to v4i16 or v4i32.
577 for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
579 for (MVT VT : MVT::integer_vector_valuetypes()) {
580 setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
581 setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
582 setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
587 // ARM and Thumb2 support UMLAL/SMLAL.
588 if (!Subtarget->isThumb1Only())
589 setTargetDAGCombine(ISD::ADDC);
591 if (Subtarget->isFPOnlySP()) {
592 // When targetting a floating-point unit with only single-precision
593 // operations, f64 is legal for the few double-precision instructions which
594 // are present However, no double-precision operations other than moves,
595 // loads and stores are provided by the hardware.
596 setOperationAction(ISD::FADD, MVT::f64, Expand);
597 setOperationAction(ISD::FSUB, MVT::f64, Expand);
598 setOperationAction(ISD::FMUL, MVT::f64, Expand);
599 setOperationAction(ISD::FMA, MVT::f64, Expand);
600 setOperationAction(ISD::FDIV, MVT::f64, Expand);
601 setOperationAction(ISD::FREM, MVT::f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
603 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
604 setOperationAction(ISD::FNEG, MVT::f64, Expand);
605 setOperationAction(ISD::FABS, MVT::f64, Expand);
606 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
607 setOperationAction(ISD::FSIN, MVT::f64, Expand);
608 setOperationAction(ISD::FCOS, MVT::f64, Expand);
609 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
610 setOperationAction(ISD::FPOW, MVT::f64, Expand);
611 setOperationAction(ISD::FLOG, MVT::f64, Expand);
612 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
613 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
614 setOperationAction(ISD::FEXP, MVT::f64, Expand);
615 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
616 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
617 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
618 setOperationAction(ISD::FRINT, MVT::f64, Expand);
619 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
620 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
621 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
622 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
623 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
624 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
625 setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
626 setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
627 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
628 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
631 computeRegisterProperties(Subtarget->getRegisterInfo());
633 // ARM does not have floating-point extending loads.
634 for (MVT VT : MVT::fp_valuetypes()) {
635 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
636 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
639 // ... or truncating stores
640 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
641 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
642 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
644 // ARM does not have i1 sign extending load.
645 for (MVT VT : MVT::integer_valuetypes())
646 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
648 // ARM supports all 4 flavors of integer indexed load / store.
649 if (!Subtarget->isThumb1Only()) {
650 for (unsigned im = (unsigned)ISD::PRE_INC;
651 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
652 setIndexedLoadAction(im, MVT::i1, Legal);
653 setIndexedLoadAction(im, MVT::i8, Legal);
654 setIndexedLoadAction(im, MVT::i16, Legal);
655 setIndexedLoadAction(im, MVT::i32, Legal);
656 setIndexedStoreAction(im, MVT::i1, Legal);
657 setIndexedStoreAction(im, MVT::i8, Legal);
658 setIndexedStoreAction(im, MVT::i16, Legal);
659 setIndexedStoreAction(im, MVT::i32, Legal);
663 setOperationAction(ISD::SADDO, MVT::i32, Custom);
664 setOperationAction(ISD::UADDO, MVT::i32, Custom);
665 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
666 setOperationAction(ISD::USUBO, MVT::i32, Custom);
668 // i64 operation support.
669 setOperationAction(ISD::MUL, MVT::i64, Expand);
670 setOperationAction(ISD::MULHU, MVT::i32, Expand);
671 if (Subtarget->isThumb1Only()) {
672 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
673 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
675 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
676 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
677 setOperationAction(ISD::MULHS, MVT::i32, Expand);
679 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
680 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
681 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
682 setOperationAction(ISD::SRL, MVT::i64, Custom);
683 setOperationAction(ISD::SRA, MVT::i64, Custom);
685 if (!Subtarget->isThumb1Only()) {
686 // FIXME: We should do this for Thumb1 as well.
687 setOperationAction(ISD::ADDC, MVT::i32, Custom);
688 setOperationAction(ISD::ADDE, MVT::i32, Custom);
689 setOperationAction(ISD::SUBC, MVT::i32, Custom);
690 setOperationAction(ISD::SUBE, MVT::i32, Custom);
693 // ARM does not have ROTL.
694 setOperationAction(ISD::ROTL, MVT::i32, Expand);
695 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
696 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
697 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
698 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
700 // These just redirect to CTTZ and CTLZ on ARM.
701 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
702 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
704 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
706 // Only ARMv6 has BSWAP.
707 if (!Subtarget->hasV6Ops())
708 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
710 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
711 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
712 // These are expanded into libcalls if the cpu doesn't have HW divider.
713 setOperationAction(ISD::SDIV, MVT::i32, Expand);
714 setOperationAction(ISD::UDIV, MVT::i32, Expand);
717 // FIXME: Also set divmod for SREM on EABI
718 setOperationAction(ISD::SREM, MVT::i32, Expand);
719 setOperationAction(ISD::UREM, MVT::i32, Expand);
720 // Register based DivRem for AEABI (RTABI 4.2)
721 if (Subtarget->isTargetAEABI()) {
722 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
723 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
724 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
725 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
726 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
727 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
728 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
729 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
731 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
733 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
735 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
736 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
737 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
738 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
740 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
741 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
743 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
744 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
747 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
748 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
749 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
750 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
751 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
753 setOperationAction(ISD::TRAP, MVT::Other, Legal);
755 // Use the default implementation.
756 setOperationAction(ISD::VASTART, MVT::Other, Custom);
757 setOperationAction(ISD::VAARG, MVT::Other, Expand);
758 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
759 setOperationAction(ISD::VAEND, MVT::Other, Expand);
760 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
761 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
763 if (!Subtarget->isTargetMachO()) {
764 // Non-MachO platforms may return values in these registers via the
765 // personality function.
766 setExceptionPointerRegister(ARM::R0);
767 setExceptionSelectorRegister(ARM::R1);
770 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
771 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
773 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
775 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
776 // the default expansion. If we are targeting a single threaded system,
777 // then set them all for expand so we can lower them later into their
779 if (TM.Options.ThreadModel == ThreadModel::Single)
780 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
781 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
782 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
783 // to ldrex/strex loops already.
784 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
786 // On v8, we have particularly efficient implementations of atomic fences
787 // if they can be combined with nearby atomic loads and stores.
788 if (!Subtarget->hasV8Ops()) {
789 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
790 setInsertFencesForAtomic(true);
793 // If there's anything we can use as a barrier, go through custom lowering
795 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
796 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
798 // Set them all for expansion, which will force libcalls.
799 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
805 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
806 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
807 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
808 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
809 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
810 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
811 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
812 // Unordered/Monotonic case.
813 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
814 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
817 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
819 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
820 if (!Subtarget->hasV6Ops()) {
821 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
822 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
824 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
826 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
827 !Subtarget->isThumb1Only()) {
828 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
829 // iff target supports vfp2.
830 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
831 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
834 // We want to custom lower some of our intrinsics.
835 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
836 if (Subtarget->isTargetDarwin()) {
837 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
838 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
839 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
842 setOperationAction(ISD::SETCC, MVT::i32, Expand);
843 setOperationAction(ISD::SETCC, MVT::f32, Expand);
844 setOperationAction(ISD::SETCC, MVT::f64, Expand);
845 setOperationAction(ISD::SELECT, MVT::i32, Custom);
846 setOperationAction(ISD::SELECT, MVT::f32, Custom);
847 setOperationAction(ISD::SELECT, MVT::f64, Custom);
848 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
849 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
850 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
852 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
853 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
854 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
855 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
856 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
858 // We don't support sin/cos/fmod/copysign/pow
859 setOperationAction(ISD::FSIN, MVT::f64, Expand);
860 setOperationAction(ISD::FSIN, MVT::f32, Expand);
861 setOperationAction(ISD::FCOS, MVT::f32, Expand);
862 setOperationAction(ISD::FCOS, MVT::f64, Expand);
863 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
864 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
865 setOperationAction(ISD::FREM, MVT::f64, Expand);
866 setOperationAction(ISD::FREM, MVT::f32, Expand);
867 if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
868 !Subtarget->isThumb1Only()) {
869 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
870 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
872 setOperationAction(ISD::FPOW, MVT::f64, Expand);
873 setOperationAction(ISD::FPOW, MVT::f32, Expand);
875 if (!Subtarget->hasVFP4()) {
876 setOperationAction(ISD::FMA, MVT::f64, Expand);
877 setOperationAction(ISD::FMA, MVT::f32, Expand);
880 // Various VFP goodness
881 if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
882 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
883 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
884 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
885 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
888 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
889 if (!Subtarget->hasFP16()) {
890 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
891 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
895 // Combine sin / cos into one node or libcall if possible.
896 if (Subtarget->hasSinCos()) {
897 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
898 setLibcallName(RTLIB::SINCOS_F64, "sincos");
899 if (Subtarget->getTargetTriple().isiOS()) {
900 // For iOS, we don't want to the normal expansion of a libcall to
901 // sincos. We want to issue a libcall to __sincos_stret.
902 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
903 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
907 // FP-ARMv8 implements a lot of rounding-like FP operations.
908 if (Subtarget->hasFPARMv8()) {
909 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
910 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
911 setOperationAction(ISD::FROUND, MVT::f32, Legal);
912 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
913 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
914 setOperationAction(ISD::FRINT, MVT::f32, Legal);
915 if (!Subtarget->isFPOnlySP()) {
916 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
917 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
918 setOperationAction(ISD::FROUND, MVT::f64, Legal);
919 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
920 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
921 setOperationAction(ISD::FRINT, MVT::f64, Legal);
924 // We have target-specific dag combine patterns for the following nodes:
925 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
926 setTargetDAGCombine(ISD::ADD);
927 setTargetDAGCombine(ISD::SUB);
928 setTargetDAGCombine(ISD::MUL);
929 setTargetDAGCombine(ISD::AND);
930 setTargetDAGCombine(ISD::OR);
931 setTargetDAGCombine(ISD::XOR);
933 if (Subtarget->hasV6Ops())
934 setTargetDAGCombine(ISD::SRL);
936 setStackPointerRegisterToSaveRestore(ARM::SP);
938 if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
939 !Subtarget->hasVFP2())
940 setSchedulingPreference(Sched::RegPressure);
942 setSchedulingPreference(Sched::Hybrid);
944 //// temporary - rewrite interface to use type
945 MaxStoresPerMemset = 8;
946 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
947 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
948 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
950 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
952 // On ARM arguments smaller than 4 bytes are extended, so all arguments
953 // are at least 4 bytes aligned.
954 setMinStackArgumentAlignment(4);
956 // Prefer likely predicted branches to selects on out-of-order cores.
957 PredictableSelectIsExpensive = Subtarget->isLikeA9();
959 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
962 bool ARMTargetLowering::useSoftFloat() const {
963 return Subtarget->useSoftFloat();
966 // FIXME: It might make sense to define the representative register class as the
967 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
968 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
969 // SPR's representative would be DPR_VFP2. This should work well if register
970 // pressure tracking were modified such that a register use would increment the
971 // pressure of the register class's representative and all of it's super
972 // classes' representatives transitively. We have not implemented this because
973 // of the difficulty prior to coalescing of modeling operand register classes
974 // due to the common occurrence of cross class copies and subregister insertions
976 std::pair<const TargetRegisterClass *, uint8_t>
977 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
979 const TargetRegisterClass *RRC = nullptr;
981 switch (VT.SimpleTy) {
983 return TargetLowering::findRepresentativeClass(TRI, VT);
984 // Use DPR as representative register class for all floating point
985 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
986 // the cost is 1 for both f32 and f64.
987 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
988 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
989 RRC = &ARM::DPRRegClass;
990 // When NEON is used for SP, only half of the register file is available
991 // because operations that define both SP and DP results will be constrained
992 // to the VFP2 class (D0-D15). We currently model this constraint prior to
993 // coalescing by double-counting the SP regs. See the FIXME above.
994 if (Subtarget->useNEONForSinglePrecisionFP())
997 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
998 case MVT::v4f32: case MVT::v2f64:
999 RRC = &ARM::DPRRegClass;
1003 RRC = &ARM::DPRRegClass;
1007 RRC = &ARM::DPRRegClass;
1011 return std::make_pair(RRC, Cost);
1014 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1015 switch ((ARMISD::NodeType)Opcode) {
1016 case ARMISD::FIRST_NUMBER: break;
1017 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1018 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1019 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1020 case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1021 case ARMISD::CALL: return "ARMISD::CALL";
1022 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1023 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1024 case ARMISD::tCALL: return "ARMISD::tCALL";
1025 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1026 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1027 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1028 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1029 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1030 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1031 case ARMISD::CMP: return "ARMISD::CMP";
1032 case ARMISD::CMN: return "ARMISD::CMN";
1033 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1034 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1035 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1036 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1037 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1039 case ARMISD::CMOV: return "ARMISD::CMOV";
1041 case ARMISD::RBIT: return "ARMISD::RBIT";
1043 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1044 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1045 case ARMISD::RRX: return "ARMISD::RRX";
1047 case ARMISD::ADDC: return "ARMISD::ADDC";
1048 case ARMISD::ADDE: return "ARMISD::ADDE";
1049 case ARMISD::SUBC: return "ARMISD::SUBC";
1050 case ARMISD::SUBE: return "ARMISD::SUBE";
1052 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1053 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1055 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1056 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1058 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1060 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1062 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1064 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1066 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1068 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1070 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1071 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1072 case ARMISD::VCGE: return "ARMISD::VCGE";
1073 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1074 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1075 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1076 case ARMISD::VCGT: return "ARMISD::VCGT";
1077 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1078 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1079 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1080 case ARMISD::VTST: return "ARMISD::VTST";
1082 case ARMISD::VSHL: return "ARMISD::VSHL";
1083 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1084 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1085 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1086 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1087 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1088 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1089 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1090 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1091 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1092 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1093 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1094 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1095 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1096 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1097 case ARMISD::VSLI: return "ARMISD::VSLI";
1098 case ARMISD::VSRI: return "ARMISD::VSRI";
1099 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1100 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1101 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1102 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1103 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1104 case ARMISD::VDUP: return "ARMISD::VDUP";
1105 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1106 case ARMISD::VEXT: return "ARMISD::VEXT";
1107 case ARMISD::VREV64: return "ARMISD::VREV64";
1108 case ARMISD::VREV32: return "ARMISD::VREV32";
1109 case ARMISD::VREV16: return "ARMISD::VREV16";
1110 case ARMISD::VZIP: return "ARMISD::VZIP";
1111 case ARMISD::VUZP: return "ARMISD::VUZP";
1112 case ARMISD::VTRN: return "ARMISD::VTRN";
1113 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1114 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1115 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1116 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1117 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1118 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1119 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1120 case ARMISD::FMAX: return "ARMISD::FMAX";
1121 case ARMISD::FMIN: return "ARMISD::FMIN";
1122 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1123 case ARMISD::VMINNM: return "ARMISD::VMIN";
1124 case ARMISD::BFI: return "ARMISD::BFI";
1125 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1126 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1127 case ARMISD::VBSL: return "ARMISD::VBSL";
1128 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1129 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1130 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1131 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1132 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1133 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1134 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1135 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1136 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1137 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1138 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1139 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1140 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1141 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1142 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1143 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1144 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1145 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1146 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1147 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1152 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1153 if (!VT.isVector()) return getPointerTy();
1154 return VT.changeVectorElementTypeToInteger();
1157 /// getRegClassFor - Return the register class that should be used for the
1158 /// specified value type.
1159 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1160 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1161 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1162 // load / store 4 to 8 consecutive D registers.
1163 if (Subtarget->hasNEON()) {
1164 if (VT == MVT::v4i64)
1165 return &ARM::QQPRRegClass;
1166 if (VT == MVT::v8i64)
1167 return &ARM::QQQQPRRegClass;
1169 return TargetLowering::getRegClassFor(VT);
1172 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1173 // source/dest is aligned and the copy size is large enough. We therefore want
1174 // to align such objects passed to memory intrinsics.
1175 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1176 unsigned &PrefAlign) const {
1177 if (!isa<MemIntrinsic>(CI))
1180 // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1181 // cycle faster than 4-byte aligned LDM.
1182 PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1186 // Create a fast isel object.
1188 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1189 const TargetLibraryInfo *libInfo) const {
1190 return ARM::createFastISel(funcInfo, libInfo);
1193 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1194 unsigned NumVals = N->getNumValues();
1196 return Sched::RegPressure;
1198 for (unsigned i = 0; i != NumVals; ++i) {
1199 EVT VT = N->getValueType(i);
1200 if (VT == MVT::Glue || VT == MVT::Other)
1202 if (VT.isFloatingPoint() || VT.isVector())
1206 if (!N->isMachineOpcode())
1207 return Sched::RegPressure;
1209 // Load are scheduled for latency even if there instruction itinerary
1210 // is not available.
1211 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1212 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1214 if (MCID.getNumDefs() == 0)
1215 return Sched::RegPressure;
1216 if (!Itins->isEmpty() &&
1217 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1220 return Sched::RegPressure;
1223 //===----------------------------------------------------------------------===//
1225 //===----------------------------------------------------------------------===//
1227 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1228 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1230 default: llvm_unreachable("Unknown condition code!");
1231 case ISD::SETNE: return ARMCC::NE;
1232 case ISD::SETEQ: return ARMCC::EQ;
1233 case ISD::SETGT: return ARMCC::GT;
1234 case ISD::SETGE: return ARMCC::GE;
1235 case ISD::SETLT: return ARMCC::LT;
1236 case ISD::SETLE: return ARMCC::LE;
1237 case ISD::SETUGT: return ARMCC::HI;
1238 case ISD::SETUGE: return ARMCC::HS;
1239 case ISD::SETULT: return ARMCC::LO;
1240 case ISD::SETULE: return ARMCC::LS;
1244 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1245 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1246 ARMCC::CondCodes &CondCode2) {
1247 CondCode2 = ARMCC::AL;
1249 default: llvm_unreachable("Unknown FP condition!");
1251 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1253 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1255 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1256 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1257 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1258 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1259 case ISD::SETO: CondCode = ARMCC::VC; break;
1260 case ISD::SETUO: CondCode = ARMCC::VS; break;
1261 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1262 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1263 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1265 case ISD::SETULT: CondCode = ARMCC::LT; break;
1267 case ISD::SETULE: CondCode = ARMCC::LE; break;
1269 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1273 //===----------------------------------------------------------------------===//
1274 // Calling Convention Implementation
1275 //===----------------------------------------------------------------------===//
1277 #include "ARMGenCallingConv.inc"
1279 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1280 /// account presence of floating point hardware and calling convention
1281 /// limitations, such as support for variadic functions.
1283 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1284 bool isVarArg) const {
1287 llvm_unreachable("Unsupported calling convention");
1288 case CallingConv::ARM_AAPCS:
1289 case CallingConv::ARM_APCS:
1290 case CallingConv::GHC:
1292 case CallingConv::ARM_AAPCS_VFP:
1293 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1294 case CallingConv::C:
1295 if (!Subtarget->isAAPCS_ABI())
1296 return CallingConv::ARM_APCS;
1297 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1298 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1300 return CallingConv::ARM_AAPCS_VFP;
1302 return CallingConv::ARM_AAPCS;
1303 case CallingConv::Fast:
1304 if (!Subtarget->isAAPCS_ABI()) {
1305 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1306 return CallingConv::Fast;
1307 return CallingConv::ARM_APCS;
1308 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1309 return CallingConv::ARM_AAPCS_VFP;
1311 return CallingConv::ARM_AAPCS;
1315 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1316 /// CallingConvention.
1317 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1319 bool isVarArg) const {
1320 switch (getEffectiveCallingConv(CC, isVarArg)) {
1322 llvm_unreachable("Unsupported calling convention");
1323 case CallingConv::ARM_APCS:
1324 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1325 case CallingConv::ARM_AAPCS:
1326 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1327 case CallingConv::ARM_AAPCS_VFP:
1328 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1329 case CallingConv::Fast:
1330 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1331 case CallingConv::GHC:
1332 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1336 /// LowerCallResult - Lower the result values of a call into the
1337 /// appropriate copies out of appropriate physical registers.
1339 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1340 CallingConv::ID CallConv, bool isVarArg,
1341 const SmallVectorImpl<ISD::InputArg> &Ins,
1342 SDLoc dl, SelectionDAG &DAG,
1343 SmallVectorImpl<SDValue> &InVals,
1344 bool isThisReturn, SDValue ThisVal) const {
1346 // Assign locations to each value returned by this call.
1347 SmallVector<CCValAssign, 16> RVLocs;
1348 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1349 *DAG.getContext(), Call);
1350 CCInfo.AnalyzeCallResult(Ins,
1351 CCAssignFnForNode(CallConv, /* Return*/ true,
1354 // Copy all of the result registers out of their specified physreg.
1355 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1356 CCValAssign VA = RVLocs[i];
1358 // Pass 'this' value directly from the argument to return value, to avoid
1359 // reg unit interference
1360 if (i == 0 && isThisReturn) {
1361 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1362 "unexpected return calling convention register assignment");
1363 InVals.push_back(ThisVal);
1368 if (VA.needsCustom()) {
1369 // Handle f64 or half of a v2f64.
1370 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1372 Chain = Lo.getValue(1);
1373 InFlag = Lo.getValue(2);
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1377 Chain = Hi.getValue(1);
1378 InFlag = Hi.getValue(2);
1379 if (!Subtarget->isLittle())
1381 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1383 if (VA.getLocVT() == MVT::v2f64) {
1384 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1385 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(0, dl, MVT::i32));
1388 VA = RVLocs[++i]; // skip ahead to next loc
1389 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1390 Chain = Lo.getValue(1);
1391 InFlag = Lo.getValue(2);
1392 VA = RVLocs[++i]; // skip ahead to next loc
1393 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1394 Chain = Hi.getValue(1);
1395 InFlag = Hi.getValue(2);
1396 if (!Subtarget->isLittle())
1398 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1399 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1400 DAG.getConstant(1, dl, MVT::i32));
1403 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1405 Chain = Val.getValue(1);
1406 InFlag = Val.getValue(2);
1409 switch (VA.getLocInfo()) {
1410 default: llvm_unreachable("Unknown loc info!");
1411 case CCValAssign::Full: break;
1412 case CCValAssign::BCvt:
1413 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1417 InVals.push_back(Val);
1423 /// LowerMemOpCallTo - Store the argument to the stack.
1425 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1426 SDValue StackPtr, SDValue Arg,
1427 SDLoc dl, SelectionDAG &DAG,
1428 const CCValAssign &VA,
1429 ISD::ArgFlagsTy Flags) const {
1430 unsigned LocMemOffset = VA.getLocMemOffset();
1431 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1432 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1433 return DAG.getStore(Chain, dl, Arg, PtrOff,
1434 MachinePointerInfo::getStack(LocMemOffset),
1438 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1439 SDValue Chain, SDValue &Arg,
1440 RegsToPassVector &RegsToPass,
1441 CCValAssign &VA, CCValAssign &NextVA,
1443 SmallVectorImpl<SDValue> &MemOpChains,
1444 ISD::ArgFlagsTy Flags) const {
1446 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1447 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1448 unsigned id = Subtarget->isLittle() ? 0 : 1;
1449 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1451 if (NextVA.isRegLoc())
1452 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1454 assert(NextVA.isMemLoc());
1455 if (!StackPtr.getNode())
1456 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1458 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1464 /// LowerCall - Lowering a call into a callseq_start <-
1465 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1468 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1469 SmallVectorImpl<SDValue> &InVals) const {
1470 SelectionDAG &DAG = CLI.DAG;
1472 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1473 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1474 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1475 SDValue Chain = CLI.Chain;
1476 SDValue Callee = CLI.Callee;
1477 bool &isTailCall = CLI.IsTailCall;
1478 CallingConv::ID CallConv = CLI.CallConv;
1479 bool doesNotRet = CLI.DoesNotReturn;
1480 bool isVarArg = CLI.IsVarArg;
1482 MachineFunction &MF = DAG.getMachineFunction();
1483 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1484 bool isThisReturn = false;
1485 bool isSibCall = false;
1486 auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1488 // Disable tail calls if they're not supported.
1489 if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1493 // Check if it's really possible to do a tail call.
1494 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1495 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1496 Outs, OutVals, Ins, DAG);
1497 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1498 report_fatal_error("failed to perform tail call elimination on a call "
1499 "site marked musttail");
1500 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1501 // detected sibcalls.
1508 // Analyze operands of the call, assigning locations to each operand.
1509 SmallVector<CCValAssign, 16> ArgLocs;
1510 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1511 *DAG.getContext(), Call);
1512 CCInfo.AnalyzeCallOperands(Outs,
1513 CCAssignFnForNode(CallConv, /* Return*/ false,
1516 // Get a count of how many bytes are to be pushed on the stack.
1517 unsigned NumBytes = CCInfo.getNextStackOffset();
1519 // For tail calls, memory operands are available in our caller's stack.
1523 // Adjust the stack pointer for the new arguments...
1524 // These operations are automatically eliminated by the prolog/epilog pass
1526 Chain = DAG.getCALLSEQ_START(Chain,
1527 DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1529 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1531 RegsToPassVector RegsToPass;
1532 SmallVector<SDValue, 8> MemOpChains;
1534 // Walk the register/memloc assignments, inserting copies/loads. In the case
1535 // of tail call optimization, arguments are handled later.
1536 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1538 ++i, ++realArgIdx) {
1539 CCValAssign &VA = ArgLocs[i];
1540 SDValue Arg = OutVals[realArgIdx];
1541 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1542 bool isByVal = Flags.isByVal();
1544 // Promote the value if needed.
1545 switch (VA.getLocInfo()) {
1546 default: llvm_unreachable("Unknown loc info!");
1547 case CCValAssign::Full: break;
1548 case CCValAssign::SExt:
1549 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1551 case CCValAssign::ZExt:
1552 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1554 case CCValAssign::AExt:
1555 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1557 case CCValAssign::BCvt:
1558 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1562 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1563 if (VA.needsCustom()) {
1564 if (VA.getLocVT() == MVT::v2f64) {
1565 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1566 DAG.getConstant(0, dl, MVT::i32));
1567 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1568 DAG.getConstant(1, dl, MVT::i32));
1570 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1571 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1573 VA = ArgLocs[++i]; // skip ahead to next loc
1574 if (VA.isRegLoc()) {
1575 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1576 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1578 assert(VA.isMemLoc());
1580 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1581 dl, DAG, VA, Flags));
1584 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1585 StackPtr, MemOpChains, Flags);
1587 } else if (VA.isRegLoc()) {
1588 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1589 assert(VA.getLocVT() == MVT::i32 &&
1590 "unexpected calling convention register assignment");
1591 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1592 "unexpected use of 'returned'");
1593 isThisReturn = true;
1595 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1596 } else if (isByVal) {
1597 assert(VA.isMemLoc());
1598 unsigned offset = 0;
1600 // True if this byval aggregate will be split between registers
1602 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1603 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1605 if (CurByValIdx < ByValArgsCount) {
1607 unsigned RegBegin, RegEnd;
1608 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1610 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1612 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1613 SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1614 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1615 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1616 MachinePointerInfo(),
1617 false, false, false,
1618 DAG.InferPtrAlignment(AddArg));
1619 MemOpChains.push_back(Load.getValue(1));
1620 RegsToPass.push_back(std::make_pair(j, Load));
1623 // If parameter size outsides register area, "offset" value
1624 // helps us to calculate stack slot for remained part properly.
1625 offset = RegEnd - RegBegin;
1627 CCInfo.nextInRegsParam();
1630 if (Flags.getByValSize() > 4*offset) {
1631 unsigned LocMemOffset = VA.getLocMemOffset();
1632 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1633 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1635 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1636 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1637 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1639 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1642 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1643 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1644 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1647 } else if (!isSibCall) {
1648 assert(VA.isMemLoc());
1650 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1651 dl, DAG, VA, Flags));
1655 if (!MemOpChains.empty())
1656 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1658 // Build a sequence of copy-to-reg nodes chained together with token chain
1659 // and flag operands which copy the outgoing args into the appropriate regs.
1661 // Tail call byval lowering might overwrite argument registers so in case of
1662 // tail call optimization the copies to registers are lowered later.
1664 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1665 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1666 RegsToPass[i].second, InFlag);
1667 InFlag = Chain.getValue(1);
1670 // For tail calls lower the arguments to the 'real' stack slot.
1672 // Force all the incoming stack arguments to be loaded from the stack
1673 // before any new outgoing arguments are stored to the stack, because the
1674 // outgoing stack slots may alias the incoming argument stack slots, and
1675 // the alias isn't otherwise explicit. This is slightly more conservative
1676 // than necessary, because it means that each store effectively depends
1677 // on every argument instead of just those arguments it would clobber.
1679 // Do not flag preceding copytoreg stuff together with the following stuff.
1681 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1682 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1683 RegsToPass[i].second, InFlag);
1684 InFlag = Chain.getValue(1);
1689 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1690 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1691 // node so that legalize doesn't hack it.
1692 bool isDirect = false;
1693 bool isARMFunc = false;
1694 bool isLocalARMFunc = false;
1695 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1697 if (EnableARMLongCalls) {
1698 assert((Subtarget->isTargetWindows() ||
1699 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1700 "long-calls with non-static relocation model!");
1701 // Handle a global address or an external symbol. If it's not one of
1702 // those, the target's already in a register, so we don't need to do
1704 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1705 const GlobalValue *GV = G->getGlobal();
1706 // Create a constant pool entry for the callee address
1707 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1708 ARMConstantPoolValue *CPV =
1709 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1711 // Get the address of the callee into a register
1712 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1713 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1714 Callee = DAG.getLoad(getPointerTy(), dl,
1715 DAG.getEntryNode(), CPAddr,
1716 MachinePointerInfo::getConstantPool(),
1717 false, false, false, 0);
1718 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1719 const char *Sym = S->getSymbol();
1721 // Create a constant pool entry for the callee address
1722 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1723 ARMConstantPoolValue *CPV =
1724 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1725 ARMPCLabelIndex, 0);
1726 // Get the address of the callee into a register
1727 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1728 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1729 Callee = DAG.getLoad(getPointerTy(), dl,
1730 DAG.getEntryNode(), CPAddr,
1731 MachinePointerInfo::getConstantPool(),
1732 false, false, false, 0);
1734 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1735 const GlobalValue *GV = G->getGlobal();
1737 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1738 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1739 getTargetMachine().getRelocationModel() != Reloc::Static;
1740 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1741 // ARM call to a local ARM function is predicable.
1742 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1743 // tBX takes a register source operand.
1744 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1745 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1746 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1747 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1748 0, ARMII::MO_NONLAZY));
1749 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1750 MachinePointerInfo::getGOT(), false, false, true, 0);
1751 } else if (Subtarget->isTargetCOFF()) {
1752 assert(Subtarget->isTargetWindows() &&
1753 "Windows is the only supported COFF target");
1754 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1755 ? ARMII::MO_DLLIMPORT
1756 : ARMII::MO_NO_FLAG;
1757 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1759 if (GV->hasDLLImportStorageClass())
1760 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1761 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1762 Callee), MachinePointerInfo::getGOT(),
1763 false, false, false, 0);
1765 // On ELF targets for PIC code, direct calls should go through the PLT
1766 unsigned OpFlags = 0;
1767 if (Subtarget->isTargetELF() &&
1768 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1769 OpFlags = ARMII::MO_PLT;
1770 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1772 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1774 bool isStub = Subtarget->isTargetMachO() &&
1775 getTargetMachine().getRelocationModel() != Reloc::Static;
1776 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1777 // tBX takes a register source operand.
1778 const char *Sym = S->getSymbol();
1779 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1780 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1781 ARMConstantPoolValue *CPV =
1782 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1783 ARMPCLabelIndex, 4);
1784 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1785 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1786 Callee = DAG.getLoad(getPointerTy(), dl,
1787 DAG.getEntryNode(), CPAddr,
1788 MachinePointerInfo::getConstantPool(),
1789 false, false, false, 0);
1790 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1791 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1792 getPointerTy(), Callee, PICLabel);
1794 unsigned OpFlags = 0;
1795 // On ELF targets for PIC code, direct calls should go through the PLT
1796 if (Subtarget->isTargetELF() &&
1797 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1798 OpFlags = ARMII::MO_PLT;
1799 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1803 // FIXME: handle tail calls differently.
1805 bool HasMinSizeAttr = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
1806 if (Subtarget->isThumb()) {
1807 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1808 CallOpc = ARMISD::CALL_NOLINK;
1810 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1812 if (!isDirect && !Subtarget->hasV5TOps())
1813 CallOpc = ARMISD::CALL_NOLINK;
1814 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1815 // Emit regular call when code size is the priority
1817 // "mov lr, pc; b _foo" to avoid confusing the RSP
1818 CallOpc = ARMISD::CALL_NOLINK;
1820 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1823 std::vector<SDValue> Ops;
1824 Ops.push_back(Chain);
1825 Ops.push_back(Callee);
1827 // Add argument registers to the end of the list so that they are known live
1829 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1830 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1831 RegsToPass[i].second.getValueType()));
1833 // Add a register mask operand representing the call-preserved registers.
1835 const uint32_t *Mask;
1836 const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1838 // For 'this' returns, use the R0-preserving mask if applicable
1839 Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1841 // Set isThisReturn to false if the calling convention is not one that
1842 // allows 'returned' to be modeled in this way, so LowerCallResult does
1843 // not try to pass 'this' straight through
1844 isThisReturn = false;
1845 Mask = ARI->getCallPreservedMask(MF, CallConv);
1848 Mask = ARI->getCallPreservedMask(MF, CallConv);
1850 assert(Mask && "Missing call preserved mask for calling convention");
1851 Ops.push_back(DAG.getRegisterMask(Mask));
1854 if (InFlag.getNode())
1855 Ops.push_back(InFlag);
1857 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1859 MF.getFrameInfo()->setHasTailCall();
1860 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1863 // Returns a chain and a flag for retval copy to use.
1864 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1865 InFlag = Chain.getValue(1);
1867 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1868 DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1870 InFlag = Chain.getValue(1);
1872 // Handle result values, copying them out of physregs into vregs that we
1874 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1875 InVals, isThisReturn,
1876 isThisReturn ? OutVals[0] : SDValue());
1879 /// HandleByVal - Every parameter *after* a byval parameter is passed
1880 /// on the stack. Remember the next parameter register to allocate,
1881 /// and then confiscate the rest of the parameter registers to insure
1883 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1884 unsigned Align) const {
1885 assert((State->getCallOrPrologue() == Prologue ||
1886 State->getCallOrPrologue() == Call) &&
1887 "unhandled ParmContext");
1889 // Byval (as with any stack) slots are always at least 4 byte aligned.
1890 Align = std::max(Align, 4U);
1892 unsigned Reg = State->AllocateReg(GPRArgRegs);
1896 unsigned AlignInRegs = Align / 4;
1897 unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1898 for (unsigned i = 0; i < Waste; ++i)
1899 Reg = State->AllocateReg(GPRArgRegs);
1904 unsigned Excess = 4 * (ARM::R4 - Reg);
1906 // Special case when NSAA != SP and parameter size greater than size of
1907 // all remained GPR regs. In that case we can't split parameter, we must
1908 // send it to stack. We also must set NCRN to R4, so waste all
1909 // remained registers.
1910 const unsigned NSAAOffset = State->getNextStackOffset();
1911 if (NSAAOffset != 0 && Size > Excess) {
1912 while (State->AllocateReg(GPRArgRegs))
1917 // First register for byval parameter is the first register that wasn't
1918 // allocated before this method call, so it would be "reg".
1919 // If parameter is small enough to be saved in range [reg, r4), then
1920 // the end (first after last) register would be reg + param-size-in-regs,
1921 // else parameter would be splitted between registers and stack,
1922 // end register would be r4 in this case.
1923 unsigned ByValRegBegin = Reg;
1924 unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1925 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1926 // Note, first register is allocated in the beginning of function already,
1927 // allocate remained amount of registers we need.
1928 for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1929 State->AllocateReg(GPRArgRegs);
1930 // A byval parameter that is split between registers and memory needs its
1931 // size truncated here.
1932 // In the case where the entire structure fits in registers, we set the
1933 // size in memory to zero.
1934 Size = std::max<int>(Size - Excess, 0);
1937 /// MatchingStackOffset - Return true if the given stack call argument is
1938 /// already available in the same position (relatively) of the caller's
1939 /// incoming argument stack.
1941 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1942 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1943 const TargetInstrInfo *TII) {
1944 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1946 if (Arg.getOpcode() == ISD::CopyFromReg) {
1947 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1948 if (!TargetRegisterInfo::isVirtualRegister(VR))
1950 MachineInstr *Def = MRI->getVRegDef(VR);
1953 if (!Flags.isByVal()) {
1954 if (!TII->isLoadFromStackSlot(Def, FI))
1959 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1960 if (Flags.isByVal())
1961 // ByVal argument is passed in as a pointer but it's now being
1962 // dereferenced. e.g.
1963 // define @foo(%struct.X* %A) {
1964 // tail call @bar(%struct.X* byval %A)
1967 SDValue Ptr = Ld->getBasePtr();
1968 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1971 FI = FINode->getIndex();
1975 assert(FI != INT_MAX);
1976 if (!MFI->isFixedObjectIndex(FI))
1978 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1981 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1982 /// for tail call optimization. Targets which want to do tail call
1983 /// optimization should implement this function.
1985 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1986 CallingConv::ID CalleeCC,
1988 bool isCalleeStructRet,
1989 bool isCallerStructRet,
1990 const SmallVectorImpl<ISD::OutputArg> &Outs,
1991 const SmallVectorImpl<SDValue> &OutVals,
1992 const SmallVectorImpl<ISD::InputArg> &Ins,
1993 SelectionDAG& DAG) const {
1994 const Function *CallerF = DAG.getMachineFunction().getFunction();
1995 CallingConv::ID CallerCC = CallerF->getCallingConv();
1996 bool CCMatch = CallerCC == CalleeCC;
1998 // Look for obvious safe cases to perform tail call optimization that do not
1999 // require ABI changes. This is what gcc calls sibcall.
2001 // Do not sibcall optimize vararg calls unless the call site is not passing
2003 if (isVarArg && !Outs.empty())
2006 // Exception-handling functions need a special set of instructions to indicate
2007 // a return to the hardware. Tail-calling another function would probably
2009 if (CallerF->hasFnAttribute("interrupt"))
2012 // Also avoid sibcall optimization if either caller or callee uses struct
2013 // return semantics.
2014 if (isCalleeStructRet || isCallerStructRet)
2017 // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2018 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2019 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2020 // support in the assembler and linker to be used. This would need to be
2021 // fixed to fully support tail calls in Thumb1.
2023 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2024 // LR. This means if we need to reload LR, it takes an extra instructions,
2025 // which outweighs the value of the tail call; but here we don't know yet
2026 // whether LR is going to be used. Probably the right approach is to
2027 // generate the tail call here and turn it back into CALL/RET in
2028 // emitEpilogue if LR is used.
2030 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2031 // but we need to make sure there are enough registers; the only valid
2032 // registers are the 4 used for parameters. We don't currently do this
2034 if (Subtarget->isThumb1Only())
2037 // Externally-defined functions with weak linkage should not be
2038 // tail-called on ARM when the OS does not support dynamic
2039 // pre-emption of symbols, as the AAELF spec requires normal calls
2040 // to undefined weak functions to be replaced with a NOP or jump to the
2041 // next instruction. The behaviour of branch instructions in this
2042 // situation (as used for tail calls) is implementation-defined, so we
2043 // cannot rely on the linker replacing the tail call with a return.
2044 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2045 const GlobalValue *GV = G->getGlobal();
2046 const Triple &TT = getTargetMachine().getTargetTriple();
2047 if (GV->hasExternalWeakLinkage() &&
2048 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2052 // If the calling conventions do not match, then we'd better make sure the
2053 // results are returned in the same way as what the caller expects.
2055 SmallVector<CCValAssign, 16> RVLocs1;
2056 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2057 *DAG.getContext(), Call);
2058 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2060 SmallVector<CCValAssign, 16> RVLocs2;
2061 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2062 *DAG.getContext(), Call);
2063 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2065 if (RVLocs1.size() != RVLocs2.size())
2067 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2068 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2070 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2072 if (RVLocs1[i].isRegLoc()) {
2073 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2076 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2082 // If Caller's vararg or byval argument has been split between registers and
2083 // stack, do not perform tail call, since part of the argument is in caller's
2085 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2086 getInfo<ARMFunctionInfo>();
2087 if (AFI_Caller->getArgRegsSaveSize())
2090 // If the callee takes no arguments then go on to check the results of the
2092 if (!Outs.empty()) {
2093 // Check if stack adjustment is needed. For now, do not do this if any
2094 // argument is passed on the stack.
2095 SmallVector<CCValAssign, 16> ArgLocs;
2096 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2097 *DAG.getContext(), Call);
2098 CCInfo.AnalyzeCallOperands(Outs,
2099 CCAssignFnForNode(CalleeCC, false, isVarArg));
2100 if (CCInfo.getNextStackOffset()) {
2101 MachineFunction &MF = DAG.getMachineFunction();
2103 // Check if the arguments are already laid out in the right way as
2104 // the caller's fixed stack objects.
2105 MachineFrameInfo *MFI = MF.getFrameInfo();
2106 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2107 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2108 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2110 ++i, ++realArgIdx) {
2111 CCValAssign &VA = ArgLocs[i];
2112 EVT RegVT = VA.getLocVT();
2113 SDValue Arg = OutVals[realArgIdx];
2114 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2115 if (VA.getLocInfo() == CCValAssign::Indirect)
2117 if (VA.needsCustom()) {
2118 // f64 and vector types are split into multiple registers or
2119 // register/stack-slot combinations. The types will not match
2120 // the registers; give up on memory f64 refs until we figure
2121 // out what to do about this.
2124 if (!ArgLocs[++i].isRegLoc())
2126 if (RegVT == MVT::v2f64) {
2127 if (!ArgLocs[++i].isRegLoc())
2129 if (!ArgLocs[++i].isRegLoc())
2132 } else if (!VA.isRegLoc()) {
2133 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2145 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2146 MachineFunction &MF, bool isVarArg,
2147 const SmallVectorImpl<ISD::OutputArg> &Outs,
2148 LLVMContext &Context) const {
2149 SmallVector<CCValAssign, 16> RVLocs;
2150 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2151 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2155 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2156 SDLoc DL, SelectionDAG &DAG) {
2157 const MachineFunction &MF = DAG.getMachineFunction();
2158 const Function *F = MF.getFunction();
2160 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2162 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2163 // version of the "preferred return address". These offsets affect the return
2164 // instruction if this is a return from PL1 without hypervisor extensions.
2165 // IRQ/FIQ: +4 "subs pc, lr, #4"
2166 // SWI: 0 "subs pc, lr, #0"
2167 // ABORT: +4 "subs pc, lr, #4"
2168 // UNDEF: +4/+2 "subs pc, lr, #0"
2169 // UNDEF varies depending on where the exception came from ARM or Thumb
2170 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2173 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2176 else if (IntKind == "SWI" || IntKind == "UNDEF")
2179 report_fatal_error("Unsupported interrupt attribute. If present, value "
2180 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2182 RetOps.insert(RetOps.begin() + 1,
2183 DAG.getConstant(LROffset, DL, MVT::i32, false));
2185 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2189 ARMTargetLowering::LowerReturn(SDValue Chain,
2190 CallingConv::ID CallConv, bool isVarArg,
2191 const SmallVectorImpl<ISD::OutputArg> &Outs,
2192 const SmallVectorImpl<SDValue> &OutVals,
2193 SDLoc dl, SelectionDAG &DAG) const {
2195 // CCValAssign - represent the assignment of the return value to a location.
2196 SmallVector<CCValAssign, 16> RVLocs;
2198 // CCState - Info about the registers and stack slots.
2199 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2200 *DAG.getContext(), Call);
2202 // Analyze outgoing return values.
2203 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2207 SmallVector<SDValue, 4> RetOps;
2208 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2209 bool isLittleEndian = Subtarget->isLittle();
2211 MachineFunction &MF = DAG.getMachineFunction();
2212 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2213 AFI->setReturnRegsCount(RVLocs.size());
2215 // Copy the result values into the output registers.
2216 for (unsigned i = 0, realRVLocIdx = 0;
2218 ++i, ++realRVLocIdx) {
2219 CCValAssign &VA = RVLocs[i];
2220 assert(VA.isRegLoc() && "Can only return in registers!");
2222 SDValue Arg = OutVals[realRVLocIdx];
2224 switch (VA.getLocInfo()) {
2225 default: llvm_unreachable("Unknown loc info!");
2226 case CCValAssign::Full: break;
2227 case CCValAssign::BCvt:
2228 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2232 if (VA.needsCustom()) {
2233 if (VA.getLocVT() == MVT::v2f64) {
2234 // Extract the first half and return it in two registers.
2235 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2236 DAG.getConstant(0, dl, MVT::i32));
2237 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2238 DAG.getVTList(MVT::i32, MVT::i32), Half);
2240 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2241 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2243 Flag = Chain.getValue(1);
2244 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2245 VA = RVLocs[++i]; // skip ahead to next loc
2246 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2249 Flag = Chain.getValue(1);
2250 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251 VA = RVLocs[++i]; // skip ahead to next loc
2253 // Extract the 2nd half and fall through to handle it as an f64 value.
2254 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2255 DAG.getConstant(1, dl, MVT::i32));
2257 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2259 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2260 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2261 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2262 fmrrd.getValue(isLittleEndian ? 0 : 1),
2264 Flag = Chain.getValue(1);
2265 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2266 VA = RVLocs[++i]; // skip ahead to next loc
2267 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2268 fmrrd.getValue(isLittleEndian ? 1 : 0),
2271 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2273 // Guarantee that all emitted copies are
2274 // stuck together, avoiding something bad.
2275 Flag = Chain.getValue(1);
2276 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2279 // Update chain and glue.
2282 RetOps.push_back(Flag);
2284 // CPUs which aren't M-class use a special sequence to return from
2285 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2286 // though we use "subs pc, lr, #N").
2288 // M-class CPUs actually use a normal return sequence with a special
2289 // (hardware-provided) value in LR, so the normal code path works.
2290 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2291 !Subtarget->isMClass()) {
2292 if (Subtarget->isThumb1Only())
2293 report_fatal_error("interrupt attribute is not supported in Thumb1");
2294 return LowerInterruptReturn(RetOps, dl, DAG);
2297 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2300 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2301 if (N->getNumValues() != 1)
2303 if (!N->hasNUsesOfValue(1, 0))
2306 SDValue TCChain = Chain;
2307 SDNode *Copy = *N->use_begin();
2308 if (Copy->getOpcode() == ISD::CopyToReg) {
2309 // If the copy has a glue operand, we conservatively assume it isn't safe to
2310 // perform a tail call.
2311 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2313 TCChain = Copy->getOperand(0);
2314 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2315 SDNode *VMov = Copy;
2316 // f64 returned in a pair of GPRs.
2317 SmallPtrSet<SDNode*, 2> Copies;
2318 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2320 if (UI->getOpcode() != ISD::CopyToReg)
2324 if (Copies.size() > 2)
2327 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2329 SDValue UseChain = UI->getOperand(0);
2330 if (Copies.count(UseChain.getNode()))
2334 // We are at the top of this chain.
2335 // If the copy has a glue operand, we conservatively assume it
2336 // isn't safe to perform a tail call.
2337 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2343 } else if (Copy->getOpcode() == ISD::BITCAST) {
2344 // f32 returned in a single GPR.
2345 if (!Copy->hasOneUse())
2347 Copy = *Copy->use_begin();
2348 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2350 // If the copy has a glue operand, we conservatively assume it isn't safe to
2351 // perform a tail call.
2352 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2354 TCChain = Copy->getOperand(0);
2359 bool HasRet = false;
2360 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2362 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2363 UI->getOpcode() != ARMISD::INTRET_FLAG)
2375 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2376 if (!Subtarget->supportsTailCall())
2380 CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2381 if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2384 return !Subtarget->isThumb1Only();
2387 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2388 // and pass the lower and high parts through.
2389 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2391 SDValue WriteValue = Op->getOperand(2);
2393 // This function is only supposed to be called for i64 type argument.
2394 assert(WriteValue.getValueType() == MVT::i64
2395 && "LowerWRITE_REGISTER called for non-i64 type argument.");
2397 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2398 DAG.getConstant(0, DL, MVT::i32));
2399 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2400 DAG.getConstant(1, DL, MVT::i32));
2401 SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2402 return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2405 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2406 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2407 // one of the above mentioned nodes. It has to be wrapped because otherwise
2408 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2409 // be used to form addressing mode. These wrapped nodes will be selected
2411 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2412 EVT PtrVT = Op.getValueType();
2413 // FIXME there is no actual debug info here
2415 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2417 if (CP->isMachineConstantPoolEntry())
2418 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2419 CP->getAlignment());
2421 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2422 CP->getAlignment());
2423 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2426 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2427 return MachineJumpTableInfo::EK_Inline;
2430 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2431 SelectionDAG &DAG) const {
2432 MachineFunction &MF = DAG.getMachineFunction();
2433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434 unsigned ARMPCLabelIndex = 0;
2436 EVT PtrVT = getPointerTy();
2437 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2438 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2440 if (RelocM == Reloc::Static) {
2441 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2443 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2444 ARMPCLabelIndex = AFI->createPICLabelUId();
2445 ARMConstantPoolValue *CPV =
2446 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2447 ARMCP::CPBlockAddress, PCAdj);
2448 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2450 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2451 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2452 MachinePointerInfo::getConstantPool(),
2453 false, false, false, 0);
2454 if (RelocM == Reloc::Static)
2456 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2457 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2460 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2462 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2463 SelectionDAG &DAG) const {
2465 EVT PtrVT = getPointerTy();
2466 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2467 MachineFunction &MF = DAG.getMachineFunction();
2468 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2469 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2470 ARMConstantPoolValue *CPV =
2471 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2472 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2473 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2474 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2475 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2476 MachinePointerInfo::getConstantPool(),
2477 false, false, false, 0);
2478 SDValue Chain = Argument.getValue(1);
2480 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2481 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2483 // call __tls_get_addr.
2486 Entry.Node = Argument;
2487 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2488 Args.push_back(Entry);
2490 // FIXME: is there useful debug info available here?
2491 TargetLowering::CallLoweringInfo CLI(DAG);
2492 CLI.setDebugLoc(dl).setChain(Chain)
2493 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2494 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2497 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2498 return CallResult.first;
2501 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2502 // "local exec" model.
2504 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2506 TLSModel::Model model) const {
2507 const GlobalValue *GV = GA->getGlobal();
2510 SDValue Chain = DAG.getEntryNode();
2511 EVT PtrVT = getPointerTy();
2512 // Get the Thread Pointer
2513 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2515 if (model == TLSModel::InitialExec) {
2516 MachineFunction &MF = DAG.getMachineFunction();
2517 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2518 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2519 // Initial exec model.
2520 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2521 ARMConstantPoolValue *CPV =
2522 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2523 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2525 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2526 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2527 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2528 MachinePointerInfo::getConstantPool(),
2529 false, false, false, 0);
2530 Chain = Offset.getValue(1);
2532 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2533 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2535 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2536 MachinePointerInfo::getConstantPool(),
2537 false, false, false, 0);
2540 assert(model == TLSModel::LocalExec);
2541 ARMConstantPoolValue *CPV =
2542 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2543 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2544 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2545 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2546 MachinePointerInfo::getConstantPool(),
2547 false, false, false, 0);
2550 // The address of the thread local variable is the add of the thread
2551 // pointer with the offset of the variable.
2552 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2556 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2557 // TODO: implement the "local dynamic" model
2558 assert(Subtarget->isTargetELF() &&
2559 "TLS not implemented for non-ELF targets");
2560 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2562 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2565 case TLSModel::GeneralDynamic:
2566 case TLSModel::LocalDynamic:
2567 return LowerToTLSGeneralDynamicModel(GA, DAG);
2568 case TLSModel::InitialExec:
2569 case TLSModel::LocalExec:
2570 return LowerToTLSExecModels(GA, DAG, model);
2572 llvm_unreachable("bogus TLS model");
2575 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2576 SelectionDAG &DAG) const {
2577 EVT PtrVT = getPointerTy();
2579 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2580 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2581 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2582 ARMConstantPoolValue *CPV =
2583 ARMConstantPoolConstant::Create(GV,
2584 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2585 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2586 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2587 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2589 MachinePointerInfo::getConstantPool(),
2590 false, false, false, 0);
2591 SDValue Chain = Result.getValue(1);
2592 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2593 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2595 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2596 MachinePointerInfo::getGOT(),
2597 false, false, false, 0);
2601 // If we have T2 ops, we can materialize the address directly via movt/movw
2602 // pair. This is always cheaper.
2603 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2605 // FIXME: Once remat is capable of dealing with instructions with register
2606 // operands, expand this into two nodes.
2607 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2608 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2610 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2611 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2612 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2613 MachinePointerInfo::getConstantPool(),
2614 false, false, false, 0);
2618 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2619 SelectionDAG &DAG) const {
2620 EVT PtrVT = getPointerTy();
2622 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2623 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2625 if (Subtarget->useMovt(DAG.getMachineFunction()))
2628 // FIXME: Once remat is capable of dealing with instructions with register
2629 // operands, expand this into multiple nodes
2631 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2633 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2634 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2636 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2637 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2638 MachinePointerInfo::getGOT(), false, false, false, 0);
2642 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2643 SelectionDAG &DAG) const {
2644 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2645 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2646 "Windows on ARM expects to use movw/movt");
2648 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2649 const ARMII::TOF TargetFlags =
2650 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2651 EVT PtrVT = getPointerTy();
2657 // FIXME: Once remat is capable of dealing with instructions with register
2658 // operands, expand this into two nodes.
2659 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2660 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2662 if (GV->hasDLLImportStorageClass())
2663 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2664 MachinePointerInfo::getGOT(), false, false, false, 0);
2668 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2669 SelectionDAG &DAG) const {
2670 assert(Subtarget->isTargetELF() &&
2671 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2672 MachineFunction &MF = DAG.getMachineFunction();
2673 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2674 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2675 EVT PtrVT = getPointerTy();
2677 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2678 ARMConstantPoolValue *CPV =
2679 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2680 ARMPCLabelIndex, PCAdj);
2681 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2682 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2683 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2684 MachinePointerInfo::getConstantPool(),
2685 false, false, false, 0);
2686 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2687 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2691 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2693 SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2694 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2695 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2696 Op.getOperand(1), Val);
2700 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2702 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2703 Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2707 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2708 const ARMSubtarget *Subtarget) const {
2709 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2712 default: return SDValue(); // Don't custom lower most intrinsics.
2713 case Intrinsic::arm_rbit: {
2714 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2715 "RBIT intrinsic must have i32 type!");
2716 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2718 case Intrinsic::arm_thread_pointer: {
2719 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2720 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2722 case Intrinsic::eh_sjlj_lsda: {
2723 MachineFunction &MF = DAG.getMachineFunction();
2724 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2725 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2726 EVT PtrVT = getPointerTy();
2727 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2729 unsigned PCAdj = (RelocM != Reloc::PIC_)
2730 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2731 ARMConstantPoolValue *CPV =
2732 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2733 ARMCP::CPLSDA, PCAdj);
2734 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2735 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2737 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2738 MachinePointerInfo::getConstantPool(),
2739 false, false, false, 0);
2741 if (RelocM == Reloc::PIC_) {
2742 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2743 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2747 case Intrinsic::arm_neon_vmulls:
2748 case Intrinsic::arm_neon_vmullu: {
2749 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2750 ? ARMISD::VMULLs : ARMISD::VMULLu;
2751 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2752 Op.getOperand(1), Op.getOperand(2));
2757 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2758 const ARMSubtarget *Subtarget) {
2759 // FIXME: handle "fence singlethread" more efficiently.
2761 if (!Subtarget->hasDataBarrier()) {
2762 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2763 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2765 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2766 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2767 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2768 DAG.getConstant(0, dl, MVT::i32));
2771 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2772 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2773 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2774 if (Subtarget->isMClass()) {
2775 // Only a full system barrier exists in the M-class architectures.
2776 Domain = ARM_MB::SY;
2777 } else if (Subtarget->isSwift() && Ord == Release) {
2778 // Swift happens to implement ISHST barriers in a way that's compatible with
2779 // Release semantics but weaker than ISH so we'd be fools not to use
2780 // it. Beware: other processors probably don't!
2781 Domain = ARM_MB::ISHST;
2784 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2785 DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2786 DAG.getConstant(Domain, dl, MVT::i32));
2789 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2790 const ARMSubtarget *Subtarget) {
2791 // ARM pre v5TE and Thumb1 does not have preload instructions.
2792 if (!(Subtarget->isThumb2() ||
2793 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2794 // Just preserve the chain.
2795 return Op.getOperand(0);
2798 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2800 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2801 // ARMv7 with MP extension has PLDW.
2802 return Op.getOperand(0);
2804 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2805 if (Subtarget->isThumb()) {
2807 isRead = ~isRead & 1;
2808 isData = ~isData & 1;
2811 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2812 Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2813 DAG.getConstant(isData, dl, MVT::i32));
2816 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2817 MachineFunction &MF = DAG.getMachineFunction();
2818 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2820 // vastart just stores the address of the VarArgsFrameIndex slot into the
2821 // memory location argument.
2823 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2824 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2825 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2826 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2827 MachinePointerInfo(SV), false, false, 0);
2831 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2832 SDValue &Root, SelectionDAG &DAG,
2834 MachineFunction &MF = DAG.getMachineFunction();
2835 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2837 const TargetRegisterClass *RC;
2838 if (AFI->isThumb1OnlyFunction())
2839 RC = &ARM::tGPRRegClass;
2841 RC = &ARM::GPRRegClass;
2843 // Transform the arguments stored in physical registers into virtual ones.
2844 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2845 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2848 if (NextVA.isMemLoc()) {
2849 MachineFrameInfo *MFI = MF.getFrameInfo();
2850 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2852 // Create load node to retrieve arguments from the stack.
2853 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2854 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2855 MachinePointerInfo::getFixedStack(FI),
2856 false, false, false, 0);
2858 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2859 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2861 if (!Subtarget->isLittle())
2862 std::swap (ArgValue, ArgValue2);
2863 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2866 // The remaining GPRs hold either the beginning of variable-argument
2867 // data, or the beginning of an aggregate passed by value (usually
2868 // byval). Either way, we allocate stack slots adjacent to the data
2869 // provided by our caller, and store the unallocated registers there.
2870 // If this is a variadic function, the va_list pointer will begin with
2871 // these values; otherwise, this reassembles a (byval) structure that
2872 // was split between registers and memory.
2873 // Return: The frame index registers were stored into.
2875 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2876 SDLoc dl, SDValue &Chain,
2877 const Value *OrigArg,
2878 unsigned InRegsParamRecordIdx,
2880 unsigned ArgSize) const {
2881 // Currently, two use-cases possible:
2882 // Case #1. Non-var-args function, and we meet first byval parameter.
2883 // Setup first unallocated register as first byval register;
2884 // eat all remained registers
2885 // (these two actions are performed by HandleByVal method).
2886 // Then, here, we initialize stack frame with
2887 // "store-reg" instructions.
2888 // Case #2. Var-args function, that doesn't contain byval parameters.
2889 // The same: eat all remained unallocated registers,
2890 // initialize stack frame.
2892 MachineFunction &MF = DAG.getMachineFunction();
2893 MachineFrameInfo *MFI = MF.getFrameInfo();
2894 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2895 unsigned RBegin, REnd;
2896 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2897 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2899 unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2900 RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2905 ArgOffset = -4 * (ARM::R4 - RBegin);
2907 int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2908 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2910 SmallVector<SDValue, 4> MemOps;
2911 const TargetRegisterClass *RC =
2912 AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2914 for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2915 unsigned VReg = MF.addLiveIn(Reg, RC);
2916 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2918 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2919 MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2920 MemOps.push_back(Store);
2921 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2922 DAG.getConstant(4, dl, getPointerTy()));
2925 if (!MemOps.empty())
2926 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2930 // Setup stack frame, the va_list pointer will start from.
2932 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2933 SDLoc dl, SDValue &Chain,
2935 unsigned TotalArgRegsSaveSize,
2936 bool ForceMutable) const {
2937 MachineFunction &MF = DAG.getMachineFunction();
2938 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2940 // Try to store any remaining integer argument regs
2941 // to their spots on the stack so that they may be loaded by deferencing
2942 // the result of va_next.
2943 // If there is no regs to be stored, just point address after last
2944 // argument passed via stack.
2945 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2946 CCInfo.getInRegsParamsCount(),
2947 CCInfo.getNextStackOffset(), 4);
2948 AFI->setVarArgsFrameIndex(FrameIndex);
2952 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2953 CallingConv::ID CallConv, bool isVarArg,
2954 const SmallVectorImpl<ISD::InputArg>
2956 SDLoc dl, SelectionDAG &DAG,
2957 SmallVectorImpl<SDValue> &InVals)
2959 MachineFunction &MF = DAG.getMachineFunction();
2960 MachineFrameInfo *MFI = MF.getFrameInfo();
2962 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2964 // Assign locations to all of the incoming arguments.
2965 SmallVector<CCValAssign, 16> ArgLocs;
2966 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2967 *DAG.getContext(), Prologue);
2968 CCInfo.AnalyzeFormalArguments(Ins,
2969 CCAssignFnForNode(CallConv, /* Return*/ false,
2972 SmallVector<SDValue, 16> ArgValues;
2974 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2975 unsigned CurArgIdx = 0;
2977 // Initially ArgRegsSaveSize is zero.
2978 // Then we increase this value each time we meet byval parameter.
2979 // We also increase this value in case of varargs function.
2980 AFI->setArgRegsSaveSize(0);
2982 // Calculate the amount of stack space that we need to allocate to store
2983 // byval and variadic arguments that are passed in registers.
2984 // We need to know this before we allocate the first byval or variadic
2985 // argument, as they will be allocated a stack slot below the CFA (Canonical
2986 // Frame Address, the stack pointer at entry to the function).
2987 unsigned ArgRegBegin = ARM::R4;
2988 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989 if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
2992 CCValAssign &VA = ArgLocs[i];
2993 unsigned Index = VA.getValNo();
2994 ISD::ArgFlagsTy Flags = Ins[Index].Flags;
2995 if (!Flags.isByVal())
2998 assert(VA.isMemLoc() && "unexpected byval pointer in reg");
2999 unsigned RBegin, REnd;
3000 CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3001 ArgRegBegin = std::min(ArgRegBegin, RBegin);
3003 CCInfo.nextInRegsParam();
3005 CCInfo.rewindByValRegsInfo();
3007 int lastInsIndex = -1;
3008 if (isVarArg && MFI->hasVAStart()) {
3009 unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3010 if (RegIdx != array_lengthof(GPRArgRegs))
3011 ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3014 unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3015 AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3017 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3018 CCValAssign &VA = ArgLocs[i];
3019 if (Ins[VA.getValNo()].isOrigArg()) {
3020 std::advance(CurOrigArg,
3021 Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3022 CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3024 // Arguments stored in registers.
3025 if (VA.isRegLoc()) {
3026 EVT RegVT = VA.getLocVT();
3028 if (VA.needsCustom()) {
3029 // f64 and vector types are split up into multiple registers or
3030 // combinations of registers and stack slots.
3031 if (VA.getLocVT() == MVT::v2f64) {
3032 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3034 VA = ArgLocs[++i]; // skip ahead to next loc
3036 if (VA.isMemLoc()) {
3037 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3038 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3039 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3040 MachinePointerInfo::getFixedStack(FI),
3041 false, false, false, 0);
3043 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3046 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3047 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3048 ArgValue, ArgValue1,
3049 DAG.getIntPtrConstant(0, dl));
3050 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3051 ArgValue, ArgValue2,
3052 DAG.getIntPtrConstant(1, dl));
3054 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3057 const TargetRegisterClass *RC;
3059 if (RegVT == MVT::f32)
3060 RC = &ARM::SPRRegClass;
3061 else if (RegVT == MVT::f64)
3062 RC = &ARM::DPRRegClass;
3063 else if (RegVT == MVT::v2f64)
3064 RC = &ARM::QPRRegClass;
3065 else if (RegVT == MVT::i32)
3066 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3067 : &ARM::GPRRegClass;
3069 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3071 // Transform the arguments in physical registers into virtual ones.
3072 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3073 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3076 // If this is an 8 or 16-bit value, it is really passed promoted
3077 // to 32 bits. Insert an assert[sz]ext to capture this, then
3078 // truncate to the right size.
3079 switch (VA.getLocInfo()) {
3080 default: llvm_unreachable("Unknown loc info!");
3081 case CCValAssign::Full: break;
3082 case CCValAssign::BCvt:
3083 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3085 case CCValAssign::SExt:
3086 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3087 DAG.getValueType(VA.getValVT()));
3088 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3090 case CCValAssign::ZExt:
3091 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3092 DAG.getValueType(VA.getValVT()));
3093 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3097 InVals.push_back(ArgValue);
3099 } else { // VA.isRegLoc()
3102 assert(VA.isMemLoc());
3103 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3105 int index = VA.getValNo();
3107 // Some Ins[] entries become multiple ArgLoc[] entries.
3108 // Process them only once.
3109 if (index != lastInsIndex)
3111 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3112 // FIXME: For now, all byval parameter objects are marked mutable.
3113 // This can be changed with more analysis.
3114 // In case of tail call optimization mark all arguments mutable.
3115 // Since they could be overwritten by lowering of arguments in case of
3117 if (Flags.isByVal()) {
3118 assert(Ins[index].isOrigArg() &&
3119 "Byval arguments cannot be implicit");
3120 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3122 int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3123 CurByValIndex, VA.getLocMemOffset(),
3124 Flags.getByValSize());
3125 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3126 CCInfo.nextInRegsParam();
3128 unsigned FIOffset = VA.getLocMemOffset();
3129 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3132 // Create load nodes to retrieve arguments from the stack.
3133 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3134 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3135 MachinePointerInfo::getFixedStack(FI),
3136 false, false, false, 0));
3138 lastInsIndex = index;
3144 if (isVarArg && MFI->hasVAStart())
3145 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3146 CCInfo.getNextStackOffset(),
3147 TotalArgRegsSaveSize);
3149 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3154 /// isFloatingPointZero - Return true if this is +0.0.
3155 static bool isFloatingPointZero(SDValue Op) {
3156 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3157 return CFP->getValueAPF().isPosZero();
3158 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3159 // Maybe this has already been legalized into the constant pool?
3160 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3161 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3162 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3163 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3164 return CFP->getValueAPF().isPosZero();
3166 } else if (Op->getOpcode() == ISD::BITCAST &&
3167 Op->getValueType(0) == MVT::f64) {
3168 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3169 // created by LowerConstantFP().
3170 SDValue BitcastOp = Op->getOperand(0);
3171 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3172 SDValue MoveOp = BitcastOp->getOperand(0);
3173 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3174 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3182 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3183 /// the given operands.
3185 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3186 SDValue &ARMcc, SelectionDAG &DAG,
3188 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3189 unsigned C = RHSC->getZExtValue();
3190 if (!isLegalICmpImmediate(C)) {
3191 // Constant does not fit, try adjusting it by one?
3196 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3197 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3198 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3203 if (C != 0 && isLegalICmpImmediate(C-1)) {
3204 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3205 RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3210 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3211 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3212 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3217 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3218 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3219 RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3226 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3227 ARMISD::NodeType CompareType;
3230 CompareType = ARMISD::CMP;
3235 CompareType = ARMISD::CMPZ;
3238 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3239 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3242 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3244 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3246 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3248 if (!isFloatingPointZero(RHS))
3249 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3251 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3252 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3255 /// duplicateCmp - Glue values can have only one use, so this function
3256 /// duplicates a comparison node.
3258 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3259 unsigned Opc = Cmp.getOpcode();
3261 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3262 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3264 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3265 Cmp = Cmp.getOperand(0);
3266 Opc = Cmp.getOpcode();
3267 if (Opc == ARMISD::CMPFP)
3268 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3270 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3271 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3273 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3276 std::pair<SDValue, SDValue>
3277 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3278 SDValue &ARMcc) const {
3279 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3281 SDValue Value, OverflowCmp;
3282 SDValue LHS = Op.getOperand(0);
3283 SDValue RHS = Op.getOperand(1);
3286 // FIXME: We are currently always generating CMPs because we don't support
3287 // generating CMN through the backend. This is not as good as the natural
3288 // CMP case because it causes a register dependency and cannot be folded
3291 switch (Op.getOpcode()) {
3293 llvm_unreachable("Unknown overflow instruction!");
3295 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3296 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3297 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3300 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3301 Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3302 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3305 ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3306 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3307 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3310 ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3311 Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3312 OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3316 return std::make_pair(Value, OverflowCmp);
3321 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3322 // Let legalize expand this if it isn't a legal type yet.
3323 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3326 SDValue Value, OverflowCmp;
3328 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3329 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3331 // We use 0 and 1 as false and true values.
3332 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3333 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3334 EVT VT = Op.getValueType();
3336 SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3337 ARMcc, CCR, OverflowCmp);
3339 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3340 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3344 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3345 SDValue Cond = Op.getOperand(0);
3346 SDValue SelectTrue = Op.getOperand(1);
3347 SDValue SelectFalse = Op.getOperand(2);
3349 unsigned Opc = Cond.getOpcode();
3351 if (Cond.getResNo() == 1 &&
3352 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3353 Opc == ISD::USUBO)) {
3354 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3357 SDValue Value, OverflowCmp;
3359 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3360 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3361 EVT VT = Op.getValueType();
3363 return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3369 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3370 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3372 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3373 const ConstantSDNode *CMOVTrue =
3374 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3375 const ConstantSDNode *CMOVFalse =
3376 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3378 if (CMOVTrue && CMOVFalse) {
3379 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3380 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3384 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3386 False = SelectFalse;
3387 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3392 if (True.getNode() && False.getNode()) {
3393 EVT VT = Op.getValueType();
3394 SDValue ARMcc = Cond.getOperand(2);
3395 SDValue CCR = Cond.getOperand(3);
3396 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3397 assert(True.getValueType() == VT);
3398 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3403 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3404 // undefined bits before doing a full-word comparison with zero.
3405 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3406 DAG.getConstant(1, dl, Cond.getValueType()));
3408 return DAG.getSelectCC(dl, Cond,
3409 DAG.getConstant(0, dl, Cond.getValueType()),
3410 SelectTrue, SelectFalse, ISD::SETNE);
3413 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3414 bool &swpCmpOps, bool &swpVselOps) {
3415 // Start by selecting the GE condition code for opcodes that return true for
3417 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3419 CondCode = ARMCC::GE;
3421 // and GT for opcodes that return false for 'equality'.
3422 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3424 CondCode = ARMCC::GT;
3426 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3427 // to swap the compare operands.
3428 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3432 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3433 // If we have an unordered opcode, we need to swap the operands to the VSEL
3434 // instruction (effectively negating the condition).
3436 // This also has the effect of swapping which one of 'less' or 'greater'
3437 // returns true, so we also swap the compare operands. It also switches
3438 // whether we return true for 'equality', so we compensate by picking the
3439 // opposite condition code to our original choice.
3440 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3441 CC == ISD::SETUGT) {
3442 swpCmpOps = !swpCmpOps;
3443 swpVselOps = !swpVselOps;
3444 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3447 // 'ordered' is 'anything but unordered', so use the VS condition code and
3448 // swap the VSEL operands.
3449 if (CC == ISD::SETO) {
3450 CondCode = ARMCC::VS;
3454 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3455 // code and swap the VSEL operands.
3456 if (CC == ISD::SETUNE) {
3457 CondCode = ARMCC::EQ;
3462 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3463 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3464 SDValue Cmp, SelectionDAG &DAG) const {
3465 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3466 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3467 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3468 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3469 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3471 SDValue TrueLow = TrueVal.getValue(0);
3472 SDValue TrueHigh = TrueVal.getValue(1);
3473 SDValue FalseLow = FalseVal.getValue(0);
3474 SDValue FalseHigh = FalseVal.getValue(1);
3476 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3478 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3479 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3481 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3483 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3488 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3489 EVT VT = Op.getValueType();
3490 SDValue LHS = Op.getOperand(0);
3491 SDValue RHS = Op.getOperand(1);
3492 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3493 SDValue TrueVal = Op.getOperand(2);
3494 SDValue FalseVal = Op.getOperand(3);
3497 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3498 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3501 // If softenSetCCOperands only returned one value, we should compare it to
3503 if (!RHS.getNode()) {
3504 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3509 if (LHS.getValueType() == MVT::i32) {
3510 // Try to generate VSEL on ARMv8.
3511 // The VSEL instruction can't use all the usual ARM condition
3512 // codes: it only has two bits to select the condition code, so it's
3513 // constrained to use only GE, GT, VS and EQ.
3515 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3516 // swap the operands of the previous compare instruction (effectively
3517 // inverting the compare condition, swapping 'less' and 'greater') and
3518 // sometimes need to swap the operands to the VSEL (which inverts the
3519 // condition in the sense of firing whenever the previous condition didn't)
3520 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3521 TrueVal.getValueType() == MVT::f64)) {
3522 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3523 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3524 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3525 CC = ISD::getSetCCInverse(CC, true);
3526 std::swap(TrueVal, FalseVal);
3531 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3532 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3533 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3536 ARMCC::CondCodes CondCode, CondCode2;
3537 FPCCToARMCC(CC, CondCode, CondCode2);
3539 // Try to generate VMAXNM/VMINNM on ARMv8.
3540 if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3541 TrueVal.getValueType() == MVT::f64)) {
3542 // We can use VMAXNM/VMINNM for a compare followed by a select with the
3543 // same operands, as follows:
3544 // c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3546 // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3547 bool swapSides = false;
3548 if (!getTargetMachine().Options.NoNaNsFPMath) {
3549 // transformability may depend on which way around we compare
3557 // the non-NaN should be RHS
3558 swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3564 // the non-NaN should be LHS
3565 swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3569 swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3571 CC = ISD::getSetCCSwappedOperands(CC);
3572 std::swap(LHS, RHS);
3574 if (LHS == TrueVal && RHS == FalseVal) {
3575 bool canTransform = true;
3576 // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3577 if (!getTargetMachine().Options.UnsafeFPMath &&
3578 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3579 const ConstantFPSDNode *Zero;
3586 // RHS must not be -0
3587 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3588 !Zero->isNegative();
3593 // LHS must not be -0
3594 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3595 !Zero->isNegative();
3600 // RHS must not be +0
3601 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3607 // LHS must not be +0
3608 canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3614 // Note: If one of the elements in a pair is a number and the other
3615 // element is NaN, the corresponding result element is the number.
3616 // This is consistent with the IEEE 754-2008 standard.
3617 // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3623 if (!DAG.isKnownNeverNaN(RHS))
3625 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3628 if (!DAG.isKnownNeverNaN(LHS))
3632 return DAG.getNode(ARMISD::VMAXNM, dl, VT, LHS, RHS);
3635 if (!DAG.isKnownNeverNaN(RHS))
3637 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3640 if (!DAG.isKnownNeverNaN(LHS))
3644 return DAG.getNode(ARMISD::VMINNM, dl, VT, LHS, RHS);
3649 bool swpCmpOps = false;
3650 bool swpVselOps = false;
3651 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3653 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3654 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3656 std::swap(LHS, RHS);
3658 std::swap(TrueVal, FalseVal);
3662 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3663 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3664 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3665 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3666 if (CondCode2 != ARMCC::AL) {
3667 SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3668 // FIXME: Needs another CMP because flag can have but one use.
3669 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3670 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3675 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3676 /// to morph to an integer compare sequence.
3677 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3678 const ARMSubtarget *Subtarget) {
3679 SDNode *N = Op.getNode();
3680 if (!N->hasOneUse())
3681 // Otherwise it requires moving the value from fp to integer registers.
3683 if (!N->getNumValues())
3685 EVT VT = Op.getValueType();
3686 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3687 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3688 // vmrs are very slow, e.g. cortex-a8.
3691 if (isFloatingPointZero(Op)) {
3695 return ISD::isNormalLoad(N);
3698 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3699 if (isFloatingPointZero(Op))
3700 return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3702 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3703 return DAG.getLoad(MVT::i32, SDLoc(Op),
3704 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3705 Ld->isVolatile(), Ld->isNonTemporal(),
3706 Ld->isInvariant(), Ld->getAlignment());
3708 llvm_unreachable("Unknown VFP cmp argument!");
3711 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3712 SDValue &RetVal1, SDValue &RetVal2) {
3715 if (isFloatingPointZero(Op)) {
3716 RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3717 RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3721 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3722 SDValue Ptr = Ld->getBasePtr();
3723 RetVal1 = DAG.getLoad(MVT::i32, dl,
3724 Ld->getChain(), Ptr,
3725 Ld->getPointerInfo(),
3726 Ld->isVolatile(), Ld->isNonTemporal(),
3727 Ld->isInvariant(), Ld->getAlignment());
3729 EVT PtrType = Ptr.getValueType();
3730 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3731 SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3732 PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3733 RetVal2 = DAG.getLoad(MVT::i32, dl,
3734 Ld->getChain(), NewPtr,
3735 Ld->getPointerInfo().getWithOffset(4),
3736 Ld->isVolatile(), Ld->isNonTemporal(),
3737 Ld->isInvariant(), NewAlign);
3741 llvm_unreachable("Unknown VFP cmp argument!");
3744 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3745 /// f32 and even f64 comparisons to integer ones.
3747 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3748 SDValue Chain = Op.getOperand(0);
3749 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3750 SDValue LHS = Op.getOperand(2);
3751 SDValue RHS = Op.getOperand(3);
3752 SDValue Dest = Op.getOperand(4);
3755 bool LHSSeenZero = false;
3756 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3757 bool RHSSeenZero = false;
3758 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3759 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3760 // If unsafe fp math optimization is enabled and there are no other uses of
3761 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3762 // to an integer comparison.
3763 if (CC == ISD::SETOEQ)
3765 else if (CC == ISD::SETUNE)
3768 SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3770 if (LHS.getValueType() == MVT::f32) {
3771 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3772 bitcastf32Toi32(LHS, DAG), Mask);
3773 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3774 bitcastf32Toi32(RHS, DAG), Mask);
3775 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3776 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3777 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3778 Chain, Dest, ARMcc, CCR, Cmp);
3783 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3784 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3785 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3786 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3787 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3788 ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3789 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3790 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3791 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3797 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3798 SDValue Chain = Op.getOperand(0);
3799 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3800 SDValue LHS = Op.getOperand(2);
3801 SDValue RHS = Op.getOperand(3);
3802 SDValue Dest = Op.getOperand(4);
3805 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3806 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3809 // If softenSetCCOperands only returned one value, we should compare it to
3811 if (!RHS.getNode()) {
3812 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3817 if (LHS.getValueType() == MVT::i32) {
3819 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3820 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3821 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3822 Chain, Dest, ARMcc, CCR, Cmp);
3825 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3827 if (getTargetMachine().Options.UnsafeFPMath &&
3828 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3829 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3830 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3831 if (Result.getNode())
3835 ARMCC::CondCodes CondCode, CondCode2;
3836 FPCCToARMCC(CC, CondCode, CondCode2);
3838 SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3839 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3840 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3841 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3842 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3843 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3844 if (CondCode2 != ARMCC::AL) {
3845 ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3846 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3847 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3852 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3853 SDValue Chain = Op.getOperand(0);
3854 SDValue Table = Op.getOperand(1);
3855 SDValue Index = Op.getOperand(2);
3858 EVT PTy = getPointerTy();
3859 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3860 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3861 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3862 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3863 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3864 if (Subtarget->isThumb2()) {
3865 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3866 // which does another jump to the destination. This also makes it easier
3867 // to translate it to TBB / TBH later.
3868 // FIXME: This might not work if the function is extremely large.
3869 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3870 Addr, Op.getOperand(2), JTI);
3872 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3873 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3874 MachinePointerInfo::getJumpTable(),
3875 false, false, false, 0);
3876 Chain = Addr.getValue(1);
3877 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3878 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3880 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3881 MachinePointerInfo::getJumpTable(),
3882 false, false, false, 0);
3883 Chain = Addr.getValue(1);
3884 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3888 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3889 EVT VT = Op.getValueType();
3892 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3893 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3895 return DAG.UnrollVectorOp(Op.getNode());
3898 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3899 "Invalid type for custom lowering!");
3900 if (VT != MVT::v4i16)
3901 return DAG.UnrollVectorOp(Op.getNode());
3903 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3904 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3907 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3908 EVT VT = Op.getValueType();
3910 return LowerVectorFP_TO_INT(Op, DAG);
3911 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3913 if (Op.getOpcode() == ISD::FP_TO_SINT)
3914 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3917 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3919 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3920 /*isSigned*/ false, SDLoc(Op)).first;
3926 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3927 EVT VT = Op.getValueType();
3930 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3931 if (VT.getVectorElementType() == MVT::f32)
3933 return DAG.UnrollVectorOp(Op.getNode());
3936 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3937 "Invalid type for custom lowering!");
3938 if (VT != MVT::v4f32)
3939 return DAG.UnrollVectorOp(Op.getNode());
3943 switch (Op.getOpcode()) {
3944 default: llvm_unreachable("Invalid opcode!");
3945 case ISD::SINT_TO_FP:
3946 CastOpc = ISD::SIGN_EXTEND;
3947 Opc = ISD::SINT_TO_FP;
3949 case ISD::UINT_TO_FP:
3950 CastOpc = ISD::ZERO_EXTEND;
3951 Opc = ISD::UINT_TO_FP;
3955 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3956 return DAG.getNode(Opc, dl, VT, Op);
3959 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3960 EVT VT = Op.getValueType();
3962 return LowerVectorINT_TO_FP(Op, DAG);
3963 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3965 if (Op.getOpcode() == ISD::SINT_TO_FP)
3966 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3969 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3971 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3972 /*isSigned*/ false, SDLoc(Op)).first;
3978 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3979 // Implement fcopysign with a fabs and a conditional fneg.
3980 SDValue Tmp0 = Op.getOperand(0);
3981 SDValue Tmp1 = Op.getOperand(1);
3983 EVT VT = Op.getValueType();
3984 EVT SrcVT = Tmp1.getValueType();
3985 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3986 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3987 bool UseNEON = !InGPR && Subtarget->hasNEON();
3990 // Use VBSL to copy the sign bit.
3991 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3992 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3993 DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
3994 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3996 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3997 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3998 DAG.getConstant(32, dl, MVT::i32));
3999 else /*if (VT == MVT::f32)*/
4000 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4001 if (SrcVT == MVT::f32) {
4002 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4004 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4005 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4006 DAG.getConstant(32, dl, MVT::i32));
4007 } else if (VT == MVT::f32)
4008 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4009 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4010 DAG.getConstant(32, dl, MVT::i32));
4011 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4012 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4014 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4016 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4017 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4018 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4020 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4021 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4022 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4023 if (VT == MVT::f32) {
4024 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4025 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4026 DAG.getConstant(0, dl, MVT::i32));
4028 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4034 // Bitcast operand 1 to i32.
4035 if (SrcVT == MVT::f64)
4036 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4038 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4040 // Or in the signbit with integer operations.
4041 SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4042 SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4043 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4044 if (VT == MVT::f32) {
4045 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4046 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4047 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4048 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4051 // f64: Or the high part with signbit and then combine two parts.
4052 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4054 SDValue Lo = Tmp0.getValue(0);
4055 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4056 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4057 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4060 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4061 MachineFunction &MF = DAG.getMachineFunction();
4062 MachineFrameInfo *MFI = MF.getFrameInfo();
4063 MFI->setReturnAddressIsTaken(true);
4065 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4068 EVT VT = Op.getValueType();
4070 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4072 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4073 SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4074 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4075 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4076 MachinePointerInfo(), false, false, false, 0);
4079 // Return LR, which contains the return address. Mark it an implicit live-in.
4080 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4081 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4084 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4085 const ARMBaseRegisterInfo &ARI =
4086 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4087 MachineFunction &MF = DAG.getMachineFunction();
4088 MachineFrameInfo *MFI = MF.getFrameInfo();
4089 MFI->setFrameAddressIsTaken(true);
4091 EVT VT = Op.getValueType();
4092 SDLoc dl(Op); // FIXME probably not meaningful
4093 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4094 unsigned FrameReg = ARI.getFrameRegister(MF);
4095 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4097 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4098 MachinePointerInfo(),
4099 false, false, false, 0);
4103 // FIXME? Maybe this could be a TableGen attribute on some registers and
4104 // this table could be generated automatically from RegInfo.
4105 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4107 unsigned Reg = StringSwitch<unsigned>(RegName)
4108 .Case("sp", ARM::SP)
4112 report_fatal_error(Twine("Invalid register name \""
4113 + StringRef(RegName) + "\"."));
4116 // Result is 64 bit value so split into two 32 bit values and return as a
4118 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4119 SelectionDAG &DAG) {
4122 // This function is only supposed to be called for i64 type destination.
4123 assert(N->getValueType(0) == MVT::i64
4124 && "ExpandREAD_REGISTER called for non-i64 type result.");
4126 SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4127 DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4131 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4133 Results.push_back(Read.getOperand(0));
4136 /// ExpandBITCAST - If the target supports VFP, this function is called to
4137 /// expand a bit convert where either the source or destination type is i64 to
4138 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4139 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4140 /// vectors), since the legalizer won't know what to do with that.
4141 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4142 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4144 SDValue Op = N->getOperand(0);
4146 // This function is only supposed to be called for i64 types, either as the
4147 // source or destination of the bit convert.
4148 EVT SrcVT = Op.getValueType();
4149 EVT DstVT = N->getValueType(0);
4150 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4151 "ExpandBITCAST called for non-i64 type");
4153 // Turn i64->f64 into VMOVDRR.
4154 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4155 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4156 DAG.getConstant(0, dl, MVT::i32));
4157 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4158 DAG.getConstant(1, dl, MVT::i32));
4159 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4160 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4163 // Turn f64->i64 into VMOVRRD.
4164 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4166 if (TLI.isBigEndian() && SrcVT.isVector() &&
4167 SrcVT.getVectorNumElements() > 1)
4168 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4169 DAG.getVTList(MVT::i32, MVT::i32),
4170 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4172 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4173 DAG.getVTList(MVT::i32, MVT::i32), Op);
4174 // Merge the pieces into a single i64 value.
4175 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4181 /// getZeroVector - Returns a vector of specified type with all zero elements.
4182 /// Zero vectors are used to represent vector negation and in those cases
4183 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4184 /// not support i64 elements, so sometimes the zero vectors will need to be
4185 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4187 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4188 assert(VT.isVector() && "Expected a vector type");
4189 // The canonical modified immediate encoding of a zero vector is....0!
4190 SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4191 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4192 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4193 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4196 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4197 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4198 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4199 SelectionDAG &DAG) const {
4200 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4201 EVT VT = Op.getValueType();
4202 unsigned VTBits = VT.getSizeInBits();
4204 SDValue ShOpLo = Op.getOperand(0);
4205 SDValue ShOpHi = Op.getOperand(1);
4206 SDValue ShAmt = Op.getOperand(2);
4208 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4210 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4212 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4213 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4214 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4215 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4216 DAG.getConstant(VTBits, dl, MVT::i32));
4217 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4218 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4219 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4221 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4222 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4223 ISD::SETGE, ARMcc, DAG, dl);
4224 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4225 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4228 SDValue Ops[2] = { Lo, Hi };
4229 return DAG.getMergeValues(Ops, dl);
4232 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4233 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4234 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4235 SelectionDAG &DAG) const {
4236 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4237 EVT VT = Op.getValueType();
4238 unsigned VTBits = VT.getSizeInBits();
4240 SDValue ShOpLo = Op.getOperand(0);
4241 SDValue ShOpHi = Op.getOperand(1);
4242 SDValue ShAmt = Op.getOperand(2);
4245 assert(Op.getOpcode() == ISD::SHL_PARTS);
4246 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4247 DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4248 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4249 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4250 DAG.getConstant(VTBits, dl, MVT::i32));
4251 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4252 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4254 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4255 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4256 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4257 ISD::SETGE, ARMcc, DAG, dl);
4258 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4259 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4262 SDValue Ops[2] = { Lo, Hi };
4263 return DAG.getMergeValues(Ops, dl);
4266 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4267 SelectionDAG &DAG) const {
4268 // The rounding mode is in bits 23:22 of the FPSCR.
4269 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4270 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4271 // so that the shift + and get folded into a bitfield extract.
4273 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4274 DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4276 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4277 DAG.getConstant(1U << 22, dl, MVT::i32));
4278 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4279 DAG.getConstant(22, dl, MVT::i32));
4280 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4281 DAG.getConstant(3, dl, MVT::i32));
4284 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4285 const ARMSubtarget *ST) {
4286 EVT VT = N->getValueType(0);
4289 if (!ST->hasV6T2Ops())
4292 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4293 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4296 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4297 /// for each 16-bit element from operand, repeated. The basic idea is to
4298 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4300 /// Trace for v4i16:
4301 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4302 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4303 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4304 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4305 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4306 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4307 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4308 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4309 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4310 EVT VT = N->getValueType(0);
4313 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4314 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4315 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4316 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4317 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4318 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4321 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4322 /// bit-count for each 16-bit element from the operand. We need slightly
4323 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4324 /// 64/128-bit registers.
4326 /// Trace for v4i16:
4327 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4328 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4329 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4330 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4331 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4332 EVT VT = N->getValueType(0);
4335 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4336 if (VT.is64BitVector()) {
4337 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4338 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4339 DAG.getIntPtrConstant(0, DL));
4341 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4342 BitCounts, DAG.getIntPtrConstant(0, DL));
4343 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4347 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4348 /// bit-count for each 32-bit element from the operand. The idea here is
4349 /// to split the vector into 16-bit elements, leverage the 16-bit count
4350 /// routine, and then combine the results.
4352 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4353 /// input = [v0 v1 ] (vi: 32-bit elements)
4354 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4355 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4356 /// vrev: N0 = [k1 k0 k3 k2 ]
4358 /// N1 =+[k1 k0 k3 k2 ]
4360 /// N2 =+[k1 k3 k0 k2 ]
4362 /// Extended =+[k1 k3 k0 k2 ]
4364 /// Extracted=+[k1 k3 ]
4366 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4367 EVT VT = N->getValueType(0);
4370 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4372 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4373 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4374 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4375 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4376 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4378 if (VT.is64BitVector()) {
4379 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4380 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4381 DAG.getIntPtrConstant(0, DL));
4383 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4384 DAG.getIntPtrConstant(0, DL));
4385 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4389 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4390 const ARMSubtarget *ST) {
4391 EVT VT = N->getValueType(0);
4393 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4394 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4395 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4396 "Unexpected type for custom ctpop lowering");
4398 if (VT.getVectorElementType() == MVT::i32)
4399 return lowerCTPOP32BitElements(N, DAG);
4401 return lowerCTPOP16BitElements(N, DAG);
4404 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4405 const ARMSubtarget *ST) {
4406 EVT VT = N->getValueType(0);
4412 // Lower vector shifts on NEON to use VSHL.
4413 assert(ST->hasNEON() && "unexpected vector shift");
4415 // Left shifts translate directly to the vshiftu intrinsic.
4416 if (N->getOpcode() == ISD::SHL)
4417 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4418 DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4420 N->getOperand(0), N->getOperand(1));
4422 assert((N->getOpcode() == ISD::SRA ||
4423 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4425 // NEON uses the same intrinsics for both left and right shifts. For
4426 // right shifts, the shift amounts are negative, so negate the vector of
4428 EVT ShiftVT = N->getOperand(1).getValueType();
4429 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4430 getZeroVector(ShiftVT, DAG, dl),
4432 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4433 Intrinsic::arm_neon_vshifts :
4434 Intrinsic::arm_neon_vshiftu);
4435 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4436 DAG.getConstant(vshiftInt, dl, MVT::i32),
4437 N->getOperand(0), NegatedCount);
4440 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4441 const ARMSubtarget *ST) {
4442 EVT VT = N->getValueType(0);
4445 // We can get here for a node like i32 = ISD::SHL i32, i64
4449 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4450 "Unknown shift to lower!");
4452 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4453 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4454 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4457 // If we are in thumb mode, we don't have RRX.
4458 if (ST->isThumb1Only()) return SDValue();
4460 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4461 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4462 DAG.getConstant(0, dl, MVT::i32));
4463 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4464 DAG.getConstant(1, dl, MVT::i32));
4466 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4467 // captures the result into a carry flag.
4468 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4469 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4471 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4472 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4474 // Merge the pieces into a single i64 value.
4475 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4478 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4479 SDValue TmpOp0, TmpOp1;
4480 bool Invert = false;
4484 SDValue Op0 = Op.getOperand(0);
4485 SDValue Op1 = Op.getOperand(1);
4486 SDValue CC = Op.getOperand(2);
4487 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4488 EVT VT = Op.getValueType();
4489 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4492 if (Op1.getValueType().isFloatingPoint()) {
4493 switch (SetCCOpcode) {
4494 default: llvm_unreachable("Illegal FP comparison");
4496 case ISD::SETNE: Invert = true; // Fallthrough
4498 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4500 case ISD::SETLT: Swap = true; // Fallthrough
4502 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4504 case ISD::SETLE: Swap = true; // Fallthrough
4506 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4507 case ISD::SETUGE: Swap = true; // Fallthrough
4508 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4509 case ISD::SETUGT: Swap = true; // Fallthrough
4510 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4511 case ISD::SETUEQ: Invert = true; // Fallthrough
4513 // Expand this to (OLT | OGT).
4517 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4518 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4520 case ISD::SETUO: Invert = true; // Fallthrough
4522 // Expand this to (OLT | OGE).
4526 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4527 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4531 // Integer comparisons.
4532 switch (SetCCOpcode) {
4533 default: llvm_unreachable("Illegal integer comparison");
4534 case ISD::SETNE: Invert = true;
4535 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4536 case ISD::SETLT: Swap = true;
4537 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4538 case ISD::SETLE: Swap = true;
4539 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4540 case ISD::SETULT: Swap = true;
4541 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4542 case ISD::SETULE: Swap = true;
4543 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4546 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4547 if (Opc == ARMISD::VCEQ) {
4550 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4552 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4555 // Ignore bitconvert.
4556 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4557 AndOp = AndOp.getOperand(0);
4559 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4561 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4562 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4569 std::swap(Op0, Op1);
4571 // If one of the operands is a constant vector zero, attempt to fold the
4572 // comparison to a specialized compare-against-zero form.
4574 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4576 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4577 if (Opc == ARMISD::VCGE)
4578 Opc = ARMISD::VCLEZ;
4579 else if (Opc == ARMISD::VCGT)
4580 Opc = ARMISD::VCLTZ;
4585 if (SingleOp.getNode()) {
4588 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4590 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4592 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4594 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4596 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4598 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4601 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4604 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4607 Result = DAG.getNOT(dl, Result, VT);
4612 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4613 /// valid vector constant for a NEON instruction with a "modified immediate"
4614 /// operand (e.g., VMOV). If so, return the encoded value.
4615 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4616 unsigned SplatBitSize, SelectionDAG &DAG,
4617 SDLoc dl, EVT &VT, bool is128Bits,
4618 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, dl, 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, DL, 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, DL, 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, SDLoc(Op),
4801 VMovVT, false, VMOVModImm);
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, DL, MVT::i32));
4816 // Finally, try a VMVN.i32
4817 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), 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, DL, 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 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5067 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5068 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5069 unsigned &WhichResult,
5072 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5073 return ARMISD::VTRN;
5074 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5075 return ARMISD::VUZP;
5076 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5077 return ARMISD::VZIP;
5080 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5081 return ARMISD::VTRN;
5082 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5083 return ARMISD::VUZP;
5084 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5085 return ARMISD::VZIP;
5090 /// \return true if this is a reverse operation on an vector.
5091 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5092 unsigned NumElts = VT.getVectorNumElements();
5093 // Make sure the mask has the right size.
5094 if (NumElts != M.size())
5097 // Look for <15, ..., 3, -1, 1, 0>.
5098 for (unsigned i = 0; i != NumElts; ++i)
5099 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5105 // If N is an integer constant that can be moved into a register in one
5106 // instruction, return an SDValue of such a constant (will become a MOV
5107 // instruction). Otherwise return null.
5108 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5109 const ARMSubtarget *ST, SDLoc dl) {
5111 if (!isa<ConstantSDNode>(N))
5113 Val = cast<ConstantSDNode>(N)->getZExtValue();
5115 if (ST->isThumb1Only()) {
5116 if (Val <= 255 || ~Val <= 255)
5117 return DAG.getConstant(Val, dl, MVT::i32);
5119 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5120 return DAG.getConstant(Val, dl, MVT::i32);
5125 // If this is a case we can't handle, return null and let the default
5126 // expansion code take care of it.
5127 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5128 const ARMSubtarget *ST) const {
5129 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5131 EVT VT = Op.getValueType();
5133 APInt SplatBits, SplatUndef;
5134 unsigned SplatBitSize;
5136 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5137 if (SplatBitSize <= 64) {
5138 // Check if an immediate VMOV works.
5140 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5141 SplatUndef.getZExtValue(), SplatBitSize,
5142 DAG, dl, VmovVT, VT.is128BitVector(),
5144 if (Val.getNode()) {
5145 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5146 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5149 // Try an immediate VMVN.
5150 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5151 Val = isNEONModifiedImm(NegatedImm,
5152 SplatUndef.getZExtValue(), SplatBitSize,
5153 DAG, dl, VmovVT, VT.is128BitVector(),
5155 if (Val.getNode()) {
5156 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5157 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5160 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5161 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5162 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5164 SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5165 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5171 // Scan through the operands to see if only one value is used.
5173 // As an optimisation, even if more than one value is used it may be more
5174 // profitable to splat with one value then change some lanes.
5176 // Heuristically we decide to do this if the vector has a "dominant" value,
5177 // defined as splatted to more than half of the lanes.
5178 unsigned NumElts = VT.getVectorNumElements();
5179 bool isOnlyLowElement = true;
5180 bool usesOnlyOneValue = true;
5181 bool hasDominantValue = false;
5182 bool isConstant = true;
5184 // Map of the number of times a particular SDValue appears in the
5186 DenseMap<SDValue, unsigned> ValueCounts;
5188 for (unsigned i = 0; i < NumElts; ++i) {
5189 SDValue V = Op.getOperand(i);
5190 if (V.getOpcode() == ISD::UNDEF)
5193 isOnlyLowElement = false;
5194 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5197 ValueCounts.insert(std::make_pair(V, 0));
5198 unsigned &Count = ValueCounts[V];
5200 // Is this value dominant? (takes up more than half of the lanes)
5201 if (++Count > (NumElts / 2)) {
5202 hasDominantValue = true;
5206 if (ValueCounts.size() != 1)
5207 usesOnlyOneValue = false;
5208 if (!Value.getNode() && ValueCounts.size() > 0)
5209 Value = ValueCounts.begin()->first;
5211 if (ValueCounts.size() == 0)
5212 return DAG.getUNDEF(VT);
5214 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5215 // Keep going if we are hitting this case.
5216 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5217 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5219 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5221 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5222 // i32 and try again.
5223 if (hasDominantValue && EltSize <= 32) {
5227 // If we are VDUPing a value that comes directly from a vector, that will
5228 // cause an unnecessary move to and from a GPR, where instead we could
5229 // just use VDUPLANE. We can only do this if the lane being extracted
5230 // is at a constant index, as the VDUP from lane instructions only have
5231 // constant-index forms.
5232 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5233 isa<ConstantSDNode>(Value->getOperand(1))) {
5234 // We need to create a new undef vector to use for the VDUPLANE if the
5235 // size of the vector from which we get the value is different than the
5236 // size of the vector that we need to create. We will insert the element
5237 // such that the register coalescer will remove unnecessary copies.
5238 if (VT != Value->getOperand(0).getValueType()) {
5239 ConstantSDNode *constIndex;
5240 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5241 assert(constIndex && "The index is not a constant!");
5242 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5243 VT.getVectorNumElements();
5244 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5245 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5246 Value, DAG.getConstant(index, dl, MVT::i32)),
5247 DAG.getConstant(index, dl, MVT::i32));
5249 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5250 Value->getOperand(0), Value->getOperand(1));
5252 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5254 if (!usesOnlyOneValue) {
5255 // The dominant value was splatted as 'N', but we now have to insert
5256 // all differing elements.
5257 for (unsigned I = 0; I < NumElts; ++I) {
5258 if (Op.getOperand(I) == Value)
5260 SmallVector<SDValue, 3> Ops;
5262 Ops.push_back(Op.getOperand(I));
5263 Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5264 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5269 if (VT.getVectorElementType().isFloatingPoint()) {
5270 SmallVector<SDValue, 8> Ops;
5271 for (unsigned i = 0; i < NumElts; ++i)
5272 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5274 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5275 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5276 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5278 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5280 if (usesOnlyOneValue) {
5281 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5282 if (isConstant && Val.getNode())
5283 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5287 // If all elements are constants and the case above didn't get hit, fall back
5288 // to the default expansion, which will generate a load from the constant
5293 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5295 SDValue shuffle = ReconstructShuffle(Op, DAG);
5296 if (shuffle != SDValue())
5300 // Vectors with 32- or 64-bit elements can be built by directly assigning
5301 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5302 // will be legalized.
5303 if (EltSize >= 32) {
5304 // Do the expansion with floating-point types, since that is what the VFP
5305 // registers are defined to use, and since i64 is not legal.
5306 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5307 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5308 SmallVector<SDValue, 8> Ops;
5309 for (unsigned i = 0; i < NumElts; ++i)
5310 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5311 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5312 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5315 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5316 // know the default expansion would otherwise fall back on something even
5317 // worse. For a vector with one or two non-undef values, that's
5318 // scalar_to_vector for the elements followed by a shuffle (provided the
5319 // shuffle is valid for the target) and materialization element by element
5320 // on the stack followed by a load for everything else.
5321 if (!isConstant && !usesOnlyOneValue) {
5322 SDValue Vec = DAG.getUNDEF(VT);
5323 for (unsigned i = 0 ; i < NumElts; ++i) {
5324 SDValue V = Op.getOperand(i);
5325 if (V.getOpcode() == ISD::UNDEF)
5327 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5328 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5336 // Gather data to see if the operation can be modelled as a
5337 // shuffle in combination with VEXTs.
5338 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5339 SelectionDAG &DAG) const {
5341 EVT VT = Op.getValueType();
5342 unsigned NumElts = VT.getVectorNumElements();
5344 SmallVector<SDValue, 2> SourceVecs;
5345 SmallVector<unsigned, 2> MinElts;
5346 SmallVector<unsigned, 2> MaxElts;
5348 for (unsigned i = 0; i < NumElts; ++i) {
5349 SDValue V = Op.getOperand(i);
5350 if (V.getOpcode() == ISD::UNDEF)
5352 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5353 // A shuffle can only come from building a vector from various
5354 // elements of other vectors.
5356 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5357 VT.getVectorElementType()) {
5358 // This code doesn't know how to handle shuffles where the vector
5359 // element types do not match (this happens because type legalization
5360 // promotes the return type of EXTRACT_VECTOR_ELT).
5361 // FIXME: It might be appropriate to extend this code to handle
5362 // mismatched types.
5366 // Record this extraction against the appropriate vector if possible...
5367 SDValue SourceVec = V.getOperand(0);
5368 // If the element number isn't a constant, we can't effectively
5369 // analyze what's going on.
5370 if (!isa<ConstantSDNode>(V.getOperand(1)))
5372 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5373 bool FoundSource = false;
5374 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5375 if (SourceVecs[j] == SourceVec) {
5376 if (MinElts[j] > EltNo)
5378 if (MaxElts[j] < EltNo)
5385 // Or record a new source if not...
5387 SourceVecs.push_back(SourceVec);
5388 MinElts.push_back(EltNo);
5389 MaxElts.push_back(EltNo);
5393 // Currently only do something sane when at most two source vectors
5395 if (SourceVecs.size() > 2)
5398 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5399 int VEXTOffsets[2] = {0, 0};
5401 // This loop extracts the usage patterns of the source vectors
5402 // and prepares appropriate SDValues for a shuffle if possible.
5403 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5404 if (SourceVecs[i].getValueType() == VT) {
5405 // No VEXT necessary
5406 ShuffleSrcs[i] = SourceVecs[i];
5409 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5410 // It probably isn't worth padding out a smaller vector just to
5411 // break it down again in a shuffle.
5415 // Since only 64-bit and 128-bit vectors are legal on ARM and
5416 // we've eliminated the other cases...
5417 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5418 "unexpected vector sizes in ReconstructShuffle");
5420 if (MaxElts[i] - MinElts[i] >= NumElts) {
5421 // Span too large for a VEXT to cope
5425 if (MinElts[i] >= NumElts) {
5426 // The extraction can just take the second half
5427 VEXTOffsets[i] = NumElts;
5428 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5430 DAG.getIntPtrConstant(NumElts, dl));
5431 } else if (MaxElts[i] < NumElts) {
5432 // The extraction can just take the first half
5434 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5436 DAG.getIntPtrConstant(0, dl));
5438 // An actual VEXT is needed
5439 VEXTOffsets[i] = MinElts[i];
5440 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5442 DAG.getIntPtrConstant(0, dl));
5443 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5445 DAG.getIntPtrConstant(NumElts, dl));
5446 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5447 DAG.getConstant(VEXTOffsets[i], dl,
5452 SmallVector<int, 8> Mask;
5454 for (unsigned i = 0; i < NumElts; ++i) {
5455 SDValue Entry = Op.getOperand(i);
5456 if (Entry.getOpcode() == ISD::UNDEF) {
5461 SDValue ExtractVec = Entry.getOperand(0);
5462 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5463 .getOperand(1))->getSExtValue();
5464 if (ExtractVec == SourceVecs[0]) {
5465 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5467 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5471 // Final check before we try to produce nonsense...
5472 if (isShuffleMaskLegal(Mask, VT))
5473 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5479 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5480 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5481 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5482 /// are assumed to be legal.
5484 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5486 if (VT.getVectorNumElements() == 4 &&
5487 (VT.is128BitVector() || VT.is64BitVector())) {
5488 unsigned PFIndexes[4];
5489 for (unsigned i = 0; i != 4; ++i) {
5493 PFIndexes[i] = M[i];
5496 // Compute the index in the perfect shuffle table.
5497 unsigned PFTableIndex =
5498 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5499 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5500 unsigned Cost = (PFEntry >> 30);
5506 bool ReverseVEXT, isV_UNDEF;
5507 unsigned Imm, WhichResult;
5509 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5510 return (EltSize >= 32 ||
5511 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5512 isVREVMask(M, VT, 64) ||
5513 isVREVMask(M, VT, 32) ||
5514 isVREVMask(M, VT, 16) ||
5515 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5516 isVTBLMask(M, VT) ||
5517 isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5518 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5521 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5522 /// the specified operations to build the shuffle.
5523 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5524 SDValue RHS, SelectionDAG &DAG,
5526 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5527 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5528 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5531 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5540 OP_VUZPL, // VUZP, left result
5541 OP_VUZPR, // VUZP, right result
5542 OP_VZIPL, // VZIP, left result
5543 OP_VZIPR, // VZIP, right result
5544 OP_VTRNL, // VTRN, left result
5545 OP_VTRNR // VTRN, right result
5548 if (OpNum == OP_COPY) {
5549 if (LHSID == (1*9+2)*9+3) return LHS;
5550 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5554 SDValue OpLHS, OpRHS;
5555 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5556 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5557 EVT VT = OpLHS.getValueType();
5560 default: llvm_unreachable("Unknown shuffle opcode!");
5562 // VREV divides the vector in half and swaps within the half.
5563 if (VT.getVectorElementType() == MVT::i32 ||
5564 VT.getVectorElementType() == MVT::f32)
5565 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5566 // vrev <4 x i16> -> VREV32
5567 if (VT.getVectorElementType() == MVT::i16)
5568 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5569 // vrev <4 x i8> -> VREV16
5570 assert(VT.getVectorElementType() == MVT::i8);
5571 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5576 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5577 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5581 return DAG.getNode(ARMISD::VEXT, dl, VT,
5583 DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5586 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5587 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5590 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5591 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5594 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5595 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5599 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5600 ArrayRef<int> ShuffleMask,
5601 SelectionDAG &DAG) {
5602 // Check to see if we can use the VTBL instruction.
5603 SDValue V1 = Op.getOperand(0);
5604 SDValue V2 = Op.getOperand(1);
5607 SmallVector<SDValue, 8> VTBLMask;
5608 for (ArrayRef<int>::iterator
5609 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5610 VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5612 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5613 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5614 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5616 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5617 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5620 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5621 SelectionDAG &DAG) {
5623 SDValue OpLHS = Op.getOperand(0);
5624 EVT VT = OpLHS.getValueType();
5626 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5627 "Expect an v8i16/v16i8 type");
5628 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5629 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5630 // extract the first 8 bytes into the top double word and the last 8 bytes
5631 // into the bottom double word. The v8i16 case is similar.
5632 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5633 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5634 DAG.getConstant(ExtractNum, DL, MVT::i32));
5637 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5638 SDValue V1 = Op.getOperand(0);
5639 SDValue V2 = Op.getOperand(1);
5641 EVT VT = Op.getValueType();
5642 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5644 // Convert shuffles that are directly supported on NEON to target-specific
5645 // DAG nodes, instead of keeping them as shuffles and matching them again
5646 // during code selection. This is more efficient and avoids the possibility
5647 // of inconsistencies between legalization and selection.
5648 // FIXME: floating-point vectors should be canonicalized to integer vectors
5649 // of the same time so that they get CSEd properly.
5650 ArrayRef<int> ShuffleMask = SVN->getMask();
5652 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5653 if (EltSize <= 32) {
5654 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5655 int Lane = SVN->getSplatIndex();
5656 // If this is undef splat, generate it via "just" vdup, if possible.
5657 if (Lane == -1) Lane = 0;
5659 // Test if V1 is a SCALAR_TO_VECTOR.
5660 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5661 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5663 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5664 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5666 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5667 !isa<ConstantSDNode>(V1.getOperand(0))) {
5668 bool IsScalarToVector = true;
5669 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5670 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5671 IsScalarToVector = false;
5674 if (IsScalarToVector)
5675 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5677 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5678 DAG.getConstant(Lane, dl, MVT::i32));
5683 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5686 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5687 DAG.getConstant(Imm, dl, MVT::i32));
5690 if (isVREVMask(ShuffleMask, VT, 64))
5691 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5692 if (isVREVMask(ShuffleMask, VT, 32))
5693 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5694 if (isVREVMask(ShuffleMask, VT, 16))
5695 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5697 if (V2->getOpcode() == ISD::UNDEF &&
5698 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5699 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5700 DAG.getConstant(Imm, dl, MVT::i32));
5703 // Check for Neon shuffles that modify both input vectors in place.
5704 // If both results are used, i.e., if there are two shuffles with the same
5705 // source operands and with masks corresponding to both results of one of
5706 // these operations, DAG memoization will ensure that a single node is
5707 // used for both shuffles.
5708 unsigned WhichResult;
5710 if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5711 ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5714 return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5715 .getValue(WhichResult);
5720 // If the shuffle is not directly supported and it has 4 elements, use
5721 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5722 unsigned NumElts = VT.getVectorNumElements();
5724 unsigned PFIndexes[4];
5725 for (unsigned i = 0; i != 4; ++i) {
5726 if (ShuffleMask[i] < 0)
5729 PFIndexes[i] = ShuffleMask[i];
5732 // Compute the index in the perfect shuffle table.
5733 unsigned PFTableIndex =
5734 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5735 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5736 unsigned Cost = (PFEntry >> 30);
5739 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5742 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5743 if (EltSize >= 32) {
5744 // Do the expansion with floating-point types, since that is what the VFP
5745 // registers are defined to use, and since i64 is not legal.
5746 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5747 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5748 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5749 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5750 SmallVector<SDValue, 8> Ops;
5751 for (unsigned i = 0; i < NumElts; ++i) {
5752 if (ShuffleMask[i] < 0)
5753 Ops.push_back(DAG.getUNDEF(EltVT));
5755 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5756 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5757 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5760 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5761 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5764 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5765 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5767 if (VT == MVT::v8i8) {
5768 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5769 if (NewOp.getNode())
5776 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5777 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5778 SDValue Lane = Op.getOperand(2);
5779 if (!isa<ConstantSDNode>(Lane))
5785 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5786 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5787 SDValue Lane = Op.getOperand(1);
5788 if (!isa<ConstantSDNode>(Lane))
5791 SDValue Vec = Op.getOperand(0);
5792 if (Op.getValueType() == MVT::i32 &&
5793 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5795 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5801 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5802 // The only time a CONCAT_VECTORS operation can have legal types is when
5803 // two 64-bit vectors are concatenated to a 128-bit vector.
5804 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5805 "unexpected CONCAT_VECTORS");
5807 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5808 SDValue Op0 = Op.getOperand(0);
5809 SDValue Op1 = Op.getOperand(1);
5810 if (Op0.getOpcode() != ISD::UNDEF)
5811 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5812 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5813 DAG.getIntPtrConstant(0, dl));
5814 if (Op1.getOpcode() != ISD::UNDEF)
5815 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5816 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5817 DAG.getIntPtrConstant(1, dl));
5818 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5821 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5822 /// element has been zero/sign-extended, depending on the isSigned parameter,
5823 /// from an integer type half its size.
5824 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5826 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5827 EVT VT = N->getValueType(0);
5828 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5829 SDNode *BVN = N->getOperand(0).getNode();
5830 if (BVN->getValueType(0) != MVT::v4i32 ||
5831 BVN->getOpcode() != ISD::BUILD_VECTOR)
5833 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5834 unsigned HiElt = 1 - LoElt;
5835 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5836 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5837 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5838 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5839 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5842 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5843 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5846 if (Hi0->isNullValue() && Hi1->isNullValue())
5852 if (N->getOpcode() != ISD::BUILD_VECTOR)
5855 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5856 SDNode *Elt = N->getOperand(i).getNode();
5857 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5858 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5859 unsigned HalfSize = EltSize / 2;
5861 if (!isIntN(HalfSize, C->getSExtValue()))
5864 if (!isUIntN(HalfSize, C->getZExtValue()))
5875 /// isSignExtended - Check if a node is a vector value that is sign-extended
5876 /// or a constant BUILD_VECTOR with sign-extended elements.
5877 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5878 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5880 if (isExtendedBUILD_VECTOR(N, DAG, true))
5885 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5886 /// or a constant BUILD_VECTOR with zero-extended elements.
5887 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5888 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5890 if (isExtendedBUILD_VECTOR(N, DAG, false))
5895 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5896 if (OrigVT.getSizeInBits() >= 64)
5899 assert(OrigVT.isSimple() && "Expecting a simple value type");
5901 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5902 switch (OrigSimpleTy) {
5903 default: llvm_unreachable("Unexpected Vector Type");
5912 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5913 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5914 /// We insert the required extension here to get the vector to fill a D register.
5915 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5918 unsigned ExtOpcode) {
5919 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5920 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5921 // 64-bits we need to insert a new extension so that it will be 64-bits.
5922 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5923 if (OrigTy.getSizeInBits() >= 64)
5926 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5927 EVT NewVT = getExtensionTo64Bits(OrigTy);
5929 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5932 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5933 /// does not do any sign/zero extension. If the original vector is less
5934 /// than 64 bits, an appropriate extension will be added after the load to
5935 /// reach a total size of 64 bits. We have to add the extension separately
5936 /// because ARM does not have a sign/zero extending load for vectors.
5937 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5938 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5940 // The load already has the right type.
5941 if (ExtendedTy == LD->getMemoryVT())
5942 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5943 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5944 LD->isNonTemporal(), LD->isInvariant(),
5945 LD->getAlignment());
5947 // We need to create a zextload/sextload. We cannot just create a load
5948 // followed by a zext/zext node because LowerMUL is also run during normal
5949 // operation legalization where we can't create illegal types.
5950 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5951 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5952 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5953 LD->isNonTemporal(), LD->getAlignment());
5956 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5957 /// extending load, or BUILD_VECTOR with extended elements, return the
5958 /// unextended value. The unextended vector should be 64 bits so that it can
5959 /// be used as an operand to a VMULL instruction. If the original vector size
5960 /// before extension is less than 64 bits we add a an extension to resize
5961 /// the vector to 64 bits.
5962 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5963 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5964 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5965 N->getOperand(0)->getValueType(0),
5969 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5970 return SkipLoadExtensionForVMULL(LD, DAG);
5972 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5973 // have been legalized as a BITCAST from v4i32.
5974 if (N->getOpcode() == ISD::BITCAST) {
5975 SDNode *BVN = N->getOperand(0).getNode();
5976 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5977 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5978 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5979 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5980 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5982 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5983 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5984 EVT VT = N->getValueType(0);
5985 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5986 unsigned NumElts = VT.getVectorNumElements();
5987 MVT TruncVT = MVT::getIntegerVT(EltSize);
5988 SmallVector<SDValue, 8> Ops;
5990 for (unsigned i = 0; i != NumElts; ++i) {
5991 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5992 const APInt &CInt = C->getAPIntValue();
5993 // Element types smaller than 32 bits are not legal, so use i32 elements.
5994 // The values are implicitly truncated so sext vs. zext doesn't matter.
5995 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
5997 return DAG.getNode(ISD::BUILD_VECTOR, dl,
5998 MVT::getVectorVT(TruncVT, NumElts), Ops);
6001 static bool isAddSubSExt(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 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6012 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6013 unsigned Opcode = N->getOpcode();
6014 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6015 SDNode *N0 = N->getOperand(0).getNode();
6016 SDNode *N1 = N->getOperand(1).getNode();
6017 return N0->hasOneUse() && N1->hasOneUse() &&
6018 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6023 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6024 // Multiplications are only custom-lowered for 128-bit vectors so that
6025 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6026 EVT VT = Op.getValueType();
6027 assert(VT.is128BitVector() && VT.isInteger() &&
6028 "unexpected type for custom-lowering ISD::MUL");
6029 SDNode *N0 = Op.getOperand(0).getNode();
6030 SDNode *N1 = Op.getOperand(1).getNode();
6031 unsigned NewOpc = 0;
6033 bool isN0SExt = isSignExtended(N0, DAG);
6034 bool isN1SExt = isSignExtended(N1, DAG);
6035 if (isN0SExt && isN1SExt)
6036 NewOpc = ARMISD::VMULLs;
6038 bool isN0ZExt = isZeroExtended(N0, DAG);
6039 bool isN1ZExt = isZeroExtended(N1, DAG);
6040 if (isN0ZExt && isN1ZExt)
6041 NewOpc = ARMISD::VMULLu;
6042 else if (isN1SExt || isN1ZExt) {
6043 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6044 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6045 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6046 NewOpc = ARMISD::VMULLs;
6048 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6049 NewOpc = ARMISD::VMULLu;
6051 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6053 NewOpc = ARMISD::VMULLu;
6059 if (VT == MVT::v2i64)
6060 // Fall through to expand this. It is not legal.
6063 // Other vector multiplications are legal.
6068 // Legalize to a VMULL instruction.
6071 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6073 Op0 = SkipExtensionForVMULL(N0, DAG);
6074 assert(Op0.getValueType().is64BitVector() &&
6075 Op1.getValueType().is64BitVector() &&
6076 "unexpected types for extended operands to VMULL");
6077 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6080 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6081 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6088 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6089 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6090 EVT Op1VT = Op1.getValueType();
6091 return DAG.getNode(N0->getOpcode(), DL, VT,
6092 DAG.getNode(NewOpc, DL, VT,
6093 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6094 DAG.getNode(NewOpc, DL, VT,
6095 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6099 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6101 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6102 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6103 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6104 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6105 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6106 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6107 // Get reciprocal estimate.
6108 // float4 recip = vrecpeq_f32(yf);
6109 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6110 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6112 // Because char has a smaller range than uchar, we can actually get away
6113 // without any newton steps. This requires that we use a weird bias
6114 // of 0xb000, however (again, this has been exhaustively tested).
6115 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6116 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6117 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6118 Y = DAG.getConstant(0xb000, dl, MVT::i32);
6119 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6120 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6121 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6122 // Convert back to short.
6123 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6124 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6129 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6131 // Convert to float.
6132 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6133 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6134 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6135 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6136 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6137 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6139 // Use reciprocal estimate and one refinement step.
6140 // float4 recip = vrecpeq_f32(yf);
6141 // recip *= vrecpsq_f32(yf, recip);
6142 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6143 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6145 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6146 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6148 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6149 // Because short has a smaller range than ushort, we can actually get away
6150 // with only a single newton step. This requires that we use a weird bias
6151 // of 89, however (again, this has been exhaustively tested).
6152 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6153 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6154 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6155 N1 = DAG.getConstant(0x89, dl, MVT::i32);
6156 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6157 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6158 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6159 // Convert back to integer and return.
6160 // return vmovn_s32(vcvt_s32_f32(result));
6161 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6162 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6166 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6167 EVT VT = Op.getValueType();
6168 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6169 "unexpected type for custom-lowering ISD::SDIV");
6172 SDValue N0 = Op.getOperand(0);
6173 SDValue N1 = Op.getOperand(1);
6176 if (VT == MVT::v8i8) {
6177 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6178 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6180 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6181 DAG.getIntPtrConstant(4, dl));
6182 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6183 DAG.getIntPtrConstant(4, dl));
6184 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6185 DAG.getIntPtrConstant(0, dl));
6186 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6187 DAG.getIntPtrConstant(0, dl));
6189 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6190 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6192 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6193 N0 = LowerCONCAT_VECTORS(N0, DAG);
6195 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6198 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6201 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6202 EVT VT = Op.getValueType();
6203 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6204 "unexpected type for custom-lowering ISD::UDIV");
6207 SDValue N0 = Op.getOperand(0);
6208 SDValue N1 = Op.getOperand(1);
6211 if (VT == MVT::v8i8) {
6212 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6213 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6215 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6216 DAG.getIntPtrConstant(4, dl));
6217 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6218 DAG.getIntPtrConstant(4, dl));
6219 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6220 DAG.getIntPtrConstant(0, dl));
6221 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6222 DAG.getIntPtrConstant(0, dl));
6224 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6225 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6227 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6228 N0 = LowerCONCAT_VECTORS(N0, DAG);
6230 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6231 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6237 // v4i16 sdiv ... Convert to float.
6238 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6239 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6240 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6241 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6242 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6243 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6245 // Use reciprocal estimate and two refinement steps.
6246 // float4 recip = vrecpeq_f32(yf);
6247 // recip *= vrecpsq_f32(yf, recip);
6248 // recip *= vrecpsq_f32(yf, recip);
6249 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6250 DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6252 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6253 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6255 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6256 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6257 DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6259 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6260 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6261 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6262 // and that it will never cause us to return an answer too large).
6263 // float4 result = as_float4(as_int4(xf*recip) + 2);
6264 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6265 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6266 N1 = DAG.getConstant(2, dl, MVT::i32);
6267 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6268 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6269 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6270 // Convert back to integer and return.
6271 // return vmovn_u32(vcvt_s32_f32(result));
6272 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6273 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6277 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6278 EVT VT = Op.getNode()->getValueType(0);
6279 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6282 bool ExtraOp = false;
6283 switch (Op.getOpcode()) {
6284 default: llvm_unreachable("Invalid code");
6285 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6286 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6287 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6288 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6292 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6294 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6295 Op.getOperand(1), Op.getOperand(2));
6298 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6299 assert(Subtarget->isTargetDarwin());
6301 // For iOS, we want to call an alternative entry point: __sincos_stret,
6302 // return values are passed via sret.
6304 SDValue Arg = Op.getOperand(0);
6305 EVT ArgVT = Arg.getValueType();
6306 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6308 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6309 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6311 // Pair of floats / doubles used to pass the result.
6312 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6314 // Create stack object for sret.
6315 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6316 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6317 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6318 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6324 Entry.Ty = RetTy->getPointerTo();
6325 Entry.isSExt = false;
6326 Entry.isZExt = false;
6327 Entry.isSRet = true;
6328 Args.push_back(Entry);
6332 Entry.isSExt = false;
6333 Entry.isZExt = false;
6334 Args.push_back(Entry);
6336 const char *LibcallName = (ArgVT == MVT::f64)
6337 ? "__sincos_stret" : "__sincosf_stret";
6338 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6340 TargetLowering::CallLoweringInfo CLI(DAG);
6341 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6342 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6344 .setDiscardResult();
6346 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6348 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6349 MachinePointerInfo(), false, false, false, 0);
6351 // Address of cos field.
6352 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6353 DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6354 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6355 MachinePointerInfo(), false, false, false, 0);
6357 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6358 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6359 LoadSin.getValue(0), LoadCos.getValue(0));
6362 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6363 // Monotonic load/store is legal for all targets
6364 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6367 // Acquire/Release load/store is not legal for targets without a
6368 // dmb or equivalent available.
6372 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6373 SmallVectorImpl<SDValue> &Results,
6375 const ARMSubtarget *Subtarget) {
6377 SDValue Cycles32, OutChain;
6379 if (Subtarget->hasPerfMon()) {
6380 // Under Power Management extensions, the cycle-count is:
6381 // mrc p15, #0, <Rt>, c9, c13, #0
6382 SDValue Ops[] = { N->getOperand(0), // Chain
6383 DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6384 DAG.getConstant(15, DL, MVT::i32),
6385 DAG.getConstant(0, DL, MVT::i32),
6386 DAG.getConstant(9, DL, MVT::i32),
6387 DAG.getConstant(13, DL, MVT::i32),
6388 DAG.getConstant(0, DL, MVT::i32)
6391 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6392 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6393 OutChain = Cycles32.getValue(1);
6395 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6396 // there are older ARM CPUs that have implementation-specific ways of
6397 // obtaining this information (FIXME!).
6398 Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6399 OutChain = DAG.getEntryNode();
6403 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6404 Cycles32, DAG.getConstant(0, DL, MVT::i32));
6405 Results.push_back(Cycles64);
6406 Results.push_back(OutChain);
6409 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6410 switch (Op.getOpcode()) {
6411 default: llvm_unreachable("Don't know how to custom lower this!");
6412 case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6413 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6414 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6415 case ISD::GlobalAddress:
6416 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6417 default: llvm_unreachable("unknown object format");
6419 return LowerGlobalAddressWindows(Op, DAG);
6421 return LowerGlobalAddressELF(Op, DAG);
6423 return LowerGlobalAddressDarwin(Op, DAG);
6425 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6426 case ISD::SELECT: return LowerSELECT(Op, DAG);
6427 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6428 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6429 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6430 case ISD::VASTART: return LowerVASTART(Op, DAG);
6431 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6432 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6433 case ISD::SINT_TO_FP:
6434 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6435 case ISD::FP_TO_SINT:
6436 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6437 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6438 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6439 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6440 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6441 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6442 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6443 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6445 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6448 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6449 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6450 case ISD::SRL_PARTS:
6451 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6452 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6453 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6454 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6455 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6456 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6457 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6458 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6459 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6460 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6461 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6462 case ISD::MUL: return LowerMUL(Op, DAG);
6463 case ISD::SDIV: return LowerSDIV(Op, DAG);
6464 case ISD::UDIV: return LowerUDIV(Op, DAG);
6468 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6473 return LowerXALUO(Op, DAG);
6474 case ISD::ATOMIC_LOAD:
6475 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6476 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6478 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6479 case ISD::DYNAMIC_STACKALLOC:
6480 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6481 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6482 llvm_unreachable("Don't know how to custom lower this!");
6483 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6484 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6488 /// ReplaceNodeResults - Replace the results of node with an illegal result
6489 /// type with new values built out of custom code.
6490 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6491 SmallVectorImpl<SDValue>&Results,
6492 SelectionDAG &DAG) const {
6494 switch (N->getOpcode()) {
6496 llvm_unreachable("Don't know how to custom expand this!");
6497 case ISD::READ_REGISTER:
6498 ExpandREAD_REGISTER(N, Results, DAG);
6501 Res = ExpandBITCAST(N, DAG);
6505 Res = Expand64BitShift(N, DAG, Subtarget);
6507 case ISD::READCYCLECOUNTER:
6508 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6512 Results.push_back(Res);
6515 //===----------------------------------------------------------------------===//
6516 // ARM Scheduler Hooks
6517 //===----------------------------------------------------------------------===//
6519 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6520 /// registers the function context.
6521 void ARMTargetLowering::
6522 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6523 MachineBasicBlock *DispatchBB, int FI) const {
6524 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6525 DebugLoc dl = MI->getDebugLoc();
6526 MachineFunction *MF = MBB->getParent();
6527 MachineRegisterInfo *MRI = &MF->getRegInfo();
6528 MachineConstantPool *MCP = MF->getConstantPool();
6529 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6530 const Function *F = MF->getFunction();
6532 bool isThumb = Subtarget->isThumb();
6533 bool isThumb2 = Subtarget->isThumb2();
6535 unsigned PCLabelId = AFI->createPICLabelUId();
6536 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6537 ARMConstantPoolValue *CPV =
6538 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6539 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6541 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6542 : &ARM::GPRRegClass;
6544 // Grab constant pool and fixed stack memory operands.
6545 MachineMemOperand *CPMMO =
6546 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6547 MachineMemOperand::MOLoad, 4, 4);
6549 MachineMemOperand *FIMMOSt =
6550 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6551 MachineMemOperand::MOStore, 4, 4);
6553 // Load the address of the dispatch MBB into the jump buffer.
6555 // Incoming value: jbuf
6556 // ldr.n r5, LCPI1_1
6559 // str r5, [$jbuf, #+4] ; &jbuf[1]
6560 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6561 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6562 .addConstantPoolIndex(CPI)
6563 .addMemOperand(CPMMO));
6564 // Set the low bit because of thumb mode.
6565 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6567 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6568 .addReg(NewVReg1, RegState::Kill)
6570 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6571 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6572 .addReg(NewVReg2, RegState::Kill)
6574 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6575 .addReg(NewVReg3, RegState::Kill)
6577 .addImm(36) // &jbuf[1] :: pc
6578 .addMemOperand(FIMMOSt));
6579 } else if (isThumb) {
6580 // Incoming value: jbuf
6581 // ldr.n r1, LCPI1_4
6585 // add r2, $jbuf, #+4 ; &jbuf[1]
6587 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6588 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6589 .addConstantPoolIndex(CPI)
6590 .addMemOperand(CPMMO));
6591 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6592 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6593 .addReg(NewVReg1, RegState::Kill)
6595 // Set the low bit because of thumb mode.
6596 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6597 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6598 .addReg(ARM::CPSR, RegState::Define)
6600 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6601 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6602 .addReg(ARM::CPSR, RegState::Define)
6603 .addReg(NewVReg2, RegState::Kill)
6604 .addReg(NewVReg3, RegState::Kill));
6605 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6606 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6608 .addImm(36); // &jbuf[1] :: pc
6609 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6610 .addReg(NewVReg4, RegState::Kill)
6611 .addReg(NewVReg5, RegState::Kill)
6613 .addMemOperand(FIMMOSt));
6615 // Incoming value: jbuf
6618 // str r1, [$jbuf, #+4] ; &jbuf[1]
6619 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6620 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6621 .addConstantPoolIndex(CPI)
6623 .addMemOperand(CPMMO));
6624 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6625 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6626 .addReg(NewVReg1, RegState::Kill)
6627 .addImm(PCLabelId));
6628 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6629 .addReg(NewVReg2, RegState::Kill)
6631 .addImm(36) // &jbuf[1] :: pc
6632 .addMemOperand(FIMMOSt));
6636 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6637 MachineBasicBlock *MBB) const {
6638 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6639 DebugLoc dl = MI->getDebugLoc();
6640 MachineFunction *MF = MBB->getParent();
6641 MachineRegisterInfo *MRI = &MF->getRegInfo();
6642 MachineFrameInfo *MFI = MF->getFrameInfo();
6643 int FI = MFI->getFunctionContextIndex();
6645 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6646 : &ARM::GPRnopcRegClass;
6648 // Get a mapping of the call site numbers to all of the landing pads they're
6650 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6651 unsigned MaxCSNum = 0;
6652 MachineModuleInfo &MMI = MF->getMMI();
6653 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6655 if (!BB->isLandingPad()) continue;
6657 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6659 for (MachineBasicBlock::iterator
6660 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6661 if (!II->isEHLabel()) continue;
6663 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6664 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6666 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6667 for (SmallVectorImpl<unsigned>::iterator
6668 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6669 CSI != CSE; ++CSI) {
6670 CallSiteNumToLPad[*CSI].push_back(BB);
6671 MaxCSNum = std::max(MaxCSNum, *CSI);
6677 // Get an ordered list of the machine basic blocks for the jump table.
6678 std::vector<MachineBasicBlock*> LPadList;
6679 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6680 LPadList.reserve(CallSiteNumToLPad.size());
6681 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6682 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6683 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6684 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6685 LPadList.push_back(*II);
6686 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6690 assert(!LPadList.empty() &&
6691 "No landing pad destinations for the dispatch jump table!");
6693 // Create the jump table and associated information.
6694 MachineJumpTableInfo *JTI =
6695 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6696 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6697 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6699 // Create the MBBs for the dispatch code.
6701 // Shove the dispatch's address into the return slot in the function context.
6702 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6703 DispatchBB->setIsLandingPad();
6705 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6706 unsigned trap_opcode;
6707 if (Subtarget->isThumb())
6708 trap_opcode = ARM::tTRAP;
6710 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6712 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6713 DispatchBB->addSuccessor(TrapBB);
6715 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6716 DispatchBB->addSuccessor(DispContBB);
6719 MF->insert(MF->end(), DispatchBB);
6720 MF->insert(MF->end(), DispContBB);
6721 MF->insert(MF->end(), TrapBB);
6723 // Insert code into the entry block that creates and registers the function
6725 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6727 MachineMemOperand *FIMMOLd =
6728 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6729 MachineMemOperand::MOLoad |
6730 MachineMemOperand::MOVolatile, 4, 4);
6732 MachineInstrBuilder MIB;
6733 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6735 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6736 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6738 // Add a register mask with no preserved registers. This results in all
6739 // registers being marked as clobbered.
6740 MIB.addRegMask(RI.getNoPreservedMask());
6742 unsigned NumLPads = LPadList.size();
6743 if (Subtarget->isThumb2()) {
6744 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6745 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6748 .addMemOperand(FIMMOLd));
6750 if (NumLPads < 256) {
6751 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6753 .addImm(LPadList.size()));
6755 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6756 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6757 .addImm(NumLPads & 0xFFFF));
6759 unsigned VReg2 = VReg1;
6760 if ((NumLPads & 0xFFFF0000) != 0) {
6761 VReg2 = MRI->createVirtualRegister(TRC);
6762 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6764 .addImm(NumLPads >> 16));
6767 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6772 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6777 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6778 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6779 .addJumpTableIndex(MJTI));
6781 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6784 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6785 .addReg(NewVReg3, RegState::Kill)
6787 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6789 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6790 .addReg(NewVReg4, RegState::Kill)
6792 .addJumpTableIndex(MJTI);
6793 } else if (Subtarget->isThumb()) {
6794 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6795 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6798 .addMemOperand(FIMMOLd));
6800 if (NumLPads < 256) {
6801 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6805 MachineConstantPool *ConstantPool = MF->getConstantPool();
6806 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6807 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6809 // MachineConstantPool wants an explicit alignment.
6810 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6812 Align = getDataLayout()->getTypeAllocSize(C->getType());
6813 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6815 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6816 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6817 .addReg(VReg1, RegState::Define)
6818 .addConstantPoolIndex(Idx));
6819 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6824 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6829 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6830 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6831 .addReg(ARM::CPSR, RegState::Define)
6835 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6836 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6837 .addJumpTableIndex(MJTI));
6839 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6840 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6841 .addReg(ARM::CPSR, RegState::Define)
6842 .addReg(NewVReg2, RegState::Kill)
6845 MachineMemOperand *JTMMOLd =
6846 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6847 MachineMemOperand::MOLoad, 4, 4);
6849 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6850 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6851 .addReg(NewVReg4, RegState::Kill)
6853 .addMemOperand(JTMMOLd));
6855 unsigned NewVReg6 = NewVReg5;
6856 if (RelocM == Reloc::PIC_) {
6857 NewVReg6 = MRI->createVirtualRegister(TRC);
6858 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6859 .addReg(ARM::CPSR, RegState::Define)
6860 .addReg(NewVReg5, RegState::Kill)
6864 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6865 .addReg(NewVReg6, RegState::Kill)
6866 .addJumpTableIndex(MJTI);
6868 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6869 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6872 .addMemOperand(FIMMOLd));
6874 if (NumLPads < 256) {
6875 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6878 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6879 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6880 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6881 .addImm(NumLPads & 0xFFFF));
6883 unsigned VReg2 = VReg1;
6884 if ((NumLPads & 0xFFFF0000) != 0) {
6885 VReg2 = MRI->createVirtualRegister(TRC);
6886 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6888 .addImm(NumLPads >> 16));
6891 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6895 MachineConstantPool *ConstantPool = MF->getConstantPool();
6896 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6897 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6899 // MachineConstantPool wants an explicit alignment.
6900 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6902 Align = getDataLayout()->getTypeAllocSize(C->getType());
6903 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6905 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6906 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6907 .addReg(VReg1, RegState::Define)
6908 .addConstantPoolIndex(Idx)
6910 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6912 .addReg(VReg1, RegState::Kill));
6915 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6920 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6922 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6924 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6925 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6926 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6927 .addJumpTableIndex(MJTI));
6929 MachineMemOperand *JTMMOLd =
6930 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6931 MachineMemOperand::MOLoad, 4, 4);
6932 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6934 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6935 .addReg(NewVReg3, RegState::Kill)
6938 .addMemOperand(JTMMOLd));
6940 if (RelocM == Reloc::PIC_) {
6941 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6942 .addReg(NewVReg5, RegState::Kill)
6944 .addJumpTableIndex(MJTI);
6946 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6947 .addReg(NewVReg5, RegState::Kill)
6948 .addJumpTableIndex(MJTI);
6952 // Add the jump table entries as successors to the MBB.
6953 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6954 for (std::vector<MachineBasicBlock*>::iterator
6955 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6956 MachineBasicBlock *CurMBB = *I;
6957 if (SeenMBBs.insert(CurMBB).second)
6958 DispContBB->addSuccessor(CurMBB);
6961 // N.B. the order the invoke BBs are processed in doesn't matter here.
6962 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6963 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6964 for (MachineBasicBlock *BB : InvokeBBs) {
6966 // Remove the landing pad successor from the invoke block and replace it
6967 // with the new dispatch block.
6968 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6970 while (!Successors.empty()) {
6971 MachineBasicBlock *SMBB = Successors.pop_back_val();
6972 if (SMBB->isLandingPad()) {
6973 BB->removeSuccessor(SMBB);
6974 MBBLPads.push_back(SMBB);
6978 BB->addSuccessor(DispatchBB);
6980 // Find the invoke call and mark all of the callee-saved registers as
6981 // 'implicit defined' so that they're spilled. This prevents code from
6982 // moving instructions to before the EH block, where they will never be
6984 for (MachineBasicBlock::reverse_iterator
6985 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6986 if (!II->isCall()) continue;
6988 DenseMap<unsigned, bool> DefRegs;
6989 for (MachineInstr::mop_iterator
6990 OI = II->operands_begin(), OE = II->operands_end();
6992 if (!OI->isReg()) continue;
6993 DefRegs[OI->getReg()] = true;
6996 MachineInstrBuilder MIB(*MF, &*II);
6998 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6999 unsigned Reg = SavedRegs[i];
7000 if (Subtarget->isThumb2() &&
7001 !ARM::tGPRRegClass.contains(Reg) &&
7002 !ARM::hGPRRegClass.contains(Reg))
7004 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7006 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7009 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7016 // Mark all former landing pads as non-landing pads. The dispatch is the only
7018 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7019 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7020 (*I)->setIsLandingPad(false);
7022 // The instruction is gone now.
7023 MI->eraseFromParent();
7027 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7028 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7029 E = MBB->succ_end(); I != E; ++I)
7032 llvm_unreachable("Expecting a BB with two successors!");
7035 /// Return the load opcode for a given load size. If load size >= 8,
7036 /// neon opcode will be returned.
7037 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7039 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7040 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7042 return LdSize == 4 ? ARM::tLDRi
7043 : LdSize == 2 ? ARM::tLDRHi
7044 : LdSize == 1 ? ARM::tLDRBi : 0;
7046 return LdSize == 4 ? ARM::t2LDR_POST
7047 : LdSize == 2 ? ARM::t2LDRH_POST
7048 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7049 return LdSize == 4 ? ARM::LDR_POST_IMM
7050 : LdSize == 2 ? ARM::LDRH_POST
7051 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7054 /// Return the store opcode for a given store size. If store size >= 8,
7055 /// neon opcode will be returned.
7056 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7058 return StSize == 16 ? ARM::VST1q32wb_fixed
7059 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7061 return StSize == 4 ? ARM::tSTRi
7062 : StSize == 2 ? ARM::tSTRHi
7063 : StSize == 1 ? ARM::tSTRBi : 0;
7065 return StSize == 4 ? ARM::t2STR_POST
7066 : StSize == 2 ? ARM::t2STRH_POST
7067 : StSize == 1 ? ARM::t2STRB_POST : 0;
7068 return StSize == 4 ? ARM::STR_POST_IMM
7069 : StSize == 2 ? ARM::STRH_POST
7070 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7073 /// Emit a post-increment load operation with given size. The instructions
7074 /// will be added to BB at Pos.
7075 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7076 const TargetInstrInfo *TII, DebugLoc dl,
7077 unsigned LdSize, unsigned Data, unsigned AddrIn,
7078 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7079 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7080 assert(LdOpc != 0 && "Should have a load opcode");
7082 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7083 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7085 } else if (IsThumb1) {
7086 // load + update AddrIn
7087 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7088 .addReg(AddrIn).addImm(0));
7089 MachineInstrBuilder MIB =
7090 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7091 MIB = AddDefaultT1CC(MIB);
7092 MIB.addReg(AddrIn).addImm(LdSize);
7093 AddDefaultPred(MIB);
7094 } else if (IsThumb2) {
7095 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7096 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7099 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7100 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7101 .addReg(0).addImm(LdSize));
7105 /// Emit a post-increment store operation with given size. The instructions
7106 /// will be added to BB at Pos.
7107 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7108 const TargetInstrInfo *TII, DebugLoc dl,
7109 unsigned StSize, unsigned Data, unsigned AddrIn,
7110 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7111 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7112 assert(StOpc != 0 && "Should have a store opcode");
7114 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7115 .addReg(AddrIn).addImm(0).addReg(Data));
7116 } else if (IsThumb1) {
7117 // store + update AddrIn
7118 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7119 .addReg(AddrIn).addImm(0));
7120 MachineInstrBuilder MIB =
7121 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7122 MIB = AddDefaultT1CC(MIB);
7123 MIB.addReg(AddrIn).addImm(StSize);
7124 AddDefaultPred(MIB);
7125 } else if (IsThumb2) {
7126 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7127 .addReg(Data).addReg(AddrIn).addImm(StSize));
7129 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7130 .addReg(Data).addReg(AddrIn).addReg(0)
7136 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7137 MachineBasicBlock *BB) const {
7138 // This pseudo instruction has 3 operands: dst, src, size
7139 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7140 // Otherwise, we will generate unrolled scalar copies.
7141 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7142 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7143 MachineFunction::iterator It = BB;
7146 unsigned dest = MI->getOperand(0).getReg();
7147 unsigned src = MI->getOperand(1).getReg();
7148 unsigned SizeVal = MI->getOperand(2).getImm();
7149 unsigned Align = MI->getOperand(3).getImm();
7150 DebugLoc dl = MI->getDebugLoc();
7152 MachineFunction *MF = BB->getParent();
7153 MachineRegisterInfo &MRI = MF->getRegInfo();
7154 unsigned UnitSize = 0;
7155 const TargetRegisterClass *TRC = nullptr;
7156 const TargetRegisterClass *VecTRC = nullptr;
7158 bool IsThumb1 = Subtarget->isThumb1Only();
7159 bool IsThumb2 = Subtarget->isThumb2();
7163 } else if (Align & 2) {
7166 // Check whether we can use NEON instructions.
7167 if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7168 Subtarget->hasNEON()) {
7169 if ((Align % 16 == 0) && SizeVal >= 16)
7171 else if ((Align % 8 == 0) && SizeVal >= 8)
7174 // Can't use NEON instructions.
7179 // Select the correct opcode and register class for unit size load/store
7180 bool IsNeon = UnitSize >= 8;
7181 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7183 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7184 : UnitSize == 8 ? &ARM::DPRRegClass
7187 unsigned BytesLeft = SizeVal % UnitSize;
7188 unsigned LoopSize = SizeVal - BytesLeft;
7190 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7191 // Use LDR and STR to copy.
7192 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7193 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7194 unsigned srcIn = src;
7195 unsigned destIn = dest;
7196 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7197 unsigned srcOut = MRI.createVirtualRegister(TRC);
7198 unsigned destOut = MRI.createVirtualRegister(TRC);
7199 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7200 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7201 IsThumb1, IsThumb2);
7202 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7203 IsThumb1, IsThumb2);
7208 // Handle the leftover bytes with LDRB and STRB.
7209 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7210 // [destOut] = STRB_POST(scratch, destIn, 1)
7211 for (unsigned i = 0; i < BytesLeft; i++) {
7212 unsigned srcOut = MRI.createVirtualRegister(TRC);
7213 unsigned destOut = MRI.createVirtualRegister(TRC);
7214 unsigned scratch = MRI.createVirtualRegister(TRC);
7215 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7216 IsThumb1, IsThumb2);
7217 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7218 IsThumb1, IsThumb2);
7222 MI->eraseFromParent(); // The instruction is gone now.
7226 // Expand the pseudo op to a loop.
7229 // movw varEnd, # --> with thumb2
7231 // ldrcp varEnd, idx --> without thumb2
7232 // fallthrough --> loopMBB
7234 // PHI varPhi, varEnd, varLoop
7235 // PHI srcPhi, src, srcLoop
7236 // PHI destPhi, dst, destLoop
7237 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7238 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7239 // subs varLoop, varPhi, #UnitSize
7241 // fallthrough --> exitMBB
7243 // epilogue to handle left-over bytes
7244 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7245 // [destOut] = STRB_POST(scratch, destLoop, 1)
7246 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7247 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7248 MF->insert(It, loopMBB);
7249 MF->insert(It, exitMBB);
7251 // Transfer the remainder of BB and its successor edges to exitMBB.
7252 exitMBB->splice(exitMBB->begin(), BB,
7253 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7254 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7256 // Load an immediate to varEnd.
7257 unsigned varEnd = MRI.createVirtualRegister(TRC);
7258 if (Subtarget->useMovt(*MF)) {
7259 unsigned Vtmp = varEnd;
7260 if ((LoopSize & 0xFFFF0000) != 0)
7261 Vtmp = MRI.createVirtualRegister(TRC);
7262 AddDefaultPred(BuildMI(BB, dl,
7263 TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7264 Vtmp).addImm(LoopSize & 0xFFFF));
7266 if ((LoopSize & 0xFFFF0000) != 0)
7267 AddDefaultPred(BuildMI(BB, dl,
7268 TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7271 .addImm(LoopSize >> 16));
7273 MachineConstantPool *ConstantPool = MF->getConstantPool();
7274 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7275 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7277 // MachineConstantPool wants an explicit alignment.
7278 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7280 Align = getDataLayout()->getTypeAllocSize(C->getType());
7281 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7284 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7285 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7287 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7288 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7290 BB->addSuccessor(loopMBB);
7292 // Generate the loop body:
7293 // varPhi = PHI(varLoop, varEnd)
7294 // srcPhi = PHI(srcLoop, src)
7295 // destPhi = PHI(destLoop, dst)
7296 MachineBasicBlock *entryBB = BB;
7298 unsigned varLoop = MRI.createVirtualRegister(TRC);
7299 unsigned varPhi = MRI.createVirtualRegister(TRC);
7300 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7301 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7302 unsigned destLoop = MRI.createVirtualRegister(TRC);
7303 unsigned destPhi = MRI.createVirtualRegister(TRC);
7305 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7306 .addReg(varLoop).addMBB(loopMBB)
7307 .addReg(varEnd).addMBB(entryBB);
7308 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7309 .addReg(srcLoop).addMBB(loopMBB)
7310 .addReg(src).addMBB(entryBB);
7311 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7312 .addReg(destLoop).addMBB(loopMBB)
7313 .addReg(dest).addMBB(entryBB);
7315 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7316 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7317 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7318 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7319 IsThumb1, IsThumb2);
7320 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7321 IsThumb1, IsThumb2);
7323 // Decrement loop variable by UnitSize.
7325 MachineInstrBuilder MIB =
7326 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7327 MIB = AddDefaultT1CC(MIB);
7328 MIB.addReg(varPhi).addImm(UnitSize);
7329 AddDefaultPred(MIB);
7331 MachineInstrBuilder MIB =
7332 BuildMI(*BB, BB->end(), dl,
7333 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7334 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7335 MIB->getOperand(5).setReg(ARM::CPSR);
7336 MIB->getOperand(5).setIsDef(true);
7338 BuildMI(*BB, BB->end(), dl,
7339 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7340 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7342 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7343 BB->addSuccessor(loopMBB);
7344 BB->addSuccessor(exitMBB);
7346 // Add epilogue to handle BytesLeft.
7348 MachineInstr *StartOfExit = exitMBB->begin();
7350 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7351 // [destOut] = STRB_POST(scratch, destLoop, 1)
7352 unsigned srcIn = srcLoop;
7353 unsigned destIn = destLoop;
7354 for (unsigned i = 0; i < BytesLeft; i++) {
7355 unsigned srcOut = MRI.createVirtualRegister(TRC);
7356 unsigned destOut = MRI.createVirtualRegister(TRC);
7357 unsigned scratch = MRI.createVirtualRegister(TRC);
7358 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7359 IsThumb1, IsThumb2);
7360 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7361 IsThumb1, IsThumb2);
7366 MI->eraseFromParent(); // The instruction is gone now.
7371 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7372 MachineBasicBlock *MBB) const {
7373 const TargetMachine &TM = getTargetMachine();
7374 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7375 DebugLoc DL = MI->getDebugLoc();
7377 assert(Subtarget->isTargetWindows() &&
7378 "__chkstk is only supported on Windows");
7379 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7381 // __chkstk takes the number of words to allocate on the stack in R4, and
7382 // returns the stack adjustment in number of bytes in R4. This will not
7383 // clober any other registers (other than the obvious lr).
7385 // Although, technically, IP should be considered a register which may be
7386 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7387 // thumb-2 environment, so there is no interworking required. As a result, we
7388 // do not expect a veneer to be emitted by the linker, clobbering IP.
7390 // Each module receives its own copy of __chkstk, so no import thunk is
7391 // required, again, ensuring that IP is not clobbered.
7393 // Finally, although some linkers may theoretically provide a trampoline for
7394 // out of range calls (which is quite common due to a 32M range limitation of
7395 // branches for Thumb), we can generate the long-call version via
7396 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7399 switch (TM.getCodeModel()) {
7400 case CodeModel::Small:
7401 case CodeModel::Medium:
7402 case CodeModel::Default:
7403 case CodeModel::Kernel:
7404 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7405 .addImm((unsigned)ARMCC::AL).addReg(0)
7406 .addExternalSymbol("__chkstk")
7407 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7408 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7409 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7411 case CodeModel::Large:
7412 case CodeModel::JITDefault: {
7413 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7414 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7416 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7417 .addExternalSymbol("__chkstk");
7418 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7419 .addImm((unsigned)ARMCC::AL).addReg(0)
7420 .addReg(Reg, RegState::Kill)
7421 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7422 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7423 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7428 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7430 .addReg(ARM::SP).addReg(ARM::R4)));
7432 MI->eraseFromParent();
7437 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7438 MachineBasicBlock *BB) const {
7439 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7440 DebugLoc dl = MI->getDebugLoc();
7441 bool isThumb2 = Subtarget->isThumb2();
7442 switch (MI->getOpcode()) {
7445 llvm_unreachable("Unexpected instr type to insert");
7447 // The Thumb2 pre-indexed stores have the same MI operands, they just
7448 // define them differently in the .td files from the isel patterns, so
7449 // they need pseudos.
7450 case ARM::t2STR_preidx:
7451 MI->setDesc(TII->get(ARM::t2STR_PRE));
7453 case ARM::t2STRB_preidx:
7454 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7456 case ARM::t2STRH_preidx:
7457 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7460 case ARM::STRi_preidx:
7461 case ARM::STRBi_preidx: {
7462 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7463 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7464 // Decode the offset.
7465 unsigned Offset = MI->getOperand(4).getImm();
7466 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7467 Offset = ARM_AM::getAM2Offset(Offset);
7471 MachineMemOperand *MMO = *MI->memoperands_begin();
7472 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7473 .addOperand(MI->getOperand(0)) // Rn_wb
7474 .addOperand(MI->getOperand(1)) // Rt
7475 .addOperand(MI->getOperand(2)) // Rn
7476 .addImm(Offset) // offset (skip GPR==zero_reg)
7477 .addOperand(MI->getOperand(5)) // pred
7478 .addOperand(MI->getOperand(6))
7479 .addMemOperand(MMO);
7480 MI->eraseFromParent();
7483 case ARM::STRr_preidx:
7484 case ARM::STRBr_preidx:
7485 case ARM::STRH_preidx: {
7487 switch (MI->getOpcode()) {
7488 default: llvm_unreachable("unexpected opcode!");
7489 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7490 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7491 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7493 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7494 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7495 MIB.addOperand(MI->getOperand(i));
7496 MI->eraseFromParent();
7500 case ARM::tMOVCCr_pseudo: {
7501 // To "insert" a SELECT_CC instruction, we actually have to insert the
7502 // diamond control-flow pattern. The incoming instruction knows the
7503 // destination vreg to set, the condition code register to branch on, the
7504 // true/false values to select between, and a branch opcode to use.
7505 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7506 MachineFunction::iterator It = BB;
7512 // cmpTY ccX, r1, r2
7514 // fallthrough --> copy0MBB
7515 MachineBasicBlock *thisMBB = BB;
7516 MachineFunction *F = BB->getParent();
7517 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7518 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7519 F->insert(It, copy0MBB);
7520 F->insert(It, sinkMBB);
7522 // Transfer the remainder of BB and its successor edges to sinkMBB.
7523 sinkMBB->splice(sinkMBB->begin(), BB,
7524 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7525 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7527 BB->addSuccessor(copy0MBB);
7528 BB->addSuccessor(sinkMBB);
7530 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7531 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7534 // %FalseValue = ...
7535 // # fallthrough to sinkMBB
7538 // Update machine-CFG edges
7539 BB->addSuccessor(sinkMBB);
7542 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7545 BuildMI(*BB, BB->begin(), dl,
7546 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7547 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7548 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7550 MI->eraseFromParent(); // The pseudo instruction is gone now.
7555 case ARM::BCCZi64: {
7556 // If there is an unconditional branch to the other successor, remove it.
7557 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7559 // Compare both parts that make up the double comparison separately for
7561 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7563 unsigned LHS1 = MI->getOperand(1).getReg();
7564 unsigned LHS2 = MI->getOperand(2).getReg();
7566 AddDefaultPred(BuildMI(BB, dl,
7567 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7568 .addReg(LHS1).addImm(0));
7569 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7570 .addReg(LHS2).addImm(0)
7571 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7573 unsigned RHS1 = MI->getOperand(3).getReg();
7574 unsigned RHS2 = MI->getOperand(4).getReg();
7575 AddDefaultPred(BuildMI(BB, dl,
7576 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7577 .addReg(LHS1).addReg(RHS1));
7578 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7579 .addReg(LHS2).addReg(RHS2)
7580 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7583 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7584 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7585 if (MI->getOperand(0).getImm() == ARMCC::NE)
7586 std::swap(destMBB, exitMBB);
7588 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7589 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7591 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7593 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7595 MI->eraseFromParent(); // The pseudo instruction is gone now.
7599 case ARM::Int_eh_sjlj_setjmp:
7600 case ARM::Int_eh_sjlj_setjmp_nofp:
7601 case ARM::tInt_eh_sjlj_setjmp:
7602 case ARM::t2Int_eh_sjlj_setjmp:
7603 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7604 EmitSjLjDispatchBlock(MI, BB);
7609 // To insert an ABS instruction, we have to insert the
7610 // diamond control-flow pattern. The incoming instruction knows the
7611 // source vreg to test against 0, the destination vreg to set,
7612 // the condition code register to branch on, the
7613 // true/false values to select between, and a branch opcode to use.
7618 // BCC (branch to SinkBB if V0 >= 0)
7619 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7620 // SinkBB: V1 = PHI(V2, V3)
7621 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7622 MachineFunction::iterator BBI = BB;
7624 MachineFunction *Fn = BB->getParent();
7625 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7626 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7627 Fn->insert(BBI, RSBBB);
7628 Fn->insert(BBI, SinkBB);
7630 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7631 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7632 bool ABSSrcKIll = MI->getOperand(1).isKill();
7633 bool isThumb2 = Subtarget->isThumb2();
7634 MachineRegisterInfo &MRI = Fn->getRegInfo();
7635 // In Thumb mode S must not be specified if source register is the SP or
7636 // PC and if destination register is the SP, so restrict register class
7637 unsigned NewRsbDstReg =
7638 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7640 // Transfer the remainder of BB and its successor edges to sinkMBB.
7641 SinkBB->splice(SinkBB->begin(), BB,
7642 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7643 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7645 BB->addSuccessor(RSBBB);
7646 BB->addSuccessor(SinkBB);
7648 // fall through to SinkMBB
7649 RSBBB->addSuccessor(SinkBB);
7651 // insert a cmp at the end of BB
7652 AddDefaultPred(BuildMI(BB, dl,
7653 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7654 .addReg(ABSSrcReg).addImm(0));
7656 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7658 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7659 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7661 // insert rsbri in RSBBB
7662 // Note: BCC and rsbri will be converted into predicated rsbmi
7663 // by if-conversion pass
7664 BuildMI(*RSBBB, RSBBB->begin(), dl,
7665 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7666 .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7667 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7669 // insert PHI in SinkBB,
7670 // reuse ABSDstReg to not change uses of ABS instruction
7671 BuildMI(*SinkBB, SinkBB->begin(), dl,
7672 TII->get(ARM::PHI), ABSDstReg)
7673 .addReg(NewRsbDstReg).addMBB(RSBBB)
7674 .addReg(ABSSrcReg).addMBB(BB);
7676 // remove ABS instruction
7677 MI->eraseFromParent();
7679 // return last added BB
7682 case ARM::COPY_STRUCT_BYVAL_I32:
7684 return EmitStructByval(MI, BB);
7685 case ARM::WIN__CHKSTK:
7686 return EmitLowered__chkstk(MI, BB);
7690 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7691 SDNode *Node) const {
7692 const MCInstrDesc *MCID = &MI->getDesc();
7693 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7694 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7695 // operand is still set to noreg. If needed, set the optional operand's
7696 // register to CPSR, and remove the redundant implicit def.
7698 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7700 // Rename pseudo opcodes.
7701 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7703 const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
7704 MCID = &TII->get(NewOpc);
7706 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7707 "converted opcode should be the same except for cc_out");
7711 // Add the optional cc_out operand
7712 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7714 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7716 // Any ARM instruction that sets the 's' bit should specify an optional
7717 // "cc_out" operand in the last operand position.
7718 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7719 assert(!NewOpc && "Optional cc_out operand required");
7722 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7723 // since we already have an optional CPSR def.
7724 bool definesCPSR = false;
7725 bool deadCPSR = false;
7726 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7728 const MachineOperand &MO = MI->getOperand(i);
7729 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7733 MI->RemoveOperand(i);
7738 assert(!NewOpc && "Optional cc_out operand required");
7741 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7743 assert(!MI->getOperand(ccOutIdx).getReg() &&
7744 "expect uninitialized optional cc_out operand");
7748 // If this instruction was defined with an optional CPSR def and its dag node
7749 // had a live implicit CPSR def, then activate the optional CPSR def.
7750 MachineOperand &MO = MI->getOperand(ccOutIdx);
7751 MO.setReg(ARM::CPSR);
7755 //===----------------------------------------------------------------------===//
7756 // ARM Optimization Hooks
7757 //===----------------------------------------------------------------------===//
7759 // Helper function that checks if N is a null or all ones constant.
7760 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7761 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7764 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7767 // Return true if N is conditionally 0 or all ones.
7768 // Detects these expressions where cc is an i1 value:
7770 // (select cc 0, y) [AllOnes=0]
7771 // (select cc y, 0) [AllOnes=0]
7772 // (zext cc) [AllOnes=0]
7773 // (sext cc) [AllOnes=0/1]
7774 // (select cc -1, y) [AllOnes=1]
7775 // (select cc y, -1) [AllOnes=1]
7777 // Invert is set when N is the null/all ones constant when CC is false.
7778 // OtherOp is set to the alternative value of N.
7779 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7780 SDValue &CC, bool &Invert,
7782 SelectionDAG &DAG) {
7783 switch (N->getOpcode()) {
7784 default: return false;
7786 CC = N->getOperand(0);
7787 SDValue N1 = N->getOperand(1);
7788 SDValue N2 = N->getOperand(2);
7789 if (isZeroOrAllOnes(N1, AllOnes)) {
7794 if (isZeroOrAllOnes(N2, AllOnes)) {
7801 case ISD::ZERO_EXTEND:
7802 // (zext cc) can never be the all ones value.
7806 case ISD::SIGN_EXTEND: {
7808 EVT VT = N->getValueType(0);
7809 CC = N->getOperand(0);
7810 if (CC.getValueType() != MVT::i1)
7814 // When looking for an AllOnes constant, N is an sext, and the 'other'
7816 OtherOp = DAG.getConstant(0, dl, VT);
7817 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7818 // When looking for a 0 constant, N can be zext or sext.
7819 OtherOp = DAG.getConstant(1, dl, VT);
7821 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
7828 // Combine a constant select operand into its use:
7830 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7831 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7832 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7833 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7834 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7836 // The transform is rejected if the select doesn't have a constant operand that
7837 // is null, or all ones when AllOnes is set.
7839 // Also recognize sext/zext from i1:
7841 // (add (zext cc), x) -> (select cc (add x, 1), x)
7842 // (add (sext cc), x) -> (select cc (add x, -1), x)
7844 // These transformations eventually create predicated instructions.
7846 // @param N The node to transform.
7847 // @param Slct The N operand that is a select.
7848 // @param OtherOp The other N operand (x above).
7849 // @param DCI Context.
7850 // @param AllOnes Require the select constant to be all ones instead of null.
7851 // @returns The new node, or SDValue() on failure.
7853 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7854 TargetLowering::DAGCombinerInfo &DCI,
7855 bool AllOnes = false) {
7856 SelectionDAG &DAG = DCI.DAG;
7857 EVT VT = N->getValueType(0);
7858 SDValue NonConstantVal;
7861 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7862 NonConstantVal, DAG))
7865 // Slct is now know to be the desired identity constant when CC is true.
7866 SDValue TrueVal = OtherOp;
7867 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7868 OtherOp, NonConstantVal);
7869 // Unless SwapSelectOps says CC should be false.
7871 std::swap(TrueVal, FalseVal);
7873 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7874 CCOp, TrueVal, FalseVal);
7877 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7879 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7880 TargetLowering::DAGCombinerInfo &DCI) {
7881 SDValue N0 = N->getOperand(0);
7882 SDValue N1 = N->getOperand(1);
7883 if (N0.getNode()->hasOneUse()) {
7884 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7885 if (Result.getNode())
7888 if (N1.getNode()->hasOneUse()) {
7889 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7890 if (Result.getNode())
7896 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7897 // (only after legalization).
7898 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7899 TargetLowering::DAGCombinerInfo &DCI,
7900 const ARMSubtarget *Subtarget) {
7902 // Only perform optimization if after legalize, and if NEON is available. We
7903 // also expected both operands to be BUILD_VECTORs.
7904 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7905 || N0.getOpcode() != ISD::BUILD_VECTOR
7906 || N1.getOpcode() != ISD::BUILD_VECTOR)
7909 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7910 EVT VT = N->getValueType(0);
7911 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7914 // Check that the vector operands are of the right form.
7915 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7916 // operands, where N is the size of the formed vector.
7917 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7918 // index such that we have a pair wise add pattern.
7920 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7921 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7923 SDValue Vec = N0->getOperand(0)->getOperand(0);
7924 SDNode *V = Vec.getNode();
7925 unsigned nextIndex = 0;
7927 // For each operands to the ADD which are BUILD_VECTORs,
7928 // check to see if each of their operands are an EXTRACT_VECTOR with
7929 // the same vector and appropriate index.
7930 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7931 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7932 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7934 SDValue ExtVec0 = N0->getOperand(i);
7935 SDValue ExtVec1 = N1->getOperand(i);
7937 // First operand is the vector, verify its the same.
7938 if (V != ExtVec0->getOperand(0).getNode() ||
7939 V != ExtVec1->getOperand(0).getNode())
7942 // Second is the constant, verify its correct.
7943 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7944 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7946 // For the constant, we want to see all the even or all the odd.
7947 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7948 || C1->getZExtValue() != nextIndex+1)
7957 // Create VPADDL node.
7958 SelectionDAG &DAG = DCI.DAG;
7959 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7963 // Build operand list.
7964 SmallVector<SDValue, 8> Ops;
7965 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
7966 TLI.getPointerTy()));
7968 // Input is the vector.
7971 // Get widened type and narrowed type.
7973 unsigned numElem = VT.getVectorNumElements();
7975 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7976 switch (inputLaneType.getSimpleVT().SimpleTy) {
7977 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7978 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7979 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7981 llvm_unreachable("Invalid vector element type for padd optimization.");
7984 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
7985 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7986 return DAG.getNode(ExtOp, dl, VT, tmp);
7989 static SDValue findMUL_LOHI(SDValue V) {
7990 if (V->getOpcode() == ISD::UMUL_LOHI ||
7991 V->getOpcode() == ISD::SMUL_LOHI)
7996 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7997 TargetLowering::DAGCombinerInfo &DCI,
7998 const ARMSubtarget *Subtarget) {
8000 if (Subtarget->isThumb1Only()) return SDValue();
8002 // Only perform the checks after legalize when the pattern is available.
8003 if (DCI.isBeforeLegalize()) return SDValue();
8005 // Look for multiply add opportunities.
8006 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8007 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8008 // a glue link from the first add to the second add.
8009 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8010 // a S/UMLAL instruction.
8013 // / \ [no multiline comment]
8019 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8020 SDValue AddcOp0 = AddcNode->getOperand(0);
8021 SDValue AddcOp1 = AddcNode->getOperand(1);
8023 // Check if the two operands are from the same mul_lohi node.
8024 if (AddcOp0.getNode() == AddcOp1.getNode())
8027 assert(AddcNode->getNumValues() == 2 &&
8028 AddcNode->getValueType(0) == MVT::i32 &&
8029 "Expect ADDC with two result values. First: i32");
8031 // Check that we have a glued ADDC node.
8032 if (AddcNode->getValueType(1) != MVT::Glue)
8035 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8036 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8037 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8038 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8039 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8042 // Look for the glued ADDE.
8043 SDNode* AddeNode = AddcNode->getGluedUser();
8047 // Make sure it is really an ADDE.
8048 if (AddeNode->getOpcode() != ISD::ADDE)
8051 assert(AddeNode->getNumOperands() == 3 &&
8052 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8053 "ADDE node has the wrong inputs");
8055 // Check for the triangle shape.
8056 SDValue AddeOp0 = AddeNode->getOperand(0);
8057 SDValue AddeOp1 = AddeNode->getOperand(1);
8059 // Make sure that the ADDE operands are not coming from the same node.
8060 if (AddeOp0.getNode() == AddeOp1.getNode())
8063 // Find the MUL_LOHI node walking up ADDE's operands.
8064 bool IsLeftOperandMUL = false;
8065 SDValue MULOp = findMUL_LOHI(AddeOp0);
8066 if (MULOp == SDValue())
8067 MULOp = findMUL_LOHI(AddeOp1);
8069 IsLeftOperandMUL = true;
8070 if (MULOp == SDValue())
8073 // Figure out the right opcode.
8074 unsigned Opc = MULOp->getOpcode();
8075 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8077 // Figure out the high and low input values to the MLAL node.
8078 SDValue* HiAdd = nullptr;
8079 SDValue* LoMul = nullptr;
8080 SDValue* LowAdd = nullptr;
8082 // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8083 if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8086 if (IsLeftOperandMUL)
8092 // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8093 // whose low result is fed to the ADDC we are checking.
8095 if (AddcOp0 == MULOp.getValue(0)) {
8099 if (AddcOp1 == MULOp.getValue(0)) {
8107 // Create the merged node.
8108 SelectionDAG &DAG = DCI.DAG;
8110 // Build operand list.
8111 SmallVector<SDValue, 8> Ops;
8112 Ops.push_back(LoMul->getOperand(0));
8113 Ops.push_back(LoMul->getOperand(1));
8114 Ops.push_back(*LowAdd);
8115 Ops.push_back(*HiAdd);
8117 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8118 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8120 // Replace the ADDs' nodes uses by the MLA node's values.
8121 SDValue HiMLALResult(MLALNode.getNode(), 1);
8122 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8124 SDValue LoMLALResult(MLALNode.getNode(), 0);
8125 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8127 // Return original node to notify the driver to stop replacing.
8128 SDValue resNode(AddcNode, 0);
8132 /// PerformADDCCombine - Target-specific dag combine transform from
8133 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8134 static SDValue PerformADDCCombine(SDNode *N,
8135 TargetLowering::DAGCombinerInfo &DCI,
8136 const ARMSubtarget *Subtarget) {
8138 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8142 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8143 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8144 /// called with the default operands, and if that fails, with commuted
8146 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8147 TargetLowering::DAGCombinerInfo &DCI,
8148 const ARMSubtarget *Subtarget){
8150 // Attempt to create vpaddl for this add.
8151 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8152 if (Result.getNode())
8155 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8156 if (N0.getNode()->hasOneUse()) {
8157 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8158 if (Result.getNode()) return Result;
8163 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8165 static SDValue PerformADDCombine(SDNode *N,
8166 TargetLowering::DAGCombinerInfo &DCI,
8167 const ARMSubtarget *Subtarget) {
8168 SDValue N0 = N->getOperand(0);
8169 SDValue N1 = N->getOperand(1);
8171 // First try with the default operand order.
8172 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8173 if (Result.getNode())
8176 // If that didn't work, try again with the operands commuted.
8177 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8180 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8182 static SDValue PerformSUBCombine(SDNode *N,
8183 TargetLowering::DAGCombinerInfo &DCI) {
8184 SDValue N0 = N->getOperand(0);
8185 SDValue N1 = N->getOperand(1);
8187 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8188 if (N1.getNode()->hasOneUse()) {
8189 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8190 if (Result.getNode()) return Result;
8196 /// PerformVMULCombine
8197 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8198 /// special multiplier accumulator forwarding.
8204 // However, for (A + B) * (A + B),
8211 static SDValue PerformVMULCombine(SDNode *N,
8212 TargetLowering::DAGCombinerInfo &DCI,
8213 const ARMSubtarget *Subtarget) {
8214 if (!Subtarget->hasVMLxForwarding())
8217 SelectionDAG &DAG = DCI.DAG;
8218 SDValue N0 = N->getOperand(0);
8219 SDValue N1 = N->getOperand(1);
8220 unsigned Opcode = N0.getOpcode();
8221 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8222 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8223 Opcode = N1.getOpcode();
8224 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8225 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8233 EVT VT = N->getValueType(0);
8235 SDValue N00 = N0->getOperand(0);
8236 SDValue N01 = N0->getOperand(1);
8237 return DAG.getNode(Opcode, DL, VT,
8238 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8239 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8242 static SDValue PerformMULCombine(SDNode *N,
8243 TargetLowering::DAGCombinerInfo &DCI,
8244 const ARMSubtarget *Subtarget) {
8245 SelectionDAG &DAG = DCI.DAG;
8247 if (Subtarget->isThumb1Only())
8250 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8253 EVT VT = N->getValueType(0);
8254 if (VT.is64BitVector() || VT.is128BitVector())
8255 return PerformVMULCombine(N, DCI, Subtarget);
8259 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8263 int64_t MulAmt = C->getSExtValue();
8264 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8266 ShiftAmt = ShiftAmt & (32 - 1);
8267 SDValue V = N->getOperand(0);
8271 MulAmt >>= ShiftAmt;
8274 if (isPowerOf2_32(MulAmt - 1)) {
8275 // (mul x, 2^N + 1) => (add (shl x, N), x)
8276 Res = DAG.getNode(ISD::ADD, DL, VT,
8278 DAG.getNode(ISD::SHL, DL, VT,
8280 DAG.getConstant(Log2_32(MulAmt - 1), DL,
8282 } else if (isPowerOf2_32(MulAmt + 1)) {
8283 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8284 Res = DAG.getNode(ISD::SUB, DL, VT,
8285 DAG.getNode(ISD::SHL, DL, VT,
8287 DAG.getConstant(Log2_32(MulAmt + 1), DL,
8293 uint64_t MulAmtAbs = -MulAmt;
8294 if (isPowerOf2_32(MulAmtAbs + 1)) {
8295 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8296 Res = DAG.getNode(ISD::SUB, DL, VT,
8298 DAG.getNode(ISD::SHL, DL, VT,
8300 DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8302 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8303 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8304 Res = DAG.getNode(ISD::ADD, DL, VT,
8306 DAG.getNode(ISD::SHL, DL, VT,
8308 DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8310 Res = DAG.getNode(ISD::SUB, DL, VT,
8311 DAG.getConstant(0, DL, MVT::i32), Res);
8318 Res = DAG.getNode(ISD::SHL, DL, VT,
8319 Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8321 // Do not add new nodes to DAG combiner worklist.
8322 DCI.CombineTo(N, Res, false);
8326 static SDValue PerformANDCombine(SDNode *N,
8327 TargetLowering::DAGCombinerInfo &DCI,
8328 const ARMSubtarget *Subtarget) {
8330 // Attempt to use immediate-form VBIC
8331 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8333 EVT VT = N->getValueType(0);
8334 SelectionDAG &DAG = DCI.DAG;
8336 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8339 APInt SplatBits, SplatUndef;
8340 unsigned SplatBitSize;
8343 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8344 if (SplatBitSize <= 64) {
8346 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8347 SplatUndef.getZExtValue(), SplatBitSize,
8348 DAG, dl, VbicVT, VT.is128BitVector(),
8350 if (Val.getNode()) {
8352 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8353 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8354 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8359 if (!Subtarget->isThumb1Only()) {
8360 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8361 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8362 if (Result.getNode())
8369 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8370 static SDValue PerformORCombine(SDNode *N,
8371 TargetLowering::DAGCombinerInfo &DCI,
8372 const ARMSubtarget *Subtarget) {
8373 // Attempt to use immediate-form VORR
8374 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8376 EVT VT = N->getValueType(0);
8377 SelectionDAG &DAG = DCI.DAG;
8379 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8382 APInt SplatBits, SplatUndef;
8383 unsigned SplatBitSize;
8385 if (BVN && Subtarget->hasNEON() &&
8386 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8387 if (SplatBitSize <= 64) {
8389 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8390 SplatUndef.getZExtValue(), SplatBitSize,
8391 DAG, dl, VorrVT, VT.is128BitVector(),
8393 if (Val.getNode()) {
8395 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8396 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8397 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8402 if (!Subtarget->isThumb1Only()) {
8403 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8404 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8405 if (Result.getNode())
8409 // The code below optimizes (or (and X, Y), Z).
8410 // The AND operand needs to have a single user to make these optimizations
8412 SDValue N0 = N->getOperand(0);
8413 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8415 SDValue N1 = N->getOperand(1);
8417 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8418 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8419 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8421 unsigned SplatBitSize;
8424 APInt SplatBits0, SplatBits1;
8425 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8426 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8427 // Ensure that the second operand of both ands are constants
8428 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8429 HasAnyUndefs) && !HasAnyUndefs) {
8430 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8431 HasAnyUndefs) && !HasAnyUndefs) {
8432 // Ensure that the bit width of the constants are the same and that
8433 // the splat arguments are logical inverses as per the pattern we
8434 // are trying to simplify.
8435 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8436 SplatBits0 == ~SplatBits1) {
8437 // Canonicalize the vector type to make instruction selection
8439 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8440 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8444 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8450 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8453 // BFI is only available on V6T2+
8454 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8458 // 1) or (and A, mask), val => ARMbfi A, val, mask
8459 // iff (val & mask) == val
8461 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8462 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8463 // && mask == ~mask2
8464 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8465 // && ~mask == mask2
8466 // (i.e., copy a bitfield value into another bitfield of the same width)
8471 SDValue N00 = N0.getOperand(0);
8473 // The value and the mask need to be constants so we can verify this is
8474 // actually a bitfield set. If the mask is 0xffff, we can do better
8475 // via a movt instruction, so don't use BFI in that case.
8476 SDValue MaskOp = N0.getOperand(1);
8477 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8480 unsigned Mask = MaskC->getZExtValue();
8484 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8487 unsigned Val = N1C->getZExtValue();
8488 if ((Val & ~Mask) != Val)
8491 if (ARM::isBitFieldInvertedMask(Mask)) {
8492 Val >>= countTrailingZeros(~Mask);
8494 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8495 DAG.getConstant(Val, DL, MVT::i32),
8496 DAG.getConstant(Mask, DL, MVT::i32));
8498 // Do not add new nodes to DAG combiner worklist.
8499 DCI.CombineTo(N, Res, false);
8502 } else if (N1.getOpcode() == ISD::AND) {
8503 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8504 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8507 unsigned Mask2 = N11C->getZExtValue();
8509 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8511 if (ARM::isBitFieldInvertedMask(Mask) &&
8513 // The pack halfword instruction works better for masks that fit it,
8514 // so use that when it's available.
8515 if (Subtarget->hasT2ExtractPack() &&
8516 (Mask == 0xffff || Mask == 0xffff0000))
8519 unsigned amt = countTrailingZeros(Mask2);
8520 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8521 DAG.getConstant(amt, DL, MVT::i32));
8522 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8523 DAG.getConstant(Mask, DL, MVT::i32));
8524 // Do not add new nodes to DAG combiner worklist.
8525 DCI.CombineTo(N, Res, false);
8527 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8529 // The pack halfword instruction works better for masks that fit it,
8530 // so use that when it's available.
8531 if (Subtarget->hasT2ExtractPack() &&
8532 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8535 unsigned lsb = countTrailingZeros(Mask);
8536 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8537 DAG.getConstant(lsb, DL, MVT::i32));
8538 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8539 DAG.getConstant(Mask2, DL, MVT::i32));
8540 // Do not add new nodes to DAG combiner worklist.
8541 DCI.CombineTo(N, Res, false);
8546 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8547 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8548 ARM::isBitFieldInvertedMask(~Mask)) {
8549 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8550 // where lsb(mask) == #shamt and masked bits of B are known zero.
8551 SDValue ShAmt = N00.getOperand(1);
8552 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8553 unsigned LSB = countTrailingZeros(Mask);
8557 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8558 DAG.getConstant(~Mask, DL, MVT::i32));
8560 // Do not add new nodes to DAG combiner worklist.
8561 DCI.CombineTo(N, Res, false);
8567 static SDValue PerformXORCombine(SDNode *N,
8568 TargetLowering::DAGCombinerInfo &DCI,
8569 const ARMSubtarget *Subtarget) {
8570 EVT VT = N->getValueType(0);
8571 SelectionDAG &DAG = DCI.DAG;
8573 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8576 if (!Subtarget->isThumb1Only()) {
8577 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8578 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8579 if (Result.getNode())
8586 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8587 /// the bits being cleared by the AND are not demanded by the BFI.
8588 static SDValue PerformBFICombine(SDNode *N,
8589 TargetLowering::DAGCombinerInfo &DCI) {
8590 SDValue N1 = N->getOperand(1);
8591 if (N1.getOpcode() == ISD::AND) {
8592 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8595 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8596 unsigned LSB = countTrailingZeros(~InvMask);
8597 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8599 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8600 "undefined behavior");
8601 unsigned Mask = (1u << Width) - 1;
8602 unsigned Mask2 = N11C->getZExtValue();
8603 if ((Mask & (~Mask2)) == 0)
8604 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8605 N->getOperand(0), N1.getOperand(0),
8611 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8612 /// ARMISD::VMOVRRD.
8613 static SDValue PerformVMOVRRDCombine(SDNode *N,
8614 TargetLowering::DAGCombinerInfo &DCI,
8615 const ARMSubtarget *Subtarget) {
8616 // vmovrrd(vmovdrr x, y) -> x,y
8617 SDValue InDouble = N->getOperand(0);
8618 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8619 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8621 // vmovrrd(load f64) -> (load i32), (load i32)
8622 SDNode *InNode = InDouble.getNode();
8623 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8624 InNode->getValueType(0) == MVT::f64 &&
8625 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8626 !cast<LoadSDNode>(InNode)->isVolatile()) {
8627 // TODO: Should this be done for non-FrameIndex operands?
8628 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8630 SelectionDAG &DAG = DCI.DAG;
8632 SDValue BasePtr = LD->getBasePtr();
8633 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8634 LD->getPointerInfo(), LD->isVolatile(),
8635 LD->isNonTemporal(), LD->isInvariant(),
8636 LD->getAlignment());
8638 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8639 DAG.getConstant(4, DL, MVT::i32));
8640 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8641 LD->getPointerInfo(), LD->isVolatile(),
8642 LD->isNonTemporal(), LD->isInvariant(),
8643 std::min(4U, LD->getAlignment() / 2));
8645 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8646 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8647 std::swap (NewLD1, NewLD2);
8648 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8655 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8656 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8657 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8658 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8659 SDValue Op0 = N->getOperand(0);
8660 SDValue Op1 = N->getOperand(1);
8661 if (Op0.getOpcode() == ISD::BITCAST)
8662 Op0 = Op0.getOperand(0);
8663 if (Op1.getOpcode() == ISD::BITCAST)
8664 Op1 = Op1.getOperand(0);
8665 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8666 Op0.getNode() == Op1.getNode() &&
8667 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8668 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8669 N->getValueType(0), Op0.getOperand(0));
8673 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8674 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8675 /// i64 vector to have f64 elements, since the value can then be loaded
8676 /// directly into a VFP register.
8677 static bool hasNormalLoadOperand(SDNode *N) {
8678 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8679 for (unsigned i = 0; i < NumElts; ++i) {
8680 SDNode *Elt = N->getOperand(i).getNode();
8681 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8687 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8688 /// ISD::BUILD_VECTOR.
8689 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8690 TargetLowering::DAGCombinerInfo &DCI,
8691 const ARMSubtarget *Subtarget) {
8692 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8693 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8694 // into a pair of GPRs, which is fine when the value is used as a scalar,
8695 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8696 SelectionDAG &DAG = DCI.DAG;
8697 if (N->getNumOperands() == 2) {
8698 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8703 // Load i64 elements as f64 values so that type legalization does not split
8704 // them up into i32 values.
8705 EVT VT = N->getValueType(0);
8706 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8709 SmallVector<SDValue, 8> Ops;
8710 unsigned NumElts = VT.getVectorNumElements();
8711 for (unsigned i = 0; i < NumElts; ++i) {
8712 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8714 // Make the DAGCombiner fold the bitcast.
8715 DCI.AddToWorklist(V.getNode());
8717 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8718 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8719 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8722 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8724 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8725 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8726 // At that time, we may have inserted bitcasts from integer to float.
8727 // If these bitcasts have survived DAGCombine, change the lowering of this
8728 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8729 // force to use floating point types.
8731 // Make sure we can change the type of the vector.
8732 // This is possible iff:
8733 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8734 // 1.1. Vector is used only once.
8735 // 1.2. Use is a bit convert to an integer type.
8736 // 2. The size of its operands are 32-bits (64-bits are not legal).
8737 EVT VT = N->getValueType(0);
8738 EVT EltVT = VT.getVectorElementType();
8740 // Check 1.1. and 2.
8741 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8744 // By construction, the input type must be float.
8745 assert(EltVT == MVT::f32 && "Unexpected type!");
8748 SDNode *Use = *N->use_begin();
8749 if (Use->getOpcode() != ISD::BITCAST ||
8750 Use->getValueType(0).isFloatingPoint())
8753 // Check profitability.
8754 // Model is, if more than half of the relevant operands are bitcast from
8755 // i32, turn the build_vector into a sequence of insert_vector_elt.
8756 // Relevant operands are everything that is not statically
8757 // (i.e., at compile time) bitcasted.
8758 unsigned NumOfBitCastedElts = 0;
8759 unsigned NumElts = VT.getVectorNumElements();
8760 unsigned NumOfRelevantElts = NumElts;
8761 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8762 SDValue Elt = N->getOperand(Idx);
8763 if (Elt->getOpcode() == ISD::BITCAST) {
8764 // Assume only bit cast to i32 will go away.
8765 if (Elt->getOperand(0).getValueType() == MVT::i32)
8766 ++NumOfBitCastedElts;
8767 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8768 // Constants are statically casted, thus do not count them as
8769 // relevant operands.
8770 --NumOfRelevantElts;
8773 // Check if more than half of the elements require a non-free bitcast.
8774 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8777 SelectionDAG &DAG = DCI.DAG;
8778 // Create the new vector type.
8779 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8780 // Check if the type is legal.
8781 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8782 if (!TLI.isTypeLegal(VecVT))
8786 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8787 // => BITCAST INSERT_VECTOR_ELT
8788 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8790 SDValue Vec = DAG.getUNDEF(VecVT);
8792 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8793 SDValue V = N->getOperand(Idx);
8794 if (V.getOpcode() == ISD::UNDEF)
8796 if (V.getOpcode() == ISD::BITCAST &&
8797 V->getOperand(0).getValueType() == MVT::i32)
8798 // Fold obvious case.
8799 V = V.getOperand(0);
8801 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8802 // Make the DAGCombiner fold the bitcasts.
8803 DCI.AddToWorklist(V.getNode());
8805 SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
8806 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8808 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8809 // Make the DAGCombiner fold the bitcasts.
8810 DCI.AddToWorklist(Vec.getNode());
8814 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8815 /// ISD::INSERT_VECTOR_ELT.
8816 static SDValue PerformInsertEltCombine(SDNode *N,
8817 TargetLowering::DAGCombinerInfo &DCI) {
8818 // Bitcast an i64 load inserted into a vector to f64.
8819 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8820 EVT VT = N->getValueType(0);
8821 SDNode *Elt = N->getOperand(1).getNode();
8822 if (VT.getVectorElementType() != MVT::i64 ||
8823 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8826 SelectionDAG &DAG = DCI.DAG;
8828 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8829 VT.getVectorNumElements());
8830 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8831 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8832 // Make the DAGCombiner fold the bitcasts.
8833 DCI.AddToWorklist(Vec.getNode());
8834 DCI.AddToWorklist(V.getNode());
8835 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8836 Vec, V, N->getOperand(2));
8837 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8840 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8841 /// ISD::VECTOR_SHUFFLE.
8842 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8843 // The LLVM shufflevector instruction does not require the shuffle mask
8844 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8845 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8846 // operands do not match the mask length, they are extended by concatenating
8847 // them with undef vectors. That is probably the right thing for other
8848 // targets, but for NEON it is better to concatenate two double-register
8849 // size vector operands into a single quad-register size vector. Do that
8850 // transformation here:
8851 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8852 // shuffle(concat(v1, v2), undef)
8853 SDValue Op0 = N->getOperand(0);
8854 SDValue Op1 = N->getOperand(1);
8855 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8856 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8857 Op0.getNumOperands() != 2 ||
8858 Op1.getNumOperands() != 2)
8860 SDValue Concat0Op1 = Op0.getOperand(1);
8861 SDValue Concat1Op1 = Op1.getOperand(1);
8862 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8863 Concat1Op1.getOpcode() != ISD::UNDEF)
8865 // Skip the transformation if any of the types are illegal.
8866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8867 EVT VT = N->getValueType(0);
8868 if (!TLI.isTypeLegal(VT) ||
8869 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8870 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8873 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8874 Op0.getOperand(0), Op1.getOperand(0));
8875 // Translate the shuffle mask.
8876 SmallVector<int, 16> NewMask;
8877 unsigned NumElts = VT.getVectorNumElements();
8878 unsigned HalfElts = NumElts/2;
8879 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8880 for (unsigned n = 0; n < NumElts; ++n) {
8881 int MaskElt = SVN->getMaskElt(n);
8883 if (MaskElt < (int)HalfElts)
8885 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8886 NewElt = HalfElts + MaskElt - NumElts;
8887 NewMask.push_back(NewElt);
8889 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8890 DAG.getUNDEF(VT), NewMask.data());
8893 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
8894 /// NEON load/store intrinsics, and generic vector load/stores, to merge
8895 /// base address updates.
8896 /// For generic load/stores, the memory type is assumed to be a vector.
8897 /// The caller is assumed to have checked legality.
8898 static SDValue CombineBaseUpdate(SDNode *N,
8899 TargetLowering::DAGCombinerInfo &DCI) {
8900 SelectionDAG &DAG = DCI.DAG;
8901 const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8902 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8903 const bool isStore = N->getOpcode() == ISD::STORE;
8904 const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
8905 SDValue Addr = N->getOperand(AddrOpIdx);
8906 MemSDNode *MemN = cast<MemSDNode>(N);
8909 // Search for a use of the address operand that is an increment.
8910 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8911 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8913 if (User->getOpcode() != ISD::ADD ||
8914 UI.getUse().getResNo() != Addr.getResNo())
8917 // Check that the add is independent of the load/store. Otherwise, folding
8918 // it would create a cycle.
8919 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8922 // Find the new opcode for the updating load/store.
8923 bool isLoadOp = true;
8924 bool isLaneOp = false;
8925 unsigned NewOpc = 0;
8926 unsigned NumVecs = 0;
8928 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8930 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8931 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8933 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8935 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8937 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8939 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8940 NumVecs = 2; isLaneOp = true; break;
8941 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8942 NumVecs = 3; isLaneOp = true; break;
8943 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8944 NumVecs = 4; isLaneOp = true; break;
8945 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8946 NumVecs = 1; isLoadOp = false; break;
8947 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8948 NumVecs = 2; isLoadOp = false; break;
8949 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8950 NumVecs = 3; isLoadOp = false; break;
8951 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8952 NumVecs = 4; isLoadOp = false; break;
8953 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8954 NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
8955 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8956 NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
8957 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8958 NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
8962 switch (N->getOpcode()) {
8963 default: llvm_unreachable("unexpected opcode for Neon base update");
8964 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8965 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8966 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8967 case ISD::LOAD: NewOpc = ARMISD::VLD1_UPD;
8968 NumVecs = 1; isLaneOp = false; break;
8969 case ISD::STORE: NewOpc = ARMISD::VST1_UPD;
8970 NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
8974 // Find the size of memory referenced by the load/store.
8977 VecTy = N->getValueType(0);
8978 } else if (isIntrinsic) {
8979 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8981 assert(isStore && "Node has to be a load, a store, or an intrinsic!");
8982 VecTy = N->getOperand(1).getValueType();
8985 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8987 NumBytes /= VecTy.getVectorNumElements();
8989 // If the increment is a constant, it must match the memory ref size.
8990 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8991 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8992 uint64_t IncVal = CInc->getZExtValue();
8993 if (IncVal != NumBytes)
8995 } else if (NumBytes >= 3 * 16) {
8996 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8997 // separate instructions that make it harder to use a non-constant update.
9001 // OK, we found an ADD we can fold into the base update.
9002 // Now, create a _UPD node, taking care of not breaking alignment.
9004 EVT AlignedVecTy = VecTy;
9005 unsigned Alignment = MemN->getAlignment();
9007 // If this is a less-than-standard-aligned load/store, change the type to
9008 // match the standard alignment.
9009 // The alignment is overlooked when selecting _UPD variants; and it's
9010 // easier to introduce bitcasts here than fix that.
9011 // There are 3 ways to get to this base-update combine:
9012 // - intrinsics: they are assumed to be properly aligned (to the standard
9013 // alignment of the memory type), so we don't need to do anything.
9014 // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9015 // intrinsics, so, likewise, there's nothing to do.
9016 // - generic load/store instructions: the alignment is specified as an
9017 // explicit operand, rather than implicitly as the standard alignment
9018 // of the memory type (like the intrisics). We need to change the
9019 // memory type to match the explicit alignment. That way, we don't
9020 // generate non-standard-aligned ARMISD::VLDx nodes.
9021 if (isa<LSBaseSDNode>(N)) {
9024 if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9025 MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9026 assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9027 assert(!isLaneOp && "Unexpected generic load/store lane.");
9028 unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9029 AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9031 // Don't set an explicit alignment on regular load/stores that we want
9032 // to transform to VLD/VST 1_UPD nodes.
9033 // This matches the behavior of regular load/stores, which only get an
9034 // explicit alignment if the MMO alignment is larger than the standard
9035 // alignment of the memory type.
9036 // Intrinsics, however, always get an explicit alignment, set to the
9037 // alignment of the MMO.
9041 // Create the new updating load/store node.
9042 // First, create an SDVTList for the new updating node's results.
9044 unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9046 for (n = 0; n < NumResultVecs; ++n)
9047 Tys[n] = AlignedVecTy;
9048 Tys[n++] = MVT::i32;
9049 Tys[n] = MVT::Other;
9050 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9052 // Then, gather the new node's operands.
9053 SmallVector<SDValue, 8> Ops;
9054 Ops.push_back(N->getOperand(0)); // incoming chain
9055 Ops.push_back(N->getOperand(AddrOpIdx));
9058 if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9059 // Try to match the intrinsic's signature
9060 Ops.push_back(StN->getValue());
9062 // Loads (and of course intrinsics) match the intrinsics' signature,
9063 // so just add all but the alignment operand.
9064 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9065 Ops.push_back(N->getOperand(i));
9068 // For all node types, the alignment operand is always the last one.
9069 Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9071 // If this is a non-standard-aligned STORE, the penultimate operand is the
9072 // stored value. Bitcast it to the aligned type.
9073 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9074 SDValue &StVal = Ops[Ops.size()-2];
9075 StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9078 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9080 MemN->getMemOperand());
9083 SmallVector<SDValue, 5> NewResults;
9084 for (unsigned i = 0; i < NumResultVecs; ++i)
9085 NewResults.push_back(SDValue(UpdN.getNode(), i));
9087 // If this is an non-standard-aligned LOAD, the first result is the loaded
9088 // value. Bitcast it to the expected result type.
9089 if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9090 SDValue &LdVal = NewResults[0];
9091 LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9094 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9095 DCI.CombineTo(N, NewResults);
9096 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9103 static SDValue PerformVLDCombine(SDNode *N,
9104 TargetLowering::DAGCombinerInfo &DCI) {
9105 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9108 return CombineBaseUpdate(N, DCI);
9111 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9112 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9113 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9115 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9116 SelectionDAG &DAG = DCI.DAG;
9117 EVT VT = N->getValueType(0);
9118 // vldN-dup instructions only support 64-bit vectors for N > 1.
9119 if (!VT.is64BitVector())
9122 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9123 SDNode *VLD = N->getOperand(0).getNode();
9124 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9126 unsigned NumVecs = 0;
9127 unsigned NewOpc = 0;
9128 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9129 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9131 NewOpc = ARMISD::VLD2DUP;
9132 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9134 NewOpc = ARMISD::VLD3DUP;
9135 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9137 NewOpc = ARMISD::VLD4DUP;
9142 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9143 // numbers match the load.
9144 unsigned VLDLaneNo =
9145 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9146 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9148 // Ignore uses of the chain result.
9149 if (UI.getUse().getResNo() == NumVecs)
9152 if (User->getOpcode() != ARMISD::VDUPLANE ||
9153 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9157 // Create the vldN-dup node.
9160 for (n = 0; n < NumVecs; ++n)
9162 Tys[n] = MVT::Other;
9163 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9164 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9165 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9166 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9167 Ops, VLDMemInt->getMemoryVT(),
9168 VLDMemInt->getMemOperand());
9171 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9173 unsigned ResNo = UI.getUse().getResNo();
9174 // Ignore uses of the chain result.
9175 if (ResNo == NumVecs)
9178 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9181 // Now the vldN-lane intrinsic is dead except for its chain result.
9182 // Update uses of the chain.
9183 std::vector<SDValue> VLDDupResults;
9184 for (unsigned n = 0; n < NumVecs; ++n)
9185 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9186 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9187 DCI.CombineTo(VLD, VLDDupResults);
9192 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9193 /// ARMISD::VDUPLANE.
9194 static SDValue PerformVDUPLANECombine(SDNode *N,
9195 TargetLowering::DAGCombinerInfo &DCI) {
9196 SDValue Op = N->getOperand(0);
9198 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9199 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9200 if (CombineVLDDUP(N, DCI))
9201 return SDValue(N, 0);
9203 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9204 // redundant. Ignore bit_converts for now; element sizes are checked below.
9205 while (Op.getOpcode() == ISD::BITCAST)
9206 Op = Op.getOperand(0);
9207 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9210 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9211 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9212 // The canonical VMOV for a zero vector uses a 32-bit element size.
9213 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9215 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9217 EVT VT = N->getValueType(0);
9218 if (EltSize > VT.getVectorElementType().getSizeInBits())
9221 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9224 static SDValue PerformLOADCombine(SDNode *N,
9225 TargetLowering::DAGCombinerInfo &DCI) {
9226 EVT VT = N->getValueType(0);
9228 // If this is a legal vector load, try to combine it into a VLD1_UPD.
9229 if (ISD::isNormalLoad(N) && VT.isVector() &&
9230 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9231 return CombineBaseUpdate(N, DCI);
9236 /// PerformSTORECombine - Target-specific dag combine xforms for
9238 static SDValue PerformSTORECombine(SDNode *N,
9239 TargetLowering::DAGCombinerInfo &DCI) {
9240 StoreSDNode *St = cast<StoreSDNode>(N);
9241 if (St->isVolatile())
9244 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9245 // pack all of the elements in one place. Next, store to memory in fewer
9247 SDValue StVal = St->getValue();
9248 EVT VT = StVal.getValueType();
9249 if (St->isTruncatingStore() && VT.isVector()) {
9250 SelectionDAG &DAG = DCI.DAG;
9251 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9252 EVT StVT = St->getMemoryVT();
9253 unsigned NumElems = VT.getVectorNumElements();
9254 assert(StVT != VT && "Cannot truncate to the same type");
9255 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9256 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9258 // From, To sizes and ElemCount must be pow of two
9259 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9261 // We are going to use the original vector elt for storing.
9262 // Accumulated smaller vector elements must be a multiple of the store size.
9263 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9265 unsigned SizeRatio = FromEltSz / ToEltSz;
9266 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9268 // Create a type on which we perform the shuffle.
9269 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9270 NumElems*SizeRatio);
9271 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9274 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9275 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9276 for (unsigned i = 0; i < NumElems; ++i)
9277 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9279 // Can't shuffle using an illegal type.
9280 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9282 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9283 DAG.getUNDEF(WideVec.getValueType()),
9285 // At this point all of the data is stored at the bottom of the
9286 // register. We now need to save it to mem.
9288 // Find the largest store unit
9289 MVT StoreType = MVT::i8;
9290 for (MVT Tp : MVT::integer_valuetypes()) {
9291 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9294 // Didn't find a legal store type.
9295 if (!TLI.isTypeLegal(StoreType))
9298 // Bitcast the original vector into a vector of store-size units
9299 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9300 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9301 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9302 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9303 SmallVector<SDValue, 8> Chains;
9304 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, DL,
9305 TLI.getPointerTy());
9306 SDValue BasePtr = St->getBasePtr();
9308 // Perform one or more big stores into memory.
9309 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9310 for (unsigned I = 0; I < E; I++) {
9311 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9312 StoreType, ShuffWide,
9313 DAG.getIntPtrConstant(I, DL));
9314 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9315 St->getPointerInfo(), St->isVolatile(),
9316 St->isNonTemporal(), St->getAlignment());
9317 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9319 Chains.push_back(Ch);
9321 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9324 if (!ISD::isNormalStore(St))
9327 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9328 // ARM stores of arguments in the same cache line.
9329 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9330 StVal.getNode()->hasOneUse()) {
9331 SelectionDAG &DAG = DCI.DAG;
9332 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9334 SDValue BasePtr = St->getBasePtr();
9335 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9336 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9337 BasePtr, St->getPointerInfo(), St->isVolatile(),
9338 St->isNonTemporal(), St->getAlignment());
9340 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9341 DAG.getConstant(4, DL, MVT::i32));
9342 return DAG.getStore(NewST1.getValue(0), DL,
9343 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9344 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9345 St->isNonTemporal(),
9346 std::min(4U, St->getAlignment() / 2));
9349 if (StVal.getValueType() == MVT::i64 &&
9350 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9352 // Bitcast an i64 store extracted from a vector to f64.
9353 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9354 SelectionDAG &DAG = DCI.DAG;
9356 SDValue IntVec = StVal.getOperand(0);
9357 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9358 IntVec.getValueType().getVectorNumElements());
9359 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9360 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9361 Vec, StVal.getOperand(1));
9363 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9364 // Make the DAGCombiner fold the bitcasts.
9365 DCI.AddToWorklist(Vec.getNode());
9366 DCI.AddToWorklist(ExtElt.getNode());
9367 DCI.AddToWorklist(V.getNode());
9368 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9369 St->getPointerInfo(), St->isVolatile(),
9370 St->isNonTemporal(), St->getAlignment(),
9374 // If this is a legal vector store, try to combine it into a VST1_UPD.
9375 if (ISD::isNormalStore(N) && VT.isVector() &&
9376 DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9377 return CombineBaseUpdate(N, DCI);
9382 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9383 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9384 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9388 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9390 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9395 APFloat APF = C->getValueAPF();
9396 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9397 != APFloat::opOK || !isExact)
9400 c0 = (I == 0) ? cN : c0;
9401 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9408 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9409 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9410 /// when the VMUL has a constant operand that is a power of 2.
9412 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9413 /// vmul.f32 d16, d17, d16
9414 /// vcvt.s32.f32 d16, d16
9416 /// vcvt.s32.f32 d16, d16, #3
9417 static SDValue PerformVCVTCombine(SDNode *N,
9418 TargetLowering::DAGCombinerInfo &DCI,
9419 const ARMSubtarget *Subtarget) {
9420 SelectionDAG &DAG = DCI.DAG;
9421 SDValue Op = N->getOperand(0);
9423 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9424 Op.getOpcode() != ISD::FMUL)
9428 SDValue N0 = Op->getOperand(0);
9429 SDValue ConstVec = Op->getOperand(1);
9430 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9432 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9433 !isConstVecPow2(ConstVec, isSigned, C))
9436 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9437 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9438 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9439 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9441 // These instructions only exist converting from f32 to i32. We can handle
9442 // smaller integers by generating an extra truncate, but larger ones would
9443 // be lossy. We also can't handle more then 4 lanes, since these intructions
9444 // only support v2i32/v4i32 types.
9449 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9450 Intrinsic::arm_neon_vcvtfp2fxu;
9451 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9452 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9453 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9455 DAG.getConstant(Log2_64(C), dl, MVT::i32));
9457 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9458 FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9463 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9464 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9465 /// when the VDIV has a constant operand that is a power of 2.
9467 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9468 /// vcvt.f32.s32 d16, d16
9469 /// vdiv.f32 d16, d17, d16
9471 /// vcvt.f32.s32 d16, d16, #3
9472 static SDValue PerformVDIVCombine(SDNode *N,
9473 TargetLowering::DAGCombinerInfo &DCI,
9474 const ARMSubtarget *Subtarget) {
9475 SelectionDAG &DAG = DCI.DAG;
9476 SDValue Op = N->getOperand(0);
9477 unsigned OpOpcode = Op.getNode()->getOpcode();
9479 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9480 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9484 SDValue ConstVec = N->getOperand(1);
9485 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9487 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9488 !isConstVecPow2(ConstVec, isSigned, C))
9491 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9492 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9493 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9494 // These instructions only exist converting from i32 to f32. We can handle
9495 // smaller integers by generating an extra extend, but larger ones would
9501 SDValue ConvInput = Op.getOperand(0);
9502 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9503 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9504 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9505 dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9508 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9509 Intrinsic::arm_neon_vcvtfxu2fp;
9510 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9512 DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9513 ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9516 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9517 /// operand of a vector shift operation, where all the elements of the
9518 /// build_vector must have the same constant integer value.
9519 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9520 // Ignore bit_converts.
9521 while (Op.getOpcode() == ISD::BITCAST)
9522 Op = Op.getOperand(0);
9523 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9524 APInt SplatBits, SplatUndef;
9525 unsigned SplatBitSize;
9527 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9528 HasAnyUndefs, ElementBits) ||
9529 SplatBitSize > ElementBits)
9531 Cnt = SplatBits.getSExtValue();
9535 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9536 /// operand of a vector shift left operation. That value must be in the range:
9537 /// 0 <= Value < ElementBits for a left shift; or
9538 /// 0 <= Value <= ElementBits for a long left shift.
9539 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9540 assert(VT.isVector() && "vector shift count is not a vector type");
9541 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9542 if (! getVShiftImm(Op, ElementBits, Cnt))
9544 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9547 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9548 /// operand of a vector shift right operation. For a shift opcode, the value
9549 /// is positive, but for an intrinsic the value count must be negative. The
9550 /// absolute value must be in the range:
9551 /// 1 <= |Value| <= ElementBits for a right shift; or
9552 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9553 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9555 assert(VT.isVector() && "vector shift count is not a vector type");
9556 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9557 if (! getVShiftImm(Op, ElementBits, Cnt))
9561 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9564 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9565 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9566 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9569 // Don't do anything for most intrinsics.
9572 // Vector shifts: check for immediate versions and lower them.
9573 // Note: This is done during DAG combining instead of DAG legalizing because
9574 // the build_vectors for 64-bit vector element shift counts are generally
9575 // not legal, and it is hard to see their values after they get legalized to
9576 // loads from a constant pool.
9577 case Intrinsic::arm_neon_vshifts:
9578 case Intrinsic::arm_neon_vshiftu:
9579 case Intrinsic::arm_neon_vrshifts:
9580 case Intrinsic::arm_neon_vrshiftu:
9581 case Intrinsic::arm_neon_vrshiftn:
9582 case Intrinsic::arm_neon_vqshifts:
9583 case Intrinsic::arm_neon_vqshiftu:
9584 case Intrinsic::arm_neon_vqshiftsu:
9585 case Intrinsic::arm_neon_vqshiftns:
9586 case Intrinsic::arm_neon_vqshiftnu:
9587 case Intrinsic::arm_neon_vqshiftnsu:
9588 case Intrinsic::arm_neon_vqrshiftns:
9589 case Intrinsic::arm_neon_vqrshiftnu:
9590 case Intrinsic::arm_neon_vqrshiftnsu: {
9591 EVT VT = N->getOperand(1).getValueType();
9593 unsigned VShiftOpc = 0;
9596 case Intrinsic::arm_neon_vshifts:
9597 case Intrinsic::arm_neon_vshiftu:
9598 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9599 VShiftOpc = ARMISD::VSHL;
9602 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9603 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9604 ARMISD::VSHRs : ARMISD::VSHRu);
9609 case Intrinsic::arm_neon_vrshifts:
9610 case Intrinsic::arm_neon_vrshiftu:
9611 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9615 case Intrinsic::arm_neon_vqshifts:
9616 case Intrinsic::arm_neon_vqshiftu:
9617 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9621 case Intrinsic::arm_neon_vqshiftsu:
9622 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9624 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9626 case Intrinsic::arm_neon_vrshiftn:
9627 case Intrinsic::arm_neon_vqshiftns:
9628 case Intrinsic::arm_neon_vqshiftnu:
9629 case Intrinsic::arm_neon_vqshiftnsu:
9630 case Intrinsic::arm_neon_vqrshiftns:
9631 case Intrinsic::arm_neon_vqrshiftnu:
9632 case Intrinsic::arm_neon_vqrshiftnsu:
9633 // Narrowing shifts require an immediate right shift.
9634 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9636 llvm_unreachable("invalid shift count for narrowing vector shift "
9640 llvm_unreachable("unhandled vector shift");
9644 case Intrinsic::arm_neon_vshifts:
9645 case Intrinsic::arm_neon_vshiftu:
9646 // Opcode already set above.
9648 case Intrinsic::arm_neon_vrshifts:
9649 VShiftOpc = ARMISD::VRSHRs; break;
9650 case Intrinsic::arm_neon_vrshiftu:
9651 VShiftOpc = ARMISD::VRSHRu; break;
9652 case Intrinsic::arm_neon_vrshiftn:
9653 VShiftOpc = ARMISD::VRSHRN; break;
9654 case Intrinsic::arm_neon_vqshifts:
9655 VShiftOpc = ARMISD::VQSHLs; break;
9656 case Intrinsic::arm_neon_vqshiftu:
9657 VShiftOpc = ARMISD::VQSHLu; break;
9658 case Intrinsic::arm_neon_vqshiftsu:
9659 VShiftOpc = ARMISD::VQSHLsu; break;
9660 case Intrinsic::arm_neon_vqshiftns:
9661 VShiftOpc = ARMISD::VQSHRNs; break;
9662 case Intrinsic::arm_neon_vqshiftnu:
9663 VShiftOpc = ARMISD::VQSHRNu; break;
9664 case Intrinsic::arm_neon_vqshiftnsu:
9665 VShiftOpc = ARMISD::VQSHRNsu; break;
9666 case Intrinsic::arm_neon_vqrshiftns:
9667 VShiftOpc = ARMISD::VQRSHRNs; break;
9668 case Intrinsic::arm_neon_vqrshiftnu:
9669 VShiftOpc = ARMISD::VQRSHRNu; break;
9670 case Intrinsic::arm_neon_vqrshiftnsu:
9671 VShiftOpc = ARMISD::VQRSHRNsu; break;
9675 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9676 N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
9679 case Intrinsic::arm_neon_vshiftins: {
9680 EVT VT = N->getOperand(1).getValueType();
9682 unsigned VShiftOpc = 0;
9684 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9685 VShiftOpc = ARMISD::VSLI;
9686 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9687 VShiftOpc = ARMISD::VSRI;
9689 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9693 return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
9694 N->getOperand(1), N->getOperand(2),
9695 DAG.getConstant(Cnt, dl, MVT::i32));
9698 case Intrinsic::arm_neon_vqrshifts:
9699 case Intrinsic::arm_neon_vqrshiftu:
9700 // No immediate versions of these to check for.
9707 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9708 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9709 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9710 /// vector element shift counts are generally not legal, and it is hard to see
9711 /// their values after they get legalized to loads from a constant pool.
9712 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9713 const ARMSubtarget *ST) {
9714 EVT VT = N->getValueType(0);
9715 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9716 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9717 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9718 SDValue N1 = N->getOperand(1);
9719 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9720 SDValue N0 = N->getOperand(0);
9721 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9722 DAG.MaskedValueIsZero(N0.getOperand(0),
9723 APInt::getHighBitsSet(32, 16)))
9724 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9728 // Nothing to be done for scalar shifts.
9729 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9730 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9733 assert(ST->hasNEON() && "unexpected vector shift");
9736 switch (N->getOpcode()) {
9737 default: llvm_unreachable("unexpected shift opcode");
9740 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
9742 return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
9743 DAG.getConstant(Cnt, dl, MVT::i32));
9749 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9750 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9751 ARMISD::VSHRs : ARMISD::VSHRu);
9753 return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
9754 DAG.getConstant(Cnt, dl, MVT::i32));
9760 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9761 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9762 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9763 const ARMSubtarget *ST) {
9764 SDValue N0 = N->getOperand(0);
9766 // Check for sign- and zero-extensions of vector extract operations of 8-
9767 // and 16-bit vector elements. NEON supports these directly. They are
9768 // handled during DAG combining because type legalization will promote them
9769 // to 32-bit types and it is messy to recognize the operations after that.
9770 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9771 SDValue Vec = N0.getOperand(0);
9772 SDValue Lane = N0.getOperand(1);
9773 EVT VT = N->getValueType(0);
9774 EVT EltVT = N0.getValueType();
9775 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9777 if (VT == MVT::i32 &&
9778 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9779 TLI.isTypeLegal(Vec.getValueType()) &&
9780 isa<ConstantSDNode>(Lane)) {
9783 switch (N->getOpcode()) {
9784 default: llvm_unreachable("unexpected opcode");
9785 case ISD::SIGN_EXTEND:
9786 Opc = ARMISD::VGETLANEs;
9788 case ISD::ZERO_EXTEND:
9789 case ISD::ANY_EXTEND:
9790 Opc = ARMISD::VGETLANEu;
9793 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9800 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9801 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9802 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9803 const ARMSubtarget *ST) {
9804 // If the target supports NEON, try to use vmax/vmin instructions for f32
9805 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9806 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9807 // a NaN; only do the transformation when it matches that behavior.
9809 // For now only do this when using NEON for FP operations; if using VFP, it
9810 // is not obvious that the benefit outweighs the cost of switching to the
9812 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9813 N->getValueType(0) != MVT::f32)
9816 SDValue CondLHS = N->getOperand(0);
9817 SDValue CondRHS = N->getOperand(1);
9818 SDValue LHS = N->getOperand(2);
9819 SDValue RHS = N->getOperand(3);
9820 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9822 unsigned Opcode = 0;
9824 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9825 IsReversed = false; // x CC y ? x : y
9826 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9827 IsReversed = true ; // x CC y ? y : x
9841 // If LHS is NaN, an ordered comparison will be false and the result will
9842 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9843 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9844 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9845 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9847 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9848 // will return -0, so vmin can only be used for unsafe math or if one of
9849 // the operands is known to be nonzero.
9850 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9851 !DAG.getTarget().Options.UnsafeFPMath &&
9852 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9854 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9863 // If LHS is NaN, an ordered comparison will be false and the result will
9864 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9865 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9866 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9867 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9869 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9870 // will return +0, so vmax can only be used for unsafe math or if one of
9871 // the operands is known to be nonzero.
9872 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9873 !DAG.getTarget().Options.UnsafeFPMath &&
9874 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9876 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9882 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9885 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9887 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9888 SDValue Cmp = N->getOperand(4);
9889 if (Cmp.getOpcode() != ARMISD::CMPZ)
9890 // Only looking at EQ and NE cases.
9893 EVT VT = N->getValueType(0);
9895 SDValue LHS = Cmp.getOperand(0);
9896 SDValue RHS = Cmp.getOperand(1);
9897 SDValue FalseVal = N->getOperand(0);
9898 SDValue TrueVal = N->getOperand(1);
9899 SDValue ARMcc = N->getOperand(2);
9900 ARMCC::CondCodes CC =
9901 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9919 /// FIXME: Turn this into a target neutral optimization?
9921 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9922 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9923 N->getOperand(3), Cmp);
9924 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9926 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9927 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9928 N->getOperand(3), NewCmp);
9931 if (Res.getNode()) {
9932 APInt KnownZero, KnownOne;
9933 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9934 // Capture demanded bits information that would be otherwise lost.
9935 if (KnownZero == 0xfffffffe)
9936 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9937 DAG.getValueType(MVT::i1));
9938 else if (KnownZero == 0xffffff00)
9939 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9940 DAG.getValueType(MVT::i8));
9941 else if (KnownZero == 0xffff0000)
9942 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9943 DAG.getValueType(MVT::i16));
9949 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9950 DAGCombinerInfo &DCI) const {
9951 switch (N->getOpcode()) {
9953 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9954 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9955 case ISD::SUB: return PerformSUBCombine(N, DCI);
9956 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9957 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9958 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9959 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9960 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9961 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9962 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9963 case ISD::STORE: return PerformSTORECombine(N, DCI);
9964 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9965 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9966 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9967 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9968 case ISD::FP_TO_SINT:
9969 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9970 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9971 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9974 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9975 case ISD::SIGN_EXTEND:
9976 case ISD::ZERO_EXTEND:
9977 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9978 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9979 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9980 case ISD::LOAD: return PerformLOADCombine(N, DCI);
9981 case ARMISD::VLD2DUP:
9982 case ARMISD::VLD3DUP:
9983 case ARMISD::VLD4DUP:
9984 return PerformVLDCombine(N, DCI);
9985 case ARMISD::BUILD_VECTOR:
9986 return PerformARMBUILD_VECTORCombine(N, DCI);
9987 case ISD::INTRINSIC_VOID:
9988 case ISD::INTRINSIC_W_CHAIN:
9989 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9990 case Intrinsic::arm_neon_vld1:
9991 case Intrinsic::arm_neon_vld2:
9992 case Intrinsic::arm_neon_vld3:
9993 case Intrinsic::arm_neon_vld4:
9994 case Intrinsic::arm_neon_vld2lane:
9995 case Intrinsic::arm_neon_vld3lane:
9996 case Intrinsic::arm_neon_vld4lane:
9997 case Intrinsic::arm_neon_vst1:
9998 case Intrinsic::arm_neon_vst2:
9999 case Intrinsic::arm_neon_vst3:
10000 case Intrinsic::arm_neon_vst4:
10001 case Intrinsic::arm_neon_vst2lane:
10002 case Intrinsic::arm_neon_vst3lane:
10003 case Intrinsic::arm_neon_vst4lane:
10004 return PerformVLDCombine(N, DCI);
10012 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10014 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10017 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10020 bool *Fast) const {
10021 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10022 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10024 switch (VT.getSimpleVT().SimpleTy) {
10030 // Unaligned access can use (for example) LRDB, LRDH, LDR
10031 if (AllowsUnaligned) {
10033 *Fast = Subtarget->hasV7Ops();
10040 // For any little-endian targets with neon, we can support unaligned ld/st
10041 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10042 // A big-endian target may also explicitly support unaligned accesses
10043 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10053 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10054 unsigned AlignCheck) {
10055 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10056 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10059 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10060 unsigned DstAlign, unsigned SrcAlign,
10061 bool IsMemset, bool ZeroMemset,
10063 MachineFunction &MF) const {
10064 const Function *F = MF.getFunction();
10066 // See if we can use NEON instructions for this...
10067 if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10068 !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10071 (memOpAlign(SrcAlign, DstAlign, 16) ||
10072 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10074 } else if (Size >= 8 &&
10075 (memOpAlign(SrcAlign, DstAlign, 8) ||
10076 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10082 // Lowering to i32/i16 if the size permits.
10085 else if (Size >= 2)
10088 // Let the target-independent logic figure it out.
10092 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10093 if (Val.getOpcode() != ISD::LOAD)
10096 EVT VT1 = Val.getValueType();
10097 if (!VT1.isSimple() || !VT1.isInteger() ||
10098 !VT2.isSimple() || !VT2.isInteger())
10101 switch (VT1.getSimpleVT().SimpleTy) {
10106 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10113 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10114 EVT VT = ExtVal.getValueType();
10116 if (!isTypeLegal(VT))
10119 // Don't create a loadext if we can fold the extension into a wide/long
10121 // If there's more than one user instruction, the loadext is desirable no
10122 // matter what. There can be two uses by the same instruction.
10123 if (ExtVal->use_empty() ||
10124 !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10127 SDNode *U = *ExtVal->use_begin();
10128 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10129 U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10135 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10136 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10139 if (!isTypeLegal(EVT::getEVT(Ty1)))
10142 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10144 // Assuming the caller doesn't have a zeroext or signext return parameter,
10145 // truncation all the way down to i1 is valid.
10150 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10154 unsigned Scale = 1;
10155 switch (VT.getSimpleVT().SimpleTy) {
10156 default: return false;
10171 if ((V & (Scale - 1)) != 0)
10174 return V == (V & ((1LL << 5) - 1));
10177 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10178 const ARMSubtarget *Subtarget) {
10179 bool isNeg = false;
10185 switch (VT.getSimpleVT().SimpleTy) {
10186 default: return false;
10191 // + imm12 or - imm8
10193 return V == (V & ((1LL << 8) - 1));
10194 return V == (V & ((1LL << 12) - 1));
10197 // Same as ARM mode. FIXME: NEON?
10198 if (!Subtarget->hasVFP2())
10203 return V == (V & ((1LL << 8) - 1));
10207 /// isLegalAddressImmediate - Return true if the integer value can be used
10208 /// as the offset of the target addressing mode for load / store of the
10210 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10211 const ARMSubtarget *Subtarget) {
10215 if (!VT.isSimple())
10218 if (Subtarget->isThumb1Only())
10219 return isLegalT1AddressImmediate(V, VT);
10220 else if (Subtarget->isThumb2())
10221 return isLegalT2AddressImmediate(V, VT, Subtarget);
10226 switch (VT.getSimpleVT().SimpleTy) {
10227 default: return false;
10232 return V == (V & ((1LL << 12) - 1));
10235 return V == (V & ((1LL << 8) - 1));
10238 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10243 return V == (V & ((1LL << 8) - 1));
10247 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10249 int Scale = AM.Scale;
10253 switch (VT.getSimpleVT().SimpleTy) {
10254 default: return false;
10262 Scale = Scale & ~1;
10263 return Scale == 2 || Scale == 4 || Scale == 8;
10266 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10270 // Note, we allow "void" uses (basically, uses that aren't loads or
10271 // stores), because arm allows folding a scale into many arithmetic
10272 // operations. This should be made more precise and revisited later.
10274 // Allow r << imm, but the imm has to be a multiple of two.
10275 if (Scale & 1) return false;
10276 return isPowerOf2_32(Scale);
10280 /// isLegalAddressingMode - Return true if the addressing mode represented
10281 /// by AM is legal for this target, for a load/store of the specified type.
10282 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10284 unsigned AS) const {
10285 EVT VT = getValueType(Ty, true);
10286 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10289 // Can never fold addr of global into load/store.
10293 switch (AM.Scale) {
10294 case 0: // no scale reg, must be "r+i" or "r", or "i".
10297 if (Subtarget->isThumb1Only())
10301 // ARM doesn't support any R+R*scale+imm addr modes.
10305 if (!VT.isSimple())
10308 if (Subtarget->isThumb2())
10309 return isLegalT2ScaledAddressingMode(AM, VT);
10311 int Scale = AM.Scale;
10312 switch (VT.getSimpleVT().SimpleTy) {
10313 default: return false;
10317 if (Scale < 0) Scale = -Scale;
10321 return isPowerOf2_32(Scale & ~1);
10325 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10330 // Note, we allow "void" uses (basically, uses that aren't loads or
10331 // stores), because arm allows folding a scale into many arithmetic
10332 // operations. This should be made more precise and revisited later.
10334 // Allow r << imm, but the imm has to be a multiple of two.
10335 if (Scale & 1) return false;
10336 return isPowerOf2_32(Scale);
10342 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10343 /// icmp immediate, that is the target has icmp instructions which can compare
10344 /// a register against the immediate without having to materialize the
10345 /// immediate into a register.
10346 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10347 // Thumb2 and ARM modes can use cmn for negative immediates.
10348 if (!Subtarget->isThumb())
10349 return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10350 if (Subtarget->isThumb2())
10351 return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10352 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10353 return Imm >= 0 && Imm <= 255;
10356 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10357 /// *or sub* immediate, that is the target has add or sub instructions which can
10358 /// add a register with the immediate without having to materialize the
10359 /// immediate into a register.
10360 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10361 // Same encoding for add/sub, just flip the sign.
10362 int64_t AbsImm = std::abs(Imm);
10363 if (!Subtarget->isThumb())
10364 return ARM_AM::getSOImmVal(AbsImm) != -1;
10365 if (Subtarget->isThumb2())
10366 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10367 // Thumb1 only has 8-bit unsigned immediate.
10368 return AbsImm >= 0 && AbsImm <= 255;
10371 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10372 bool isSEXTLoad, SDValue &Base,
10373 SDValue &Offset, bool &isInc,
10374 SelectionDAG &DAG) {
10375 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10378 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10379 // AddressingMode 3
10380 Base = Ptr->getOperand(0);
10381 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10382 int RHSC = (int)RHS->getZExtValue();
10383 if (RHSC < 0 && RHSC > -256) {
10384 assert(Ptr->getOpcode() == ISD::ADD);
10386 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10390 isInc = (Ptr->getOpcode() == ISD::ADD);
10391 Offset = Ptr->getOperand(1);
10393 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10394 // AddressingMode 2
10395 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10396 int RHSC = (int)RHS->getZExtValue();
10397 if (RHSC < 0 && RHSC > -0x1000) {
10398 assert(Ptr->getOpcode() == ISD::ADD);
10400 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10401 Base = Ptr->getOperand(0);
10406 if (Ptr->getOpcode() == ISD::ADD) {
10408 ARM_AM::ShiftOpc ShOpcVal=
10409 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10410 if (ShOpcVal != ARM_AM::no_shift) {
10411 Base = Ptr->getOperand(1);
10412 Offset = Ptr->getOperand(0);
10414 Base = Ptr->getOperand(0);
10415 Offset = Ptr->getOperand(1);
10420 isInc = (Ptr->getOpcode() == ISD::ADD);
10421 Base = Ptr->getOperand(0);
10422 Offset = Ptr->getOperand(1);
10426 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10430 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10431 bool isSEXTLoad, SDValue &Base,
10432 SDValue &Offset, bool &isInc,
10433 SelectionDAG &DAG) {
10434 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10437 Base = Ptr->getOperand(0);
10438 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10439 int RHSC = (int)RHS->getZExtValue();
10440 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10441 assert(Ptr->getOpcode() == ISD::ADD);
10443 Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10445 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10446 isInc = Ptr->getOpcode() == ISD::ADD;
10447 Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10455 /// getPreIndexedAddressParts - returns true by value, base pointer and
10456 /// offset pointer and addressing mode by reference if the node's address
10457 /// can be legally represented as pre-indexed load / store address.
10459 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10461 ISD::MemIndexedMode &AM,
10462 SelectionDAG &DAG) const {
10463 if (Subtarget->isThumb1Only())
10468 bool isSEXTLoad = false;
10469 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10470 Ptr = LD->getBasePtr();
10471 VT = LD->getMemoryVT();
10472 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10473 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10474 Ptr = ST->getBasePtr();
10475 VT = ST->getMemoryVT();
10480 bool isLegal = false;
10481 if (Subtarget->isThumb2())
10482 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10483 Offset, isInc, DAG);
10485 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10486 Offset, isInc, DAG);
10490 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10494 /// getPostIndexedAddressParts - returns true by value, base pointer and
10495 /// offset pointer and addressing mode by reference if this node can be
10496 /// combined with a load / store to form a post-indexed load / store.
10497 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10500 ISD::MemIndexedMode &AM,
10501 SelectionDAG &DAG) const {
10502 if (Subtarget->isThumb1Only())
10507 bool isSEXTLoad = false;
10508 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10509 VT = LD->getMemoryVT();
10510 Ptr = LD->getBasePtr();
10511 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10512 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10513 VT = ST->getMemoryVT();
10514 Ptr = ST->getBasePtr();
10519 bool isLegal = false;
10520 if (Subtarget->isThumb2())
10521 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10524 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10530 // Swap base ptr and offset to catch more post-index load / store when
10531 // it's legal. In Thumb2 mode, offset must be an immediate.
10532 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10533 !Subtarget->isThumb2())
10534 std::swap(Base, Offset);
10536 // Post-indexed load / store update the base pointer.
10541 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10545 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10548 const SelectionDAG &DAG,
10549 unsigned Depth) const {
10550 unsigned BitWidth = KnownOne.getBitWidth();
10551 KnownZero = KnownOne = APInt(BitWidth, 0);
10552 switch (Op.getOpcode()) {
10558 // These nodes' second result is a boolean
10559 if (Op.getResNo() == 0)
10561 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10563 case ARMISD::CMOV: {
10564 // Bits are known zero/one if known on the LHS and RHS.
10565 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10566 if (KnownZero == 0 && KnownOne == 0) return;
10568 APInt KnownZeroRHS, KnownOneRHS;
10569 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10570 KnownZero &= KnownZeroRHS;
10571 KnownOne &= KnownOneRHS;
10574 case ISD::INTRINSIC_W_CHAIN: {
10575 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10576 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10579 case Intrinsic::arm_ldaex:
10580 case Intrinsic::arm_ldrex: {
10581 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10582 unsigned MemBits = VT.getScalarType().getSizeInBits();
10583 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10591 //===----------------------------------------------------------------------===//
10592 // ARM Inline Assembly Support
10593 //===----------------------------------------------------------------------===//
10595 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10596 // Looking for "rev" which is V6+.
10597 if (!Subtarget->hasV6Ops())
10600 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10601 std::string AsmStr = IA->getAsmString();
10602 SmallVector<StringRef, 4> AsmPieces;
10603 SplitString(AsmStr, AsmPieces, ";\n");
10605 switch (AsmPieces.size()) {
10606 default: return false;
10608 AsmStr = AsmPieces[0];
10610 SplitString(AsmStr, AsmPieces, " \t,");
10613 if (AsmPieces.size() == 3 &&
10614 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10615 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10616 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10617 if (Ty && Ty->getBitWidth() == 32)
10618 return IntrinsicLowering::LowerToByteSwap(CI);
10626 /// getConstraintType - Given a constraint letter, return the type of
10627 /// constraint it is for this target.
10628 ARMTargetLowering::ConstraintType
10629 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10630 if (Constraint.size() == 1) {
10631 switch (Constraint[0]) {
10633 case 'l': return C_RegisterClass;
10634 case 'w': return C_RegisterClass;
10635 case 'h': return C_RegisterClass;
10636 case 'x': return C_RegisterClass;
10637 case 't': return C_RegisterClass;
10638 case 'j': return C_Other; // Constant for movw.
10639 // An address with a single base register. Due to the way we
10640 // currently handle addresses it is the same as an 'r' memory constraint.
10641 case 'Q': return C_Memory;
10643 } else if (Constraint.size() == 2) {
10644 switch (Constraint[0]) {
10646 // All 'U+' constraints are addresses.
10647 case 'U': return C_Memory;
10650 return TargetLowering::getConstraintType(Constraint);
10653 /// Examine constraint type and operand type and determine a weight value.
10654 /// This object must already have been set up with the operand type
10655 /// and the current alternative constraint selected.
10656 TargetLowering::ConstraintWeight
10657 ARMTargetLowering::getSingleConstraintMatchWeight(
10658 AsmOperandInfo &info, const char *constraint) const {
10659 ConstraintWeight weight = CW_Invalid;
10660 Value *CallOperandVal = info.CallOperandVal;
10661 // If we don't have a value, we can't do a match,
10662 // but allow it at the lowest weight.
10663 if (!CallOperandVal)
10665 Type *type = CallOperandVal->getType();
10666 // Look at the constraint type.
10667 switch (*constraint) {
10669 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10672 if (type->isIntegerTy()) {
10673 if (Subtarget->isThumb())
10674 weight = CW_SpecificReg;
10676 weight = CW_Register;
10680 if (type->isFloatingPointTy())
10681 weight = CW_Register;
10687 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10689 ARMTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10690 const std::string &Constraint,
10692 if (Constraint.size() == 1) {
10693 // GCC ARM Constraint Letters
10694 switch (Constraint[0]) {
10695 case 'l': // Low regs or general regs.
10696 if (Subtarget->isThumb())
10697 return RCPair(0U, &ARM::tGPRRegClass);
10698 return RCPair(0U, &ARM::GPRRegClass);
10699 case 'h': // High regs or no regs.
10700 if (Subtarget->isThumb())
10701 return RCPair(0U, &ARM::hGPRRegClass);
10704 if (Subtarget->isThumb1Only())
10705 return RCPair(0U, &ARM::tGPRRegClass);
10706 return RCPair(0U, &ARM::GPRRegClass);
10708 if (VT == MVT::Other)
10710 if (VT == MVT::f32)
10711 return RCPair(0U, &ARM::SPRRegClass);
10712 if (VT.getSizeInBits() == 64)
10713 return RCPair(0U, &ARM::DPRRegClass);
10714 if (VT.getSizeInBits() == 128)
10715 return RCPair(0U, &ARM::QPRRegClass);
10718 if (VT == MVT::Other)
10720 if (VT == MVT::f32)
10721 return RCPair(0U, &ARM::SPR_8RegClass);
10722 if (VT.getSizeInBits() == 64)
10723 return RCPair(0U, &ARM::DPR_8RegClass);
10724 if (VT.getSizeInBits() == 128)
10725 return RCPair(0U, &ARM::QPR_8RegClass);
10728 if (VT == MVT::f32)
10729 return RCPair(0U, &ARM::SPRRegClass);
10733 if (StringRef("{cc}").equals_lower(Constraint))
10734 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10736 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10739 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10740 /// vector. If it is invalid, don't add anything to Ops.
10741 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10742 std::string &Constraint,
10743 std::vector<SDValue>&Ops,
10744 SelectionDAG &DAG) const {
10747 // Currently only support length 1 constraints.
10748 if (Constraint.length() != 1) return;
10750 char ConstraintLetter = Constraint[0];
10751 switch (ConstraintLetter) {
10754 case 'I': case 'J': case 'K': case 'L':
10755 case 'M': case 'N': case 'O':
10756 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10760 int64_t CVal64 = C->getSExtValue();
10761 int CVal = (int) CVal64;
10762 // None of these constraints allow values larger than 32 bits. Check
10763 // that the value fits in an int.
10764 if (CVal != CVal64)
10767 switch (ConstraintLetter) {
10769 // Constant suitable for movw, must be between 0 and
10771 if (Subtarget->hasV6T2Ops())
10772 if (CVal >= 0 && CVal <= 65535)
10776 if (Subtarget->isThumb1Only()) {
10777 // This must be a constant between 0 and 255, for ADD
10779 if (CVal >= 0 && CVal <= 255)
10781 } else if (Subtarget->isThumb2()) {
10782 // A constant that can be used as an immediate value in a
10783 // data-processing instruction.
10784 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10787 // A constant that can be used as an immediate value in a
10788 // data-processing instruction.
10789 if (ARM_AM::getSOImmVal(CVal) != -1)
10795 if (Subtarget->isThumb()) { // FIXME thumb2
10796 // This must be a constant between -255 and -1, for negated ADD
10797 // immediates. This can be used in GCC with an "n" modifier that
10798 // prints the negated value, for use with SUB instructions. It is
10799 // not useful otherwise but is implemented for compatibility.
10800 if (CVal >= -255 && CVal <= -1)
10803 // This must be a constant between -4095 and 4095. It is not clear
10804 // what this constraint is intended for. Implemented for
10805 // compatibility with GCC.
10806 if (CVal >= -4095 && CVal <= 4095)
10812 if (Subtarget->isThumb1Only()) {
10813 // A 32-bit value where only one byte has a nonzero value. Exclude
10814 // zero to match GCC. This constraint is used by GCC internally for
10815 // constants that can be loaded with a move/shift combination.
10816 // It is not useful otherwise but is implemented for compatibility.
10817 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10819 } else if (Subtarget->isThumb2()) {
10820 // A constant whose bitwise inverse can be used as an immediate
10821 // value in a data-processing instruction. This can be used in GCC
10822 // with a "B" modifier that prints the inverted value, for use with
10823 // BIC and MVN instructions. It is not useful otherwise but is
10824 // implemented for compatibility.
10825 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10828 // A constant whose bitwise inverse can be used as an immediate
10829 // value in a data-processing instruction. This can be used in GCC
10830 // with a "B" modifier that prints the inverted value, for use with
10831 // BIC and MVN instructions. It is not useful otherwise but is
10832 // implemented for compatibility.
10833 if (ARM_AM::getSOImmVal(~CVal) != -1)
10839 if (Subtarget->isThumb1Only()) {
10840 // This must be a constant between -7 and 7,
10841 // for 3-operand ADD/SUB immediate instructions.
10842 if (CVal >= -7 && CVal < 7)
10844 } else if (Subtarget->isThumb2()) {
10845 // A constant whose negation can be used as an immediate value in a
10846 // data-processing instruction. This can be used in GCC with an "n"
10847 // modifier that prints the negated value, for use with SUB
10848 // instructions. It is not useful otherwise but is implemented for
10850 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10853 // A constant whose negation can be used as an immediate value in a
10854 // data-processing instruction. This can be used in GCC with an "n"
10855 // modifier that prints the negated value, for use with SUB
10856 // instructions. It is not useful otherwise but is implemented for
10858 if (ARM_AM::getSOImmVal(-CVal) != -1)
10864 if (Subtarget->isThumb()) { // FIXME thumb2
10865 // This must be a multiple of 4 between 0 and 1020, for
10866 // ADD sp + immediate.
10867 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10870 // A power of two or a constant between 0 and 32. This is used in
10871 // GCC for the shift amount on shifted register operands, but it is
10872 // useful in general for any shift amounts.
10873 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10879 if (Subtarget->isThumb()) { // FIXME thumb2
10880 // This must be a constant between 0 and 31, for shift amounts.
10881 if (CVal >= 0 && CVal <= 31)
10887 if (Subtarget->isThumb()) { // FIXME thumb2
10888 // This must be a multiple of 4 between -508 and 508, for
10889 // ADD/SUB sp = sp + immediate.
10890 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10895 Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
10899 if (Result.getNode()) {
10900 Ops.push_back(Result);
10903 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10906 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10907 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10908 unsigned Opcode = Op->getOpcode();
10909 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10910 "Invalid opcode for Div/Rem lowering");
10911 bool isSigned = (Opcode == ISD::SDIVREM);
10912 EVT VT = Op->getValueType(0);
10913 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10916 switch (VT.getSimpleVT().SimpleTy) {
10917 default: llvm_unreachable("Unexpected request for libcall!");
10918 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10919 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10920 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10921 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10924 SDValue InChain = DAG.getEntryNode();
10926 TargetLowering::ArgListTy Args;
10927 TargetLowering::ArgListEntry Entry;
10928 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10929 EVT ArgVT = Op->getOperand(i).getValueType();
10930 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10931 Entry.Node = Op->getOperand(i);
10933 Entry.isSExt = isSigned;
10934 Entry.isZExt = !isSigned;
10935 Args.push_back(Entry);
10938 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10941 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10944 TargetLowering::CallLoweringInfo CLI(DAG);
10945 CLI.setDebugLoc(dl).setChain(InChain)
10946 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10947 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10949 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10950 return CallInfo.first;
10954 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10955 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10959 SDValue Chain = Op.getOperand(0);
10960 SDValue Size = Op.getOperand(1);
10962 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10963 DAG.getConstant(2, DL, MVT::i32));
10966 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10967 Flag = Chain.getValue(1);
10969 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10970 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10972 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10973 Chain = NewSP.getValue(1);
10975 SDValue Ops[2] = { NewSP, Chain };
10976 return DAG.getMergeValues(Ops, DL);
10979 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10980 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10981 "Unexpected type for custom-lowering FP_EXTEND");
10984 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10986 SDValue SrcVal = Op.getOperand(0);
10987 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10988 /*isSigned*/ false, SDLoc(Op)).first;
10991 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10992 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10993 Subtarget->isFPOnlySP() &&
10994 "Unexpected type for custom-lowering FP_ROUND");
10997 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10999 SDValue SrcVal = Op.getOperand(0);
11000 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11001 /*isSigned*/ false, SDLoc(Op)).first;
11005 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11006 // The ARM target isn't yet aware of offsets.
11010 bool ARM::isBitFieldInvertedMask(unsigned v) {
11011 if (v == 0xffffffff)
11014 // there can be 1's on either or both "outsides", all the "inside"
11015 // bits must be 0's
11016 return isShiftedMask_32(~v);
11019 /// isFPImmLegal - Returns true if the target can instruction select the
11020 /// specified FP immediate natively. If false, the legalizer will
11021 /// materialize the FP immediate as a load from a constant pool.
11022 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11023 if (!Subtarget->hasVFP3())
11025 if (VT == MVT::f32)
11026 return ARM_AM::getFP32Imm(Imm) != -1;
11027 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11028 return ARM_AM::getFP64Imm(Imm) != -1;
11032 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11033 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11034 /// specified in the intrinsic calls.
11035 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11037 unsigned Intrinsic) const {
11038 switch (Intrinsic) {
11039 case Intrinsic::arm_neon_vld1:
11040 case Intrinsic::arm_neon_vld2:
11041 case Intrinsic::arm_neon_vld3:
11042 case Intrinsic::arm_neon_vld4:
11043 case Intrinsic::arm_neon_vld2lane:
11044 case Intrinsic::arm_neon_vld3lane:
11045 case Intrinsic::arm_neon_vld4lane: {
11046 Info.opc = ISD::INTRINSIC_W_CHAIN;
11047 // Conservatively set memVT to the entire set of vectors loaded.
11048 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11049 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11050 Info.ptrVal = I.getArgOperand(0);
11052 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11053 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11054 Info.vol = false; // volatile loads with NEON intrinsics not supported
11055 Info.readMem = true;
11056 Info.writeMem = false;
11059 case Intrinsic::arm_neon_vst1:
11060 case Intrinsic::arm_neon_vst2:
11061 case Intrinsic::arm_neon_vst3:
11062 case Intrinsic::arm_neon_vst4:
11063 case Intrinsic::arm_neon_vst2lane:
11064 case Intrinsic::arm_neon_vst3lane:
11065 case Intrinsic::arm_neon_vst4lane: {
11066 Info.opc = ISD::INTRINSIC_VOID;
11067 // Conservatively set memVT to the entire set of vectors stored.
11068 unsigned NumElts = 0;
11069 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11070 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11071 if (!ArgTy->isVectorTy())
11073 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11075 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11076 Info.ptrVal = I.getArgOperand(0);
11078 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11079 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11080 Info.vol = false; // volatile stores with NEON intrinsics not supported
11081 Info.readMem = false;
11082 Info.writeMem = true;
11085 case Intrinsic::arm_ldaex:
11086 case Intrinsic::arm_ldrex: {
11087 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11088 Info.opc = ISD::INTRINSIC_W_CHAIN;
11089 Info.memVT = MVT::getVT(PtrTy->getElementType());
11090 Info.ptrVal = I.getArgOperand(0);
11092 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11094 Info.readMem = true;
11095 Info.writeMem = false;
11098 case Intrinsic::arm_stlex:
11099 case Intrinsic::arm_strex: {
11100 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11101 Info.opc = ISD::INTRINSIC_W_CHAIN;
11102 Info.memVT = MVT::getVT(PtrTy->getElementType());
11103 Info.ptrVal = I.getArgOperand(1);
11105 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11107 Info.readMem = false;
11108 Info.writeMem = true;
11111 case Intrinsic::arm_stlexd:
11112 case Intrinsic::arm_strexd: {
11113 Info.opc = ISD::INTRINSIC_W_CHAIN;
11114 Info.memVT = MVT::i64;
11115 Info.ptrVal = I.getArgOperand(2);
11119 Info.readMem = false;
11120 Info.writeMem = true;
11123 case Intrinsic::arm_ldaexd:
11124 case Intrinsic::arm_ldrexd: {
11125 Info.opc = ISD::INTRINSIC_W_CHAIN;
11126 Info.memVT = MVT::i64;
11127 Info.ptrVal = I.getArgOperand(0);
11131 Info.readMem = true;
11132 Info.writeMem = false;
11142 /// \brief Returns true if it is beneficial to convert a load of a constant
11143 /// to just the constant itself.
11144 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11146 assert(Ty->isIntegerTy());
11148 unsigned Bits = Ty->getPrimitiveSizeInBits();
11149 if (Bits == 0 || Bits > 32)
11154 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11156 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11157 ARM_MB::MemBOpt Domain) const {
11158 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11160 // First, if the target has no DMB, see what fallback we can use.
11161 if (!Subtarget->hasDataBarrier()) {
11162 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11163 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11165 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11166 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11167 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11168 Builder.getInt32(0), Builder.getInt32(7),
11169 Builder.getInt32(10), Builder.getInt32(5)};
11170 return Builder.CreateCall(MCR, args);
11172 // Instead of using barriers, atomic accesses on these subtargets use
11174 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11177 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11178 // Only a full system barrier exists in the M-class architectures.
11179 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11180 Constant *CDomain = Builder.getInt32(Domain);
11181 return Builder.CreateCall(DMB, CDomain);
11185 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11186 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11187 AtomicOrdering Ord, bool IsStore,
11188 bool IsLoad) const {
11189 if (!getInsertFencesForAtomic())
11195 llvm_unreachable("Invalid fence: unordered/non-atomic");
11198 return nullptr; // Nothing to do
11199 case SequentiallyConsistent:
11201 return nullptr; // Nothing to do
11204 case AcquireRelease:
11205 if (Subtarget->isSwift())
11206 return makeDMB(Builder, ARM_MB::ISHST);
11207 // FIXME: add a comment with a link to documentation justifying this.
11209 return makeDMB(Builder, ARM_MB::ISH);
11211 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11214 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11215 AtomicOrdering Ord, bool IsStore,
11216 bool IsLoad) const {
11217 if (!getInsertFencesForAtomic())
11223 llvm_unreachable("Invalid fence: unordered/not-atomic");
11226 return nullptr; // Nothing to do
11228 case AcquireRelease:
11229 case SequentiallyConsistent:
11230 return makeDMB(Builder, ARM_MB::ISH);
11232 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11235 // Loads and stores less than 64-bits are already atomic; ones above that
11236 // are doomed anyway, so defer to the default libcall and blame the OS when
11237 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11238 // anything for those.
11239 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11240 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11241 return (Size == 64) && !Subtarget->isMClass();
11244 // Loads and stores less than 64-bits are already atomic; ones above that
11245 // are doomed anyway, so defer to the default libcall and blame the OS when
11246 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11247 // anything for those.
11248 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11249 // guarantee, see DDI0406C ARM architecture reference manual,
11250 // sections A8.8.72-74 LDRD)
11251 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11252 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11253 return (Size == 64) && !Subtarget->isMClass();
11256 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11257 // and up to 64 bits on the non-M profiles
11258 TargetLoweringBase::AtomicRMWExpansionKind
11259 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11260 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11261 return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11262 ? AtomicRMWExpansionKind::LLSC
11263 : AtomicRMWExpansionKind::None;
11266 // This has so far only been implemented for MachO.
11267 bool ARMTargetLowering::useLoadStackGuardNode() const {
11268 return Subtarget->isTargetMachO();
11271 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11272 unsigned &Cost) const {
11273 // If we do not have NEON, vector types are not natively supported.
11274 if (!Subtarget->hasNEON())
11277 // Floating point values and vector values map to the same register file.
11278 // Therefore, althought we could do a store extract of a vector type, this is
11279 // better to leave at float as we have more freedom in the addressing mode for
11281 if (VectorTy->isFPOrFPVectorTy())
11284 // If the index is unknown at compile time, this is very expensive to lower
11285 // and it is not possible to combine the store with the extract.
11286 if (!isa<ConstantInt>(Idx))
11289 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11290 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11291 // We can do a store + vector extract on any vector that fits perfectly in a D
11293 if (BitWidth == 64 || BitWidth == 128) {
11300 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11301 AtomicOrdering Ord) const {
11302 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11303 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11304 bool IsAcquire = isAtLeastAcquire(Ord);
11306 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11307 // intrinsic must return {i32, i32} and we have to recombine them into a
11308 // single i64 here.
11309 if (ValTy->getPrimitiveSizeInBits() == 64) {
11310 Intrinsic::ID Int =
11311 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11312 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11314 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11315 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11317 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11318 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11319 if (!Subtarget->isLittle())
11320 std::swap (Lo, Hi);
11321 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11322 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11323 return Builder.CreateOr(
11324 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11327 Type *Tys[] = { Addr->getType() };
11328 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11329 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11331 return Builder.CreateTruncOrBitCast(
11332 Builder.CreateCall(Ldrex, Addr),
11333 cast<PointerType>(Addr->getType())->getElementType());
11336 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11338 AtomicOrdering Ord) const {
11339 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11340 bool IsRelease = isAtLeastRelease(Ord);
11342 // Since the intrinsics must have legal type, the i64 intrinsics take two
11343 // parameters: "i32, i32". We must marshal Val into the appropriate form
11344 // before the call.
11345 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11346 Intrinsic::ID Int =
11347 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11348 Function *Strex = Intrinsic::getDeclaration(M, Int);
11349 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11351 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11352 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11353 if (!Subtarget->isLittle())
11354 std::swap (Lo, Hi);
11355 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11356 return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11359 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11360 Type *Tys[] = { Addr->getType() };
11361 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11363 return Builder.CreateCall(
11364 Strex, {Builder.CreateZExtOrBitCast(
11365 Val, Strex->getFunctionType()->getParamType(0)),
11377 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11378 uint64_t &Members) {
11379 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11380 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11381 uint64_t SubMembers = 0;
11382 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11384 Members += SubMembers;
11386 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11387 uint64_t SubMembers = 0;
11388 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11390 Members += SubMembers * AT->getNumElements();
11391 } else if (Ty->isFloatTy()) {
11392 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11396 } else if (Ty->isDoubleTy()) {
11397 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11401 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11408 return VT->getBitWidth() == 64;
11410 return VT->getBitWidth() == 128;
11412 switch (VT->getBitWidth()) {
11425 return (Members > 0 && Members <= 4);
11428 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11429 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11430 /// passing according to AAPCS rules.
11431 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11432 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11433 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11434 CallingConv::ARM_AAPCS_VFP)
11437 HABaseType Base = HA_UNKNOWN;
11438 uint64_t Members = 0;
11439 bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11440 DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11442 bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11443 return IsHA || IsIntArray;