1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
54 #define DEBUG_TYPE "arm-isel"
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62 cl::desc("Generate calls via indirect call instructions"),
66 ARMInterworking("arm-interworking", cl::Hidden,
67 cl::desc("Enable / disable ARM interworking (for debugging only)"),
71 class ARMCCState : public CCState {
73 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
76 : CCState(CC, isVarArg, MF, locs, C) {
77 assert(((PC == Call) || (PC == Prologue)) &&
78 "ARMCCState users must specify whether their context is call"
79 "or prologue generation.");
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87 ARM::R0, ARM::R1, ARM::R2, ARM::R3
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91 MVT PromotedBitwiseVT) {
92 if (VT != PromotedLdStVT) {
93 setOperationAction(ISD::LOAD, VT, Promote);
94 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
96 setOperationAction(ISD::STORE, VT, Promote);
97 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
100 MVT ElemTy = VT.getVectorElementType();
101 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102 setOperationAction(ISD::SETCC, VT, Custom);
103 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105 if (ElemTy == MVT::i32) {
106 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
111 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
116 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
117 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
118 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
119 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120 setOperationAction(ISD::SELECT, VT, Expand);
121 setOperationAction(ISD::SELECT_CC, VT, Expand);
122 setOperationAction(ISD::VSELECT, VT, Expand);
123 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124 if (VT.isInteger()) {
125 setOperationAction(ISD::SHL, VT, Custom);
126 setOperationAction(ISD::SRA, VT, Custom);
127 setOperationAction(ISD::SRL, VT, Custom);
130 // Promote all bit-wise operations.
131 if (VT.isInteger() && VT != PromotedBitwiseVT) {
132 setOperationAction(ISD::AND, VT, Promote);
133 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::OR, VT, Promote);
135 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
136 setOperationAction(ISD::XOR, VT, Promote);
137 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
140 // Neon does not support vector divide/remainder operations.
141 setOperationAction(ISD::SDIV, VT, Expand);
142 setOperationAction(ISD::UDIV, VT, Expand);
143 setOperationAction(ISD::FDIV, VT, Expand);
144 setOperationAction(ISD::SREM, VT, Expand);
145 setOperationAction(ISD::UREM, VT, Expand);
146 setOperationAction(ISD::FREM, VT, Expand);
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150 addRegisterClass(VT, &ARM::DPRRegClass);
151 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155 addRegisterClass(VT, &ARM::DPairRegClass);
156 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
159 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
160 : TargetLowering(TM) {
161 Subtarget = &TM.getSubtarget<ARMSubtarget>();
162 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
163 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
165 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
167 if (Subtarget->isTargetMachO()) {
168 // Uses VFP for Thumb libfuncs if available.
169 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
170 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
171 // Single-precision floating-point arithmetic.
172 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
173 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
174 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
175 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
177 // Double-precision floating-point arithmetic.
178 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
179 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
180 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
181 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
183 // Single-precision comparisons.
184 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
185 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
186 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
187 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
188 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
189 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
190 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
191 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
193 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
194 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
195 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
196 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
197 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
198 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
202 // Double-precision comparisons.
203 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
204 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
205 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
206 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
207 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
208 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
209 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
210 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
212 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
213 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
214 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
215 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
216 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
217 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
221 // Floating-point to integer conversions.
222 // i64 conversions are done via library routines even when generating VFP
223 // instructions, so use the same ones.
224 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
225 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
226 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
227 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
229 // Conversions between floating types.
230 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
231 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
233 // Integer to floating-point conversions.
234 // i64 conversions are done via library routines even when generating VFP
235 // instructions, so use the same ones.
236 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
237 // e.g., __floatunsidf vs. __floatunssidfvfp.
238 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
239 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
240 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
241 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245 // These libcalls are not available in 32-bit.
246 setLibcallName(RTLIB::SHL_I128, nullptr);
247 setLibcallName(RTLIB::SRL_I128, nullptr);
248 setLibcallName(RTLIB::SRA_I128, nullptr);
250 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
251 !Subtarget->isTargetWindows()) {
252 static const struct {
253 const RTLIB::Libcall Op;
254 const char * const Name;
255 const CallingConv::ID CC;
256 const ISD::CondCode Cond;
258 // Double-precision floating-point arithmetic helper functions
259 // RTABI chapter 4.1.2, Table 2
260 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
262 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
263 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
265 // Double-precision floating-point comparison helper functions
266 // RTABI chapter 4.1.2, Table 3
267 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
268 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
269 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
270 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
271 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
272 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
273 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
274 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 // Single-precision floating-point arithmetic helper functions
277 // RTABI chapter 4.1.2, Table 4
278 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
280 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
281 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
283 // Single-precision floating-point comparison helper functions
284 // RTABI chapter 4.1.2, Table 5
285 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
286 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
287 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
288 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
289 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
290 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
291 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
292 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 // Floating-point to integer conversions.
295 // RTABI chapter 4.1.2, Table 6
296 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
302 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
303 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 // Conversions between floating types.
306 // RTABI chapter 4.1.2, Table 7
307 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 // Integer to floating-point conversions.
312 // RTABI chapter 4.1.2, Table 8
313 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 // Long long helper functions
323 // RTABI chapter 4.2, Table 9
324 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329 // Integer division functions
330 // RTABI chapter 4.3.1
331 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 // RTABI chapter 4.3.4
342 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 for (const auto &LC : LibraryCalls) {
348 setLibcallName(LC.Op, LC.Name);
349 setLibcallCallingConv(LC.Op, LC.CC);
350 if (LC.Cond != ISD::SETCC_INVALID)
351 setCmpLibcallCC(LC.Op, LC.Cond);
355 if (Subtarget->isTargetWindows()) {
356 static const struct {
357 const RTLIB::Libcall Op;
358 const char * const Name;
359 const CallingConv::ID CC;
361 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
362 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
363 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
364 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
365 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
366 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
367 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
371 for (const auto &LC : LibraryCalls) {
372 setLibcallName(LC.Op, LC.Name);
373 setLibcallCallingConv(LC.Op, LC.CC);
377 // Use divmod compiler-rt calls for iOS 5.0 and later.
378 if (Subtarget->getTargetTriple().isiOS() &&
379 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
380 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
381 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384 // The half <-> float conversion functions are always soft-float, but are
385 // needed for some targets which use a hard-float calling convention by
387 if (Subtarget->isAAPCS_ABI()) {
388 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
393 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
394 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397 if (Subtarget->isThumb1Only())
398 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
400 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
401 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
402 !Subtarget->isThumb1Only()) {
403 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
404 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407 for (MVT VT : MVT::vector_valuetypes()) {
408 for (MVT InnerVT : MVT::vector_valuetypes()) {
409 setTruncStoreAction(VT, InnerVT, Expand);
410 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
411 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
412 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415 setOperationAction(ISD::MULHS, VT, Expand);
416 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
417 setOperationAction(ISD::MULHU, VT, Expand);
418 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
420 setOperationAction(ISD::BSWAP, VT, Expand);
423 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
426 if (Subtarget->hasNEON()) {
427 addDRTypeForNEON(MVT::v2f32);
428 addDRTypeForNEON(MVT::v8i8);
429 addDRTypeForNEON(MVT::v4i16);
430 addDRTypeForNEON(MVT::v2i32);
431 addDRTypeForNEON(MVT::v1i64);
433 addQRTypeForNEON(MVT::v4f32);
434 addQRTypeForNEON(MVT::v2f64);
435 addQRTypeForNEON(MVT::v16i8);
436 addQRTypeForNEON(MVT::v8i16);
437 addQRTypeForNEON(MVT::v4i32);
438 addQRTypeForNEON(MVT::v2i64);
440 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
441 // neither Neon nor VFP support any arithmetic operations on it.
442 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
443 // supported for v4f32.
444 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
445 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
446 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
447 // FIXME: Code duplication: FDIV and FREM are expanded always, see
448 // ARMTargetLowering::addTypeForNEON method for details.
449 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
450 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
451 // FIXME: Create unittest.
452 // In another words, find a way when "copysign" appears in DAG with vector
454 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
455 // FIXME: Code duplication: SETCC has custom operation action, see
456 // ARMTargetLowering::addTypeForNEON method for details.
457 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
458 // FIXME: Create unittest for FNEG and for FABS.
459 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
460 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
461 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
462 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
463 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
464 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
465 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
466 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
467 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
468 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
469 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
470 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
471 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
472 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
473 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
474 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
475 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
476 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
477 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
479 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
480 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
481 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
482 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
483 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
484 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
485 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
486 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
487 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
488 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
489 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
490 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
491 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
493 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
495 // Mark v2f32 intrinsics.
496 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
497 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
498 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
499 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
500 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
501 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
502 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
503 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
504 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
505 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
506 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
507 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
508 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
509 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
510 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
512 // Neon does not support some operations on v1i64 and v2i64 types.
513 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
514 // Custom handling for some quad-vector types to detect VMULL.
515 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
517 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
518 // Custom handling for some vector types to avoid expensive expansions
519 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
520 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
521 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
522 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
523 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
524 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
525 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
526 // a destination type that is wider than the source, and nor does
527 // it have a FP_TO_[SU]INT instruction with a narrower destination than
529 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
530 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
531 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
534 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
535 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
537 // NEON does not have single instruction CTPOP for vectors with element
538 // types wider than 8-bits. However, custom lowering can leverage the
539 // v8i8/v16i8 vcnt instruction.
540 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
541 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
542 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
543 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
545 // NEON only has FMA instructions as of VFP4.
546 if (!Subtarget->hasVFP4()) {
547 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
548 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
551 setTargetDAGCombine(ISD::INTRINSIC_VOID);
552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
554 setTargetDAGCombine(ISD::SHL);
555 setTargetDAGCombine(ISD::SRL);
556 setTargetDAGCombine(ISD::SRA);
557 setTargetDAGCombine(ISD::SIGN_EXTEND);
558 setTargetDAGCombine(ISD::ZERO_EXTEND);
559 setTargetDAGCombine(ISD::ANY_EXTEND);
560 setTargetDAGCombine(ISD::SELECT_CC);
561 setTargetDAGCombine(ISD::BUILD_VECTOR);
562 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
563 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
564 setTargetDAGCombine(ISD::STORE);
565 setTargetDAGCombine(ISD::FP_TO_SINT);
566 setTargetDAGCombine(ISD::FP_TO_UINT);
567 setTargetDAGCombine(ISD::FDIV);
569 // It is legal to extload from v4i8 to v4i16 or v4i32.
570 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
571 MVT::v4i16, MVT::v2i16,
573 for (unsigned i = 0; i < 6; ++i) {
574 for (MVT VT : MVT::integer_vector_valuetypes()) {
575 setLoadExtAction(ISD::EXTLOAD, VT, Tys[i], Legal);
576 setLoadExtAction(ISD::ZEXTLOAD, VT, Tys[i], Legal);
577 setLoadExtAction(ISD::SEXTLOAD, VT, Tys[i], Legal);
582 // ARM and Thumb2 support UMLAL/SMLAL.
583 if (!Subtarget->isThumb1Only())
584 setTargetDAGCombine(ISD::ADDC);
586 if (Subtarget->isFPOnlySP()) {
587 // When targetting a floating-point unit with only single-precision
588 // operations, f64 is legal for the few double-precision instructions which
589 // are present However, no double-precision operations other than moves,
590 // loads and stores are provided by the hardware.
591 setOperationAction(ISD::FADD, MVT::f64, Expand);
592 setOperationAction(ISD::FSUB, MVT::f64, Expand);
593 setOperationAction(ISD::FMUL, MVT::f64, Expand);
594 setOperationAction(ISD::FMA, MVT::f64, Expand);
595 setOperationAction(ISD::FDIV, MVT::f64, Expand);
596 setOperationAction(ISD::FREM, MVT::f64, Expand);
597 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
598 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
599 setOperationAction(ISD::FNEG, MVT::f64, Expand);
600 setOperationAction(ISD::FABS, MVT::f64, Expand);
601 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
602 setOperationAction(ISD::FSIN, MVT::f64, Expand);
603 setOperationAction(ISD::FCOS, MVT::f64, Expand);
604 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
605 setOperationAction(ISD::FPOW, MVT::f64, Expand);
606 setOperationAction(ISD::FLOG, MVT::f64, Expand);
607 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
608 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
609 setOperationAction(ISD::FEXP, MVT::f64, Expand);
610 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
611 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
612 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
613 setOperationAction(ISD::FRINT, MVT::f64, Expand);
614 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
615 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
616 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
617 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
620 computeRegisterProperties();
622 // ARM does not have floating-point extending loads.
623 for (MVT VT : MVT::fp_valuetypes()) {
624 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
625 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
628 // ... or truncating stores
629 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
630 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
631 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
633 // ARM does not have i1 sign extending load.
634 for (MVT VT : MVT::integer_valuetypes())
635 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
637 // ARM supports all 4 flavors of integer indexed load / store.
638 if (!Subtarget->isThumb1Only()) {
639 for (unsigned im = (unsigned)ISD::PRE_INC;
640 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
641 setIndexedLoadAction(im, MVT::i1, Legal);
642 setIndexedLoadAction(im, MVT::i8, Legal);
643 setIndexedLoadAction(im, MVT::i16, Legal);
644 setIndexedLoadAction(im, MVT::i32, Legal);
645 setIndexedStoreAction(im, MVT::i1, Legal);
646 setIndexedStoreAction(im, MVT::i8, Legal);
647 setIndexedStoreAction(im, MVT::i16, Legal);
648 setIndexedStoreAction(im, MVT::i32, Legal);
652 setOperationAction(ISD::SADDO, MVT::i32, Custom);
653 setOperationAction(ISD::UADDO, MVT::i32, Custom);
654 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
655 setOperationAction(ISD::USUBO, MVT::i32, Custom);
657 // i64 operation support.
658 setOperationAction(ISD::MUL, MVT::i64, Expand);
659 setOperationAction(ISD::MULHU, MVT::i32, Expand);
660 if (Subtarget->isThumb1Only()) {
661 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
662 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
664 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
665 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
666 setOperationAction(ISD::MULHS, MVT::i32, Expand);
668 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
669 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
670 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
671 setOperationAction(ISD::SRL, MVT::i64, Custom);
672 setOperationAction(ISD::SRA, MVT::i64, Custom);
674 if (!Subtarget->isThumb1Only()) {
675 // FIXME: We should do this for Thumb1 as well.
676 setOperationAction(ISD::ADDC, MVT::i32, Custom);
677 setOperationAction(ISD::ADDE, MVT::i32, Custom);
678 setOperationAction(ISD::SUBC, MVT::i32, Custom);
679 setOperationAction(ISD::SUBE, MVT::i32, Custom);
682 // ARM does not have ROTL.
683 setOperationAction(ISD::ROTL, MVT::i32, Expand);
684 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
685 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
686 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
687 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
689 // These just redirect to CTTZ and CTLZ on ARM.
690 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
691 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
693 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
695 // Only ARMv6 has BSWAP.
696 if (!Subtarget->hasV6Ops())
697 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
699 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
700 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
701 // These are expanded into libcalls if the cpu doesn't have HW divider.
702 setOperationAction(ISD::SDIV, MVT::i32, Expand);
703 setOperationAction(ISD::UDIV, MVT::i32, Expand);
706 // FIXME: Also set divmod for SREM on EABI
707 setOperationAction(ISD::SREM, MVT::i32, Expand);
708 setOperationAction(ISD::UREM, MVT::i32, Expand);
709 // Register based DivRem for AEABI (RTABI 4.2)
710 if (Subtarget->isTargetAEABI()) {
711 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
712 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
713 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
714 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
715 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
716 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
717 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
718 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
720 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
721 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
722 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
723 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
724 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
725 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
729 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
730 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
732 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
733 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
736 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
737 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
738 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
739 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
740 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
742 setOperationAction(ISD::TRAP, MVT::Other, Legal);
744 // Use the default implementation.
745 setOperationAction(ISD::VASTART, MVT::Other, Custom);
746 setOperationAction(ISD::VAARG, MVT::Other, Expand);
747 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
748 setOperationAction(ISD::VAEND, MVT::Other, Expand);
749 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
750 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
752 if (!Subtarget->isTargetMachO()) {
753 // Non-MachO platforms may return values in these registers via the
754 // personality function.
755 setExceptionPointerRegister(ARM::R0);
756 setExceptionSelectorRegister(ARM::R1);
759 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
760 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
762 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
764 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
765 // the default expansion. If we are targeting a single threaded system,
766 // then set them all for expand so we can lower them later into their
768 if (TM.Options.ThreadModel == ThreadModel::Single)
769 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
770 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
771 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
772 // to ldrex/strex loops already.
773 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
775 // On v8, we have particularly efficient implementations of atomic fences
776 // if they can be combined with nearby atomic loads and stores.
777 if (!Subtarget->hasV8Ops()) {
778 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
779 setInsertFencesForAtomic(true);
782 // If there's anything we can use as a barrier, go through custom lowering
784 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
785 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
787 // Set them all for expansion, which will force libcalls.
788 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
789 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
800 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
801 // Unordered/Monotonic case.
802 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
803 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
806 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
808 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
809 if (!Subtarget->hasV6Ops()) {
810 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
811 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
813 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
815 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
816 !Subtarget->isThumb1Only()) {
817 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
818 // iff target supports vfp2.
819 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
820 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
823 // We want to custom lower some of our intrinsics.
824 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
825 if (Subtarget->isTargetDarwin()) {
826 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
827 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
828 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
831 setOperationAction(ISD::SETCC, MVT::i32, Expand);
832 setOperationAction(ISD::SETCC, MVT::f32, Expand);
833 setOperationAction(ISD::SETCC, MVT::f64, Expand);
834 setOperationAction(ISD::SELECT, MVT::i32, Custom);
835 setOperationAction(ISD::SELECT, MVT::f32, Custom);
836 setOperationAction(ISD::SELECT, MVT::f64, Custom);
837 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
838 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
839 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
841 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
842 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
843 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
844 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
845 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
847 // We don't support sin/cos/fmod/copysign/pow
848 setOperationAction(ISD::FSIN, MVT::f64, Expand);
849 setOperationAction(ISD::FSIN, MVT::f32, Expand);
850 setOperationAction(ISD::FCOS, MVT::f32, Expand);
851 setOperationAction(ISD::FCOS, MVT::f64, Expand);
852 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
853 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
854 setOperationAction(ISD::FREM, MVT::f64, Expand);
855 setOperationAction(ISD::FREM, MVT::f32, Expand);
856 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
857 !Subtarget->isThumb1Only()) {
858 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
859 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
861 setOperationAction(ISD::FPOW, MVT::f64, Expand);
862 setOperationAction(ISD::FPOW, MVT::f32, Expand);
864 if (!Subtarget->hasVFP4()) {
865 setOperationAction(ISD::FMA, MVT::f64, Expand);
866 setOperationAction(ISD::FMA, MVT::f32, Expand);
869 // Various VFP goodness
870 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
871 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
872 if (Subtarget->hasVFP2()) {
873 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
874 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
875 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
876 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
879 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
880 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
881 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
882 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
885 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
886 if (!Subtarget->hasFP16()) {
887 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
888 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
892 // Combine sin / cos into one node or libcall if possible.
893 if (Subtarget->hasSinCos()) {
894 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
895 setLibcallName(RTLIB::SINCOS_F64, "sincos");
896 if (Subtarget->getTargetTriple().isiOS()) {
897 // For iOS, we don't want to the normal expansion of a libcall to
898 // sincos. We want to issue a libcall to __sincos_stret.
899 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
900 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
904 // FP-ARMv8 implements a lot of rounding-like FP operations.
905 if (Subtarget->hasFPARMv8()) {
906 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
907 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
908 setOperationAction(ISD::FROUND, MVT::f32, Legal);
909 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
910 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
911 setOperationAction(ISD::FRINT, MVT::f32, Legal);
912 if (!Subtarget->isFPOnlySP()) {
913 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
914 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
915 setOperationAction(ISD::FROUND, MVT::f64, Legal);
916 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
917 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
918 setOperationAction(ISD::FRINT, MVT::f64, Legal);
921 // We have target-specific dag combine patterns for the following nodes:
922 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
923 setTargetDAGCombine(ISD::ADD);
924 setTargetDAGCombine(ISD::SUB);
925 setTargetDAGCombine(ISD::MUL);
926 setTargetDAGCombine(ISD::AND);
927 setTargetDAGCombine(ISD::OR);
928 setTargetDAGCombine(ISD::XOR);
930 if (Subtarget->hasV6Ops())
931 setTargetDAGCombine(ISD::SRL);
933 setStackPointerRegisterToSaveRestore(ARM::SP);
935 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936 !Subtarget->hasVFP2())
937 setSchedulingPreference(Sched::RegPressure);
939 setSchedulingPreference(Sched::Hybrid);
941 //// temporary - rewrite interface to use type
942 MaxStoresPerMemset = 8;
943 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
949 // On ARM arguments smaller than 4 bytes are extended, so all arguments
950 // are at least 4 bytes aligned.
951 setMinStackArgumentAlignment(4);
953 // Prefer likely predicted branches to selects on out-of-order cores.
954 PredictableSelectIsExpensive = Subtarget->isLikeA9();
956 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971 const TargetRegisterClass *RRC = nullptr;
973 switch (VT.SimpleTy) {
975 return TargetLowering::findRepresentativeClass(VT);
976 // Use DPR as representative register class for all floating point
977 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978 // the cost is 1 for both f32 and f64.
979 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981 RRC = &ARM::DPRRegClass;
982 // When NEON is used for SP, only half of the register file is available
983 // because operations that define both SP and DP results will be constrained
984 // to the VFP2 class (D0-D15). We currently model this constraint prior to
985 // coalescing by double-counting the SP regs. See the FIXME above.
986 if (Subtarget->useNEONForSinglePrecisionFP())
989 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990 case MVT::v4f32: case MVT::v2f64:
991 RRC = &ARM::DPRRegClass;
995 RRC = &ARM::DPRRegClass;
999 RRC = &ARM::DPRRegClass;
1003 return std::make_pair(RRC, Cost);
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1008 default: return nullptr;
1009 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1010 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1011 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1012 case ARMISD::CALL: return "ARMISD::CALL";
1013 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1014 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1015 case ARMISD::tCALL: return "ARMISD::tCALL";
1016 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1017 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1018 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1019 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1020 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1021 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1022 case ARMISD::CMP: return "ARMISD::CMP";
1023 case ARMISD::CMN: return "ARMISD::CMN";
1024 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1025 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1026 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1027 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1028 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1030 case ARMISD::CMOV: return "ARMISD::CMOV";
1032 case ARMISD::RBIT: return "ARMISD::RBIT";
1034 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1035 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1036 case ARMISD::SITOF: return "ARMISD::SITOF";
1037 case ARMISD::UITOF: return "ARMISD::UITOF";
1039 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1040 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1041 case ARMISD::RRX: return "ARMISD::RRX";
1043 case ARMISD::ADDC: return "ARMISD::ADDC";
1044 case ARMISD::ADDE: return "ARMISD::ADDE";
1045 case ARMISD::SUBC: return "ARMISD::SUBC";
1046 case ARMISD::SUBE: return "ARMISD::SUBE";
1048 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1049 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1051 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1054 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1056 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1058 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1060 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1062 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1064 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1066 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1067 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1068 case ARMISD::VCGE: return "ARMISD::VCGE";
1069 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1070 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1071 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1072 case ARMISD::VCGT: return "ARMISD::VCGT";
1073 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1074 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1075 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1076 case ARMISD::VTST: return "ARMISD::VTST";
1078 case ARMISD::VSHL: return "ARMISD::VSHL";
1079 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1080 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1081 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1082 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1083 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1084 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1085 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1086 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1087 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1088 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1089 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1090 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1091 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1092 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1093 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1094 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1095 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1096 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1097 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1098 case ARMISD::VDUP: return "ARMISD::VDUP";
1099 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1100 case ARMISD::VEXT: return "ARMISD::VEXT";
1101 case ARMISD::VREV64: return "ARMISD::VREV64";
1102 case ARMISD::VREV32: return "ARMISD::VREV32";
1103 case ARMISD::VREV16: return "ARMISD::VREV16";
1104 case ARMISD::VZIP: return "ARMISD::VZIP";
1105 case ARMISD::VUZP: return "ARMISD::VUZP";
1106 case ARMISD::VTRN: return "ARMISD::VTRN";
1107 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1108 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1109 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1110 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1111 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1112 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1113 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1114 case ARMISD::FMAX: return "ARMISD::FMAX";
1115 case ARMISD::FMIN: return "ARMISD::FMIN";
1116 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1117 case ARMISD::VMINNM: return "ARMISD::VMIN";
1118 case ARMISD::BFI: return "ARMISD::BFI";
1119 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1120 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1121 case ARMISD::VBSL: return "ARMISD::VBSL";
1122 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1123 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1124 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1125 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1126 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1127 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1128 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1129 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1130 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1131 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1132 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1133 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1134 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1135 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1136 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1137 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1138 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1139 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1140 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1141 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146 if (!VT.isVector()) return getPointerTy();
1147 return VT.changeVectorElementTypeToInteger();
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155 // load / store 4 to 8 consecutive D registers.
1156 if (Subtarget->hasNEON()) {
1157 if (VT == MVT::v4i64)
1158 return &ARM::QQPRRegClass;
1159 if (VT == MVT::v8i64)
1160 return &ARM::QQQQPRRegClass;
1162 return TargetLowering::getRegClassFor(VT);
1165 // Create a fast isel object.
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168 const TargetLibraryInfo *libInfo) const {
1169 return ARM::createFastISel(funcInfo, libInfo);
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175 return (Subtarget->isThumb1Only() ? 127 : 4095);
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179 unsigned NumVals = N->getNumValues();
1181 return Sched::RegPressure;
1183 for (unsigned i = 0; i != NumVals; ++i) {
1184 EVT VT = N->getValueType(i);
1185 if (VT == MVT::Glue || VT == MVT::Other)
1187 if (VT.isFloatingPoint() || VT.isVector())
1191 if (!N->isMachineOpcode())
1192 return Sched::RegPressure;
1194 // Load are scheduled for latency even if there instruction itinerary
1195 // is not available.
1196 const TargetInstrInfo *TII =
1197 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1200 if (MCID.getNumDefs() == 0)
1201 return Sched::RegPressure;
1202 if (!Itins->isEmpty() &&
1203 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206 return Sched::RegPressure;
1209 //===----------------------------------------------------------------------===//
1211 //===----------------------------------------------------------------------===//
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1216 default: llvm_unreachable("Unknown condition code!");
1217 case ISD::SETNE: return ARMCC::NE;
1218 case ISD::SETEQ: return ARMCC::EQ;
1219 case ISD::SETGT: return ARMCC::GT;
1220 case ISD::SETGE: return ARMCC::GE;
1221 case ISD::SETLT: return ARMCC::LT;
1222 case ISD::SETLE: return ARMCC::LE;
1223 case ISD::SETUGT: return ARMCC::HI;
1224 case ISD::SETUGE: return ARMCC::HS;
1225 case ISD::SETULT: return ARMCC::LO;
1226 case ISD::SETULE: return ARMCC::LS;
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232 ARMCC::CondCodes &CondCode2) {
1233 CondCode2 = ARMCC::AL;
1235 default: llvm_unreachable("Unknown FP condition!");
1237 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1239 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1241 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245 case ISD::SETO: CondCode = ARMCC::VC; break;
1246 case ISD::SETUO: CondCode = ARMCC::VS; break;
1247 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1251 case ISD::SETULT: CondCode = ARMCC::LT; break;
1253 case ISD::SETULE: CondCode = ARMCC::LE; break;
1255 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259 //===----------------------------------------------------------------------===//
1260 // Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1263 #include "ARMGenCallingConv.inc"
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270 bool isVarArg) const {
1273 llvm_unreachable("Unsupported calling convention");
1274 case CallingConv::ARM_AAPCS:
1275 case CallingConv::ARM_APCS:
1276 case CallingConv::GHC:
1278 case CallingConv::ARM_AAPCS_VFP:
1279 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280 case CallingConv::C:
1281 if (!Subtarget->isAAPCS_ABI())
1282 return CallingConv::ARM_APCS;
1283 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1286 return CallingConv::ARM_AAPCS_VFP;
1288 return CallingConv::ARM_AAPCS;
1289 case CallingConv::Fast:
1290 if (!Subtarget->isAAPCS_ABI()) {
1291 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292 return CallingConv::Fast;
1293 return CallingConv::ARM_APCS;
1294 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295 return CallingConv::ARM_AAPCS_VFP;
1297 return CallingConv::ARM_AAPCS;
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1305 bool isVarArg) const {
1306 switch (getEffectiveCallingConv(CC, isVarArg)) {
1308 llvm_unreachable("Unsupported calling convention");
1309 case CallingConv::ARM_APCS:
1310 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311 case CallingConv::ARM_AAPCS:
1312 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313 case CallingConv::ARM_AAPCS_VFP:
1314 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315 case CallingConv::Fast:
1316 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317 case CallingConv::GHC:
1318 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326 CallingConv::ID CallConv, bool isVarArg,
1327 const SmallVectorImpl<ISD::InputArg> &Ins,
1328 SDLoc dl, SelectionDAG &DAG,
1329 SmallVectorImpl<SDValue> &InVals,
1330 bool isThisReturn, SDValue ThisVal) const {
1332 // Assign locations to each value returned by this call.
1333 SmallVector<CCValAssign, 16> RVLocs;
1334 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335 *DAG.getContext(), Call);
1336 CCInfo.AnalyzeCallResult(Ins,
1337 CCAssignFnForNode(CallConv, /* Return*/ true,
1340 // Copy all of the result registers out of their specified physreg.
1341 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342 CCValAssign VA = RVLocs[i];
1344 // Pass 'this' value directly from the argument to return value, to avoid
1345 // reg unit interference
1346 if (i == 0 && isThisReturn) {
1347 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348 "unexpected return calling convention register assignment");
1349 InVals.push_back(ThisVal);
1354 if (VA.needsCustom()) {
1355 // Handle f64 or half of a v2f64.
1356 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1358 Chain = Lo.getValue(1);
1359 InFlag = Lo.getValue(2);
1360 VA = RVLocs[++i]; // skip ahead to next loc
1361 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1363 Chain = Hi.getValue(1);
1364 InFlag = Hi.getValue(2);
1365 if (!Subtarget->isLittle())
1367 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1369 if (VA.getLocVT() == MVT::v2f64) {
1370 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372 DAG.getConstant(0, MVT::i32));
1374 VA = RVLocs[++i]; // skip ahead to next loc
1375 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376 Chain = Lo.getValue(1);
1377 InFlag = Lo.getValue(2);
1378 VA = RVLocs[++i]; // skip ahead to next loc
1379 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380 Chain = Hi.getValue(1);
1381 InFlag = Hi.getValue(2);
1382 if (!Subtarget->isLittle())
1384 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386 DAG.getConstant(1, MVT::i32));
1389 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1391 Chain = Val.getValue(1);
1392 InFlag = Val.getValue(2);
1395 switch (VA.getLocInfo()) {
1396 default: llvm_unreachable("Unknown loc info!");
1397 case CCValAssign::Full: break;
1398 case CCValAssign::BCvt:
1399 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1403 InVals.push_back(Val);
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412 SDValue StackPtr, SDValue Arg,
1413 SDLoc dl, SelectionDAG &DAG,
1414 const CCValAssign &VA,
1415 ISD::ArgFlagsTy Flags) const {
1416 unsigned LocMemOffset = VA.getLocMemOffset();
1417 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419 return DAG.getStore(Chain, dl, Arg, PtrOff,
1420 MachinePointerInfo::getStack(LocMemOffset),
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425 SDValue Chain, SDValue &Arg,
1426 RegsToPassVector &RegsToPass,
1427 CCValAssign &VA, CCValAssign &NextVA,
1429 SmallVectorImpl<SDValue> &MemOpChains,
1430 ISD::ArgFlagsTy Flags) const {
1432 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434 unsigned id = Subtarget->isLittle() ? 0 : 1;
1435 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1437 if (NextVA.isRegLoc())
1438 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1440 assert(NextVA.isMemLoc());
1441 if (!StackPtr.getNode())
1442 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1444 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455 SmallVectorImpl<SDValue> &InVals) const {
1456 SelectionDAG &DAG = CLI.DAG;
1458 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1460 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1461 SDValue Chain = CLI.Chain;
1462 SDValue Callee = CLI.Callee;
1463 bool &isTailCall = CLI.IsTailCall;
1464 CallingConv::ID CallConv = CLI.CallConv;
1465 bool doesNotRet = CLI.DoesNotReturn;
1466 bool isVarArg = CLI.IsVarArg;
1468 MachineFunction &MF = DAG.getMachineFunction();
1469 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470 bool isThisReturn = false;
1471 bool isSibCall = false;
1473 // Disable tail calls if they're not supported.
1474 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1478 // Check if it's really possible to do a tail call.
1479 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481 Outs, OutVals, Ins, DAG);
1482 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483 report_fatal_error("failed to perform tail call elimination on a call "
1484 "site marked musttail");
1485 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486 // detected sibcalls.
1493 // Analyze operands of the call, assigning locations to each operand.
1494 SmallVector<CCValAssign, 16> ArgLocs;
1495 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496 *DAG.getContext(), Call);
1497 CCInfo.AnalyzeCallOperands(Outs,
1498 CCAssignFnForNode(CallConv, /* Return*/ false,
1501 // Get a count of how many bytes are to be pushed on the stack.
1502 unsigned NumBytes = CCInfo.getNextStackOffset();
1504 // For tail calls, memory operands are available in our caller's stack.
1508 // Adjust the stack pointer for the new arguments...
1509 // These operations are automatically eliminated by the prolog/epilog pass
1511 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1514 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1516 RegsToPassVector RegsToPass;
1517 SmallVector<SDValue, 8> MemOpChains;
1519 // Walk the register/memloc assignments, inserting copies/loads. In the case
1520 // of tail call optimization, arguments are handled later.
1521 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1523 ++i, ++realArgIdx) {
1524 CCValAssign &VA = ArgLocs[i];
1525 SDValue Arg = OutVals[realArgIdx];
1526 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527 bool isByVal = Flags.isByVal();
1529 // Promote the value if needed.
1530 switch (VA.getLocInfo()) {
1531 default: llvm_unreachable("Unknown loc info!");
1532 case CCValAssign::Full: break;
1533 case CCValAssign::SExt:
1534 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1536 case CCValAssign::ZExt:
1537 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1539 case CCValAssign::AExt:
1540 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1542 case CCValAssign::BCvt:
1543 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1547 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548 if (VA.needsCustom()) {
1549 if (VA.getLocVT() == MVT::v2f64) {
1550 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551 DAG.getConstant(0, MVT::i32));
1552 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553 DAG.getConstant(1, MVT::i32));
1555 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1558 VA = ArgLocs[++i]; // skip ahead to next loc
1559 if (VA.isRegLoc()) {
1560 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1563 assert(VA.isMemLoc());
1565 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566 dl, DAG, VA, Flags));
1569 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570 StackPtr, MemOpChains, Flags);
1572 } else if (VA.isRegLoc()) {
1573 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574 assert(VA.getLocVT() == MVT::i32 &&
1575 "unexpected calling convention register assignment");
1576 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577 "unexpected use of 'returned'");
1578 isThisReturn = true;
1580 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581 } else if (isByVal) {
1582 assert(VA.isMemLoc());
1583 unsigned offset = 0;
1585 // True if this byval aggregate will be split between registers
1587 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588 unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1590 if (CurByValIdx < ByValArgsCount) {
1592 unsigned RegBegin, RegEnd;
1593 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1595 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1597 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601 MachinePointerInfo(),
1602 false, false, false,
1603 DAG.InferPtrAlignment(AddArg));
1604 MemOpChains.push_back(Load.getValue(1));
1605 RegsToPass.push_back(std::make_pair(j, Load));
1608 // If parameter size outsides register area, "offset" value
1609 // helps us to calculate stack slot for remained part properly.
1610 offset = RegEnd - RegBegin;
1612 CCInfo.nextInRegsParam();
1615 if (Flags.getByValSize() > 4*offset) {
1616 unsigned LocMemOffset = VA.getLocMemOffset();
1617 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1620 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1624 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1626 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1631 } else if (!isSibCall) {
1632 assert(VA.isMemLoc());
1634 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635 dl, DAG, VA, Flags));
1639 if (!MemOpChains.empty())
1640 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1642 // Build a sequence of copy-to-reg nodes chained together with token chain
1643 // and flag operands which copy the outgoing args into the appropriate regs.
1645 // Tail call byval lowering might overwrite argument registers so in case of
1646 // tail call optimization the copies to registers are lowered later.
1648 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650 RegsToPass[i].second, InFlag);
1651 InFlag = Chain.getValue(1);
1654 // For tail calls lower the arguments to the 'real' stack slot.
1656 // Force all the incoming stack arguments to be loaded from the stack
1657 // before any new outgoing arguments are stored to the stack, because the
1658 // outgoing stack slots may alias the incoming argument stack slots, and
1659 // the alias isn't otherwise explicit. This is slightly more conservative
1660 // than necessary, because it means that each store effectively depends
1661 // on every argument instead of just those arguments it would clobber.
1663 // Do not flag preceding copytoreg stuff together with the following stuff.
1665 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667 RegsToPass[i].second, InFlag);
1668 InFlag = Chain.getValue(1);
1673 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675 // node so that legalize doesn't hack it.
1676 bool isDirect = false;
1677 bool isARMFunc = false;
1678 bool isLocalARMFunc = false;
1679 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1681 if (EnableARMLongCalls) {
1682 assert((Subtarget->isTargetWindows() ||
1683 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684 "long-calls with non-static relocation model!");
1685 // Handle a global address or an external symbol. If it's not one of
1686 // those, the target's already in a register, so we don't need to do
1688 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689 const GlobalValue *GV = G->getGlobal();
1690 // Create a constant pool entry for the callee address
1691 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692 ARMConstantPoolValue *CPV =
1693 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1695 // Get the address of the callee into a register
1696 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698 Callee = DAG.getLoad(getPointerTy(), dl,
1699 DAG.getEntryNode(), CPAddr,
1700 MachinePointerInfo::getConstantPool(),
1701 false, false, false, 0);
1702 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703 const char *Sym = S->getSymbol();
1705 // Create a constant pool entry for the callee address
1706 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707 ARMConstantPoolValue *CPV =
1708 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709 ARMPCLabelIndex, 0);
1710 // Get the address of the callee into a register
1711 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713 Callee = DAG.getLoad(getPointerTy(), dl,
1714 DAG.getEntryNode(), CPAddr,
1715 MachinePointerInfo::getConstantPool(),
1716 false, false, false, 0);
1718 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719 const GlobalValue *GV = G->getGlobal();
1721 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723 getTargetMachine().getRelocationModel() != Reloc::Static;
1724 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725 // ARM call to a local ARM function is predicable.
1726 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727 // tBX takes a register source operand.
1728 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732 0, ARMII::MO_NONLAZY));
1733 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734 MachinePointerInfo::getGOT(), false, false, true, 0);
1735 } else if (Subtarget->isTargetCOFF()) {
1736 assert(Subtarget->isTargetWindows() &&
1737 "Windows is the only supported COFF target");
1738 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739 ? ARMII::MO_DLLIMPORT
1740 : ARMII::MO_NO_FLAG;
1741 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1743 if (GV->hasDLLImportStorageClass())
1744 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746 Callee), MachinePointerInfo::getGOT(),
1747 false, false, false, 0);
1749 // On ELF targets for PIC code, direct calls should go through the PLT
1750 unsigned OpFlags = 0;
1751 if (Subtarget->isTargetELF() &&
1752 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753 OpFlags = ARMII::MO_PLT;
1754 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1756 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1758 bool isStub = Subtarget->isTargetMachO() &&
1759 getTargetMachine().getRelocationModel() != Reloc::Static;
1760 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761 // tBX takes a register source operand.
1762 const char *Sym = S->getSymbol();
1763 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765 ARMConstantPoolValue *CPV =
1766 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767 ARMPCLabelIndex, 4);
1768 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770 Callee = DAG.getLoad(getPointerTy(), dl,
1771 DAG.getEntryNode(), CPAddr,
1772 MachinePointerInfo::getConstantPool(),
1773 false, false, false, 0);
1774 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776 getPointerTy(), Callee, PICLabel);
1778 unsigned OpFlags = 0;
1779 // On ELF targets for PIC code, direct calls should go through the PLT
1780 if (Subtarget->isTargetELF() &&
1781 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782 OpFlags = ARMII::MO_PLT;
1783 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1787 // FIXME: handle tail calls differently.
1789 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1790 AttributeSet::FunctionIndex, Attribute::MinSize);
1791 if (Subtarget->isThumb()) {
1792 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1793 CallOpc = ARMISD::CALL_NOLINK;
1795 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1797 if (!isDirect && !Subtarget->hasV5TOps())
1798 CallOpc = ARMISD::CALL_NOLINK;
1799 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1800 // Emit regular call when code size is the priority
1802 // "mov lr, pc; b _foo" to avoid confusing the RSP
1803 CallOpc = ARMISD::CALL_NOLINK;
1805 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1808 std::vector<SDValue> Ops;
1809 Ops.push_back(Chain);
1810 Ops.push_back(Callee);
1812 // Add argument registers to the end of the list so that they are known live
1814 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816 RegsToPass[i].second.getValueType()));
1818 // Add a register mask operand representing the call-preserved registers.
1820 const uint32_t *Mask;
1821 const TargetRegisterInfo *TRI =
1822 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1823 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1825 // For 'this' returns, use the R0-preserving mask if applicable
1826 Mask = ARI->getThisReturnPreservedMask(CallConv);
1828 // Set isThisReturn to false if the calling convention is not one that
1829 // allows 'returned' to be modeled in this way, so LowerCallResult does
1830 // not try to pass 'this' straight through
1831 isThisReturn = false;
1832 Mask = ARI->getCallPreservedMask(CallConv);
1835 Mask = ARI->getCallPreservedMask(CallConv);
1837 assert(Mask && "Missing call preserved mask for calling convention");
1838 Ops.push_back(DAG.getRegisterMask(Mask));
1841 if (InFlag.getNode())
1842 Ops.push_back(InFlag);
1844 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1846 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1848 // Returns a chain and a flag for retval copy to use.
1849 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850 InFlag = Chain.getValue(1);
1852 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853 DAG.getIntPtrConstant(0, true), InFlag, dl);
1855 InFlag = Chain.getValue(1);
1857 // Handle result values, copying them out of physregs into vregs that we
1859 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860 InVals, isThisReturn,
1861 isThisReturn ? OutVals[0] : SDValue());
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack. Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1869 ARMTargetLowering::HandleByVal(
1870 CCState *State, unsigned &size, unsigned Align) const {
1871 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1872 assert((State->getCallOrPrologue() == Prologue ||
1873 State->getCallOrPrologue() == Call) &&
1874 "unhandled ParmContext");
1876 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1877 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1878 unsigned AlignInRegs = Align / 4;
1879 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1880 for (unsigned i = 0; i < Waste; ++i)
1881 reg = State->AllocateReg(GPRArgRegs, 4);
1884 unsigned excess = 4 * (ARM::R4 - reg);
1886 // Special case when NSAA != SP and parameter size greater than size of
1887 // all remained GPR regs. In that case we can't split parameter, we must
1888 // send it to stack. We also must set NCRN to R4, so waste all
1889 // remained registers.
1890 const unsigned NSAAOffset = State->getNextStackOffset();
1891 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1892 while (State->AllocateReg(GPRArgRegs, 4))
1897 // First register for byval parameter is the first register that wasn't
1898 // allocated before this method call, so it would be "reg".
1899 // If parameter is small enough to be saved in range [reg, r4), then
1900 // the end (first after last) register would be reg + param-size-in-regs,
1901 // else parameter would be splitted between registers and stack,
1902 // end register would be r4 in this case.
1903 unsigned ByValRegBegin = reg;
1904 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1905 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1906 // Note, first register is allocated in the beginning of function already,
1907 // allocate remained amount of registers we need.
1908 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1909 State->AllocateReg(GPRArgRegs, 4);
1910 // A byval parameter that is split between registers and memory needs its
1911 // size truncated here.
1912 // In the case where the entire structure fits in registers, we set the
1913 // size in memory to zero.
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928 const TargetInstrInfo *TII) {
1929 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1931 if (Arg.getOpcode() == ISD::CopyFromReg) {
1932 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933 if (!TargetRegisterInfo::isVirtualRegister(VR))
1935 MachineInstr *Def = MRI->getVRegDef(VR);
1938 if (!Flags.isByVal()) {
1939 if (!TII->isLoadFromStackSlot(Def, FI))
1944 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945 if (Flags.isByVal())
1946 // ByVal argument is passed in as a pointer but it's now being
1947 // dereferenced. e.g.
1948 // define @foo(%struct.X* %A) {
1949 // tail call @bar(%struct.X* byval %A)
1952 SDValue Ptr = Ld->getBasePtr();
1953 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1956 FI = FINode->getIndex();
1960 assert(FI != INT_MAX);
1961 if (!MFI->isFixedObjectIndex(FI))
1963 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971 CallingConv::ID CalleeCC,
1973 bool isCalleeStructRet,
1974 bool isCallerStructRet,
1975 const SmallVectorImpl<ISD::OutputArg> &Outs,
1976 const SmallVectorImpl<SDValue> &OutVals,
1977 const SmallVectorImpl<ISD::InputArg> &Ins,
1978 SelectionDAG& DAG) const {
1979 const Function *CallerF = DAG.getMachineFunction().getFunction();
1980 CallingConv::ID CallerCC = CallerF->getCallingConv();
1981 bool CCMatch = CallerCC == CalleeCC;
1983 // Look for obvious safe cases to perform tail call optimization that do not
1984 // require ABI changes. This is what gcc calls sibcall.
1986 // Do not sibcall optimize vararg calls unless the call site is not passing
1988 if (isVarArg && !Outs.empty())
1991 // Exception-handling functions need a special set of instructions to indicate
1992 // a return to the hardware. Tail-calling another function would probably
1994 if (CallerF->hasFnAttribute("interrupt"))
1997 // Also avoid sibcall optimization if either caller or callee uses struct
1998 // return semantics.
1999 if (isCalleeStructRet || isCallerStructRet)
2002 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2003 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005 // support in the assembler and linker to be used. This would need to be
2006 // fixed to fully support tail calls in Thumb1.
2008 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009 // LR. This means if we need to reload LR, it takes an extra instructions,
2010 // which outweighs the value of the tail call; but here we don't know yet
2011 // whether LR is going to be used. Probably the right approach is to
2012 // generate the tail call here and turn it back into CALL/RET in
2013 // emitEpilogue if LR is used.
2015 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016 // but we need to make sure there are enough registers; the only valid
2017 // registers are the 4 used for parameters. We don't currently do this
2019 if (Subtarget->isThumb1Only())
2022 // Externally-defined functions with weak linkage should not be
2023 // tail-called on ARM when the OS does not support dynamic
2024 // pre-emption of symbols, as the AAELF spec requires normal calls
2025 // to undefined weak functions to be replaced with a NOP or jump to the
2026 // next instruction. The behaviour of branch instructions in this
2027 // situation (as used for tail calls) is implementation-defined, so we
2028 // cannot rely on the linker replacing the tail call with a return.
2029 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030 const GlobalValue *GV = G->getGlobal();
2031 const Triple TT(getTargetMachine().getTargetTriple());
2032 if (GV->hasExternalWeakLinkage() &&
2033 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2037 // If the calling conventions do not match, then we'd better make sure the
2038 // results are returned in the same way as what the caller expects.
2040 SmallVector<CCValAssign, 16> RVLocs1;
2041 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2042 *DAG.getContext(), Call);
2043 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2045 SmallVector<CCValAssign, 16> RVLocs2;
2046 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2047 *DAG.getContext(), Call);
2048 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2050 if (RVLocs1.size() != RVLocs2.size())
2052 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2053 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2055 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2057 if (RVLocs1[i].isRegLoc()) {
2058 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2061 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2067 // If Caller's vararg or byval argument has been split between registers and
2068 // stack, do not perform tail call, since part of the argument is in caller's
2070 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2071 getInfo<ARMFunctionInfo>();
2072 if (AFI_Caller->getArgRegsSaveSize())
2075 // If the callee takes no arguments then go on to check the results of the
2077 if (!Outs.empty()) {
2078 // Check if stack adjustment is needed. For now, do not do this if any
2079 // argument is passed on the stack.
2080 SmallVector<CCValAssign, 16> ArgLocs;
2081 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2082 *DAG.getContext(), Call);
2083 CCInfo.AnalyzeCallOperands(Outs,
2084 CCAssignFnForNode(CalleeCC, false, isVarArg));
2085 if (CCInfo.getNextStackOffset()) {
2086 MachineFunction &MF = DAG.getMachineFunction();
2088 // Check if the arguments are already laid out in the right way as
2089 // the caller's fixed stack objects.
2090 MachineFrameInfo *MFI = MF.getFrameInfo();
2091 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2092 const TargetInstrInfo *TII =
2093 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2094 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2096 ++i, ++realArgIdx) {
2097 CCValAssign &VA = ArgLocs[i];
2098 EVT RegVT = VA.getLocVT();
2099 SDValue Arg = OutVals[realArgIdx];
2100 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2101 if (VA.getLocInfo() == CCValAssign::Indirect)
2103 if (VA.needsCustom()) {
2104 // f64 and vector types are split into multiple registers or
2105 // register/stack-slot combinations. The types will not match
2106 // the registers; give up on memory f64 refs until we figure
2107 // out what to do about this.
2110 if (!ArgLocs[++i].isRegLoc())
2112 if (RegVT == MVT::v2f64) {
2113 if (!ArgLocs[++i].isRegLoc())
2115 if (!ArgLocs[++i].isRegLoc())
2118 } else if (!VA.isRegLoc()) {
2119 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2131 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2132 MachineFunction &MF, bool isVarArg,
2133 const SmallVectorImpl<ISD::OutputArg> &Outs,
2134 LLVMContext &Context) const {
2135 SmallVector<CCValAssign, 16> RVLocs;
2136 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2137 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2141 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2142 SDLoc DL, SelectionDAG &DAG) {
2143 const MachineFunction &MF = DAG.getMachineFunction();
2144 const Function *F = MF.getFunction();
2146 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2148 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2149 // version of the "preferred return address". These offsets affect the return
2150 // instruction if this is a return from PL1 without hypervisor extensions.
2151 // IRQ/FIQ: +4 "subs pc, lr, #4"
2152 // SWI: 0 "subs pc, lr, #0"
2153 // ABORT: +4 "subs pc, lr, #4"
2154 // UNDEF: +4/+2 "subs pc, lr, #0"
2155 // UNDEF varies depending on where the exception came from ARM or Thumb
2156 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2159 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2162 else if (IntKind == "SWI" || IntKind == "UNDEF")
2165 report_fatal_error("Unsupported interrupt attribute. If present, value "
2166 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2168 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2170 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2174 ARMTargetLowering::LowerReturn(SDValue Chain,
2175 CallingConv::ID CallConv, bool isVarArg,
2176 const SmallVectorImpl<ISD::OutputArg> &Outs,
2177 const SmallVectorImpl<SDValue> &OutVals,
2178 SDLoc dl, SelectionDAG &DAG) const {
2180 // CCValAssign - represent the assignment of the return value to a location.
2181 SmallVector<CCValAssign, 16> RVLocs;
2183 // CCState - Info about the registers and stack slots.
2184 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2185 *DAG.getContext(), Call);
2187 // Analyze outgoing return values.
2188 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2192 SmallVector<SDValue, 4> RetOps;
2193 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2194 bool isLittleEndian = Subtarget->isLittle();
2196 MachineFunction &MF = DAG.getMachineFunction();
2197 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2198 AFI->setReturnRegsCount(RVLocs.size());
2200 // Copy the result values into the output registers.
2201 for (unsigned i = 0, realRVLocIdx = 0;
2203 ++i, ++realRVLocIdx) {
2204 CCValAssign &VA = RVLocs[i];
2205 assert(VA.isRegLoc() && "Can only return in registers!");
2207 SDValue Arg = OutVals[realRVLocIdx];
2209 switch (VA.getLocInfo()) {
2210 default: llvm_unreachable("Unknown loc info!");
2211 case CCValAssign::Full: break;
2212 case CCValAssign::BCvt:
2213 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2217 if (VA.needsCustom()) {
2218 if (VA.getLocVT() == MVT::v2f64) {
2219 // Extract the first half and return it in two registers.
2220 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2221 DAG.getConstant(0, MVT::i32));
2222 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2223 DAG.getVTList(MVT::i32, MVT::i32), Half);
2225 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2226 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2228 Flag = Chain.getValue(1);
2229 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2230 VA = RVLocs[++i]; // skip ahead to next loc
2231 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2232 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2234 Flag = Chain.getValue(1);
2235 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2236 VA = RVLocs[++i]; // skip ahead to next loc
2238 // Extract the 2nd half and fall through to handle it as an f64 value.
2239 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2240 DAG.getConstant(1, MVT::i32));
2242 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2244 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2245 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2246 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2247 fmrrd.getValue(isLittleEndian ? 0 : 1),
2249 Flag = Chain.getValue(1);
2250 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2251 VA = RVLocs[++i]; // skip ahead to next loc
2252 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2253 fmrrd.getValue(isLittleEndian ? 1 : 0),
2256 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2258 // Guarantee that all emitted copies are
2259 // stuck together, avoiding something bad.
2260 Flag = Chain.getValue(1);
2261 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2264 // Update chain and glue.
2267 RetOps.push_back(Flag);
2269 // CPUs which aren't M-class use a special sequence to return from
2270 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2271 // though we use "subs pc, lr, #N").
2273 // M-class CPUs actually use a normal return sequence with a special
2274 // (hardware-provided) value in LR, so the normal code path works.
2275 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2276 !Subtarget->isMClass()) {
2277 if (Subtarget->isThumb1Only())
2278 report_fatal_error("interrupt attribute is not supported in Thumb1");
2279 return LowerInterruptReturn(RetOps, dl, DAG);
2282 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2285 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2286 if (N->getNumValues() != 1)
2288 if (!N->hasNUsesOfValue(1, 0))
2291 SDValue TCChain = Chain;
2292 SDNode *Copy = *N->use_begin();
2293 if (Copy->getOpcode() == ISD::CopyToReg) {
2294 // If the copy has a glue operand, we conservatively assume it isn't safe to
2295 // perform a tail call.
2296 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2298 TCChain = Copy->getOperand(0);
2299 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2300 SDNode *VMov = Copy;
2301 // f64 returned in a pair of GPRs.
2302 SmallPtrSet<SDNode*, 2> Copies;
2303 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2305 if (UI->getOpcode() != ISD::CopyToReg)
2309 if (Copies.size() > 2)
2312 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2314 SDValue UseChain = UI->getOperand(0);
2315 if (Copies.count(UseChain.getNode()))
2319 // We are at the top of this chain.
2320 // If the copy has a glue operand, we conservatively assume it
2321 // isn't safe to perform a tail call.
2322 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2328 } else if (Copy->getOpcode() == ISD::BITCAST) {
2329 // f32 returned in a single GPR.
2330 if (!Copy->hasOneUse())
2332 Copy = *Copy->use_begin();
2333 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2335 // If the copy has a glue operand, we conservatively assume it isn't safe to
2336 // perform a tail call.
2337 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2339 TCChain = Copy->getOperand(0);
2344 bool HasRet = false;
2345 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2347 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2348 UI->getOpcode() != ARMISD::INTRET_FLAG)
2360 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2361 if (!Subtarget->supportsTailCall())
2364 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2367 return !Subtarget->isThumb1Only();
2370 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2371 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2372 // one of the above mentioned nodes. It has to be wrapped because otherwise
2373 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2374 // be used to form addressing mode. These wrapped nodes will be selected
2376 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2377 EVT PtrVT = Op.getValueType();
2378 // FIXME there is no actual debug info here
2380 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2382 if (CP->isMachineConstantPoolEntry())
2383 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2384 CP->getAlignment());
2386 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2387 CP->getAlignment());
2388 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2391 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2392 return MachineJumpTableInfo::EK_Inline;
2395 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2396 SelectionDAG &DAG) const {
2397 MachineFunction &MF = DAG.getMachineFunction();
2398 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2399 unsigned ARMPCLabelIndex = 0;
2401 EVT PtrVT = getPointerTy();
2402 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2403 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2405 if (RelocM == Reloc::Static) {
2406 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2408 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2409 ARMPCLabelIndex = AFI->createPICLabelUId();
2410 ARMConstantPoolValue *CPV =
2411 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2412 ARMCP::CPBlockAddress, PCAdj);
2413 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2415 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2416 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2417 MachinePointerInfo::getConstantPool(),
2418 false, false, false, 0);
2419 if (RelocM == Reloc::Static)
2421 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2422 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2425 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2427 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2428 SelectionDAG &DAG) const {
2430 EVT PtrVT = getPointerTy();
2431 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2432 MachineFunction &MF = DAG.getMachineFunction();
2433 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2434 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2435 ARMConstantPoolValue *CPV =
2436 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2437 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2438 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2439 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2440 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2441 MachinePointerInfo::getConstantPool(),
2442 false, false, false, 0);
2443 SDValue Chain = Argument.getValue(1);
2445 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2446 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2448 // call __tls_get_addr.
2451 Entry.Node = Argument;
2452 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2453 Args.push_back(Entry);
2455 // FIXME: is there useful debug info available here?
2456 TargetLowering::CallLoweringInfo CLI(DAG);
2457 CLI.setDebugLoc(dl).setChain(Chain)
2458 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2459 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2462 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2463 return CallResult.first;
2466 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2467 // "local exec" model.
2469 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2471 TLSModel::Model model) const {
2472 const GlobalValue *GV = GA->getGlobal();
2475 SDValue Chain = DAG.getEntryNode();
2476 EVT PtrVT = getPointerTy();
2477 // Get the Thread Pointer
2478 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2480 if (model == TLSModel::InitialExec) {
2481 MachineFunction &MF = DAG.getMachineFunction();
2482 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2483 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2484 // Initial exec model.
2485 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2486 ARMConstantPoolValue *CPV =
2487 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2488 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2490 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2491 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2492 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2493 MachinePointerInfo::getConstantPool(),
2494 false, false, false, 0);
2495 Chain = Offset.getValue(1);
2497 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2498 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2500 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2501 MachinePointerInfo::getConstantPool(),
2502 false, false, false, 0);
2505 assert(model == TLSModel::LocalExec);
2506 ARMConstantPoolValue *CPV =
2507 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2508 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2509 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2510 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2511 MachinePointerInfo::getConstantPool(),
2512 false, false, false, 0);
2515 // The address of the thread local variable is the add of the thread
2516 // pointer with the offset of the variable.
2517 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2521 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2522 // TODO: implement the "local dynamic" model
2523 assert(Subtarget->isTargetELF() &&
2524 "TLS not implemented for non-ELF targets");
2525 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2527 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2530 case TLSModel::GeneralDynamic:
2531 case TLSModel::LocalDynamic:
2532 return LowerToTLSGeneralDynamicModel(GA, DAG);
2533 case TLSModel::InitialExec:
2534 case TLSModel::LocalExec:
2535 return LowerToTLSExecModels(GA, DAG, model);
2537 llvm_unreachable("bogus TLS model");
2540 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2541 SelectionDAG &DAG) const {
2542 EVT PtrVT = getPointerTy();
2544 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2545 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2546 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2547 ARMConstantPoolValue *CPV =
2548 ARMConstantPoolConstant::Create(GV,
2549 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2550 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2551 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2552 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2554 MachinePointerInfo::getConstantPool(),
2555 false, false, false, 0);
2556 SDValue Chain = Result.getValue(1);
2557 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2558 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2560 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2561 MachinePointerInfo::getGOT(),
2562 false, false, false, 0);
2566 // If we have T2 ops, we can materialize the address directly via movt/movw
2567 // pair. This is always cheaper.
2568 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2570 // FIXME: Once remat is capable of dealing with instructions with register
2571 // operands, expand this into two nodes.
2572 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2573 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2575 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2576 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2577 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2578 MachinePointerInfo::getConstantPool(),
2579 false, false, false, 0);
2583 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2584 SelectionDAG &DAG) const {
2585 EVT PtrVT = getPointerTy();
2587 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2588 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2590 if (Subtarget->useMovt(DAG.getMachineFunction()))
2593 // FIXME: Once remat is capable of dealing with instructions with register
2594 // operands, expand this into multiple nodes
2596 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2598 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2599 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2601 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2602 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2603 MachinePointerInfo::getGOT(), false, false, false, 0);
2607 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2608 SelectionDAG &DAG) const {
2609 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2610 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2611 "Windows on ARM expects to use movw/movt");
2613 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2614 const ARMII::TOF TargetFlags =
2615 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2616 EVT PtrVT = getPointerTy();
2622 // FIXME: Once remat is capable of dealing with instructions with register
2623 // operands, expand this into two nodes.
2624 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2625 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2627 if (GV->hasDLLImportStorageClass())
2628 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2629 MachinePointerInfo::getGOT(), false, false, false, 0);
2633 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2634 SelectionDAG &DAG) const {
2635 assert(Subtarget->isTargetELF() &&
2636 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2637 MachineFunction &MF = DAG.getMachineFunction();
2638 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2639 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2640 EVT PtrVT = getPointerTy();
2642 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2643 ARMConstantPoolValue *CPV =
2644 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2645 ARMPCLabelIndex, PCAdj);
2646 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2647 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2648 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2649 MachinePointerInfo::getConstantPool(),
2650 false, false, false, 0);
2651 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2652 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2656 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2658 SDValue Val = DAG.getConstant(0, MVT::i32);
2659 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2660 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2661 Op.getOperand(1), Val);
2665 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2667 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2668 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2672 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2673 const ARMSubtarget *Subtarget) const {
2674 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2677 default: return SDValue(); // Don't custom lower most intrinsics.
2678 case Intrinsic::arm_rbit: {
2679 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2680 "RBIT intrinsic must have i32 type!");
2681 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2683 case Intrinsic::arm_thread_pointer: {
2684 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2685 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2687 case Intrinsic::eh_sjlj_lsda: {
2688 MachineFunction &MF = DAG.getMachineFunction();
2689 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2690 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2691 EVT PtrVT = getPointerTy();
2692 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2694 unsigned PCAdj = (RelocM != Reloc::PIC_)
2695 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2696 ARMConstantPoolValue *CPV =
2697 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2698 ARMCP::CPLSDA, PCAdj);
2699 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2700 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2702 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2703 MachinePointerInfo::getConstantPool(),
2704 false, false, false, 0);
2706 if (RelocM == Reloc::PIC_) {
2707 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2708 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2712 case Intrinsic::arm_neon_vmulls:
2713 case Intrinsic::arm_neon_vmullu: {
2714 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2715 ? ARMISD::VMULLs : ARMISD::VMULLu;
2716 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2717 Op.getOperand(1), Op.getOperand(2));
2722 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2723 const ARMSubtarget *Subtarget) {
2724 // FIXME: handle "fence singlethread" more efficiently.
2726 if (!Subtarget->hasDataBarrier()) {
2727 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2728 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2730 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2731 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2732 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2733 DAG.getConstant(0, MVT::i32));
2736 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2737 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2738 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2739 if (Subtarget->isMClass()) {
2740 // Only a full system barrier exists in the M-class architectures.
2741 Domain = ARM_MB::SY;
2742 } else if (Subtarget->isSwift() && Ord == Release) {
2743 // Swift happens to implement ISHST barriers in a way that's compatible with
2744 // Release semantics but weaker than ISH so we'd be fools not to use
2745 // it. Beware: other processors probably don't!
2746 Domain = ARM_MB::ISHST;
2749 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2750 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2751 DAG.getConstant(Domain, MVT::i32));
2754 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2755 const ARMSubtarget *Subtarget) {
2756 // ARM pre v5TE and Thumb1 does not have preload instructions.
2757 if (!(Subtarget->isThumb2() ||
2758 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2759 // Just preserve the chain.
2760 return Op.getOperand(0);
2763 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2765 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2766 // ARMv7 with MP extension has PLDW.
2767 return Op.getOperand(0);
2769 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2770 if (Subtarget->isThumb()) {
2772 isRead = ~isRead & 1;
2773 isData = ~isData & 1;
2776 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2777 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2778 DAG.getConstant(isData, MVT::i32));
2781 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2782 MachineFunction &MF = DAG.getMachineFunction();
2783 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2785 // vastart just stores the address of the VarArgsFrameIndex slot into the
2786 // memory location argument.
2788 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2789 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2790 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2791 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2792 MachinePointerInfo(SV), false, false, 0);
2796 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2797 SDValue &Root, SelectionDAG &DAG,
2799 MachineFunction &MF = DAG.getMachineFunction();
2800 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2802 const TargetRegisterClass *RC;
2803 if (AFI->isThumb1OnlyFunction())
2804 RC = &ARM::tGPRRegClass;
2806 RC = &ARM::GPRRegClass;
2808 // Transform the arguments stored in physical registers into virtual ones.
2809 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2810 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813 if (NextVA.isMemLoc()) {
2814 MachineFrameInfo *MFI = MF.getFrameInfo();
2815 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2817 // Create load node to retrieve arguments from the stack.
2818 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2819 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2820 MachinePointerInfo::getFixedStack(FI),
2821 false, false, false, 0);
2823 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2824 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2826 if (!Subtarget->isLittle())
2827 std::swap (ArgValue, ArgValue2);
2828 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2832 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2833 unsigned InRegsParamRecordIdx,
2835 unsigned &ArgRegsSize,
2836 unsigned &ArgRegsSaveSize)
2839 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2840 unsigned RBegin, REnd;
2841 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2842 NumGPRs = REnd - RBegin;
2844 unsigned int firstUnalloced;
2845 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2846 sizeof(GPRArgRegs) /
2847 sizeof(GPRArgRegs[0]));
2848 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2851 unsigned Align = MF.getTarget()
2853 ->getFrameLowering()
2854 ->getStackAlignment();
2855 ArgRegsSize = NumGPRs * 4;
2857 // If parameter is split between stack and GPRs...
2858 if (NumGPRs && Align > 4 &&
2859 (ArgRegsSize < ArgSize ||
2860 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2861 // Add padding for part of param recovered from GPRs. For example,
2862 // if Align == 8, its last byte must be at address K*8 - 1.
2863 // We need to do it, since remained (stack) part of parameter has
2864 // stack alignment, and we need to "attach" "GPRs head" without gaps
2867 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2868 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2870 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2872 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2873 ArgRegsSaveSize = ArgRegsSize + Padding;
2875 // We don't need to extend regs save size for byval parameters if they
2876 // are passed via GPRs only.
2877 ArgRegsSaveSize = ArgRegsSize;
2880 // The remaining GPRs hold either the beginning of variable-argument
2881 // data, or the beginning of an aggregate passed by value (usually
2882 // byval). Either way, we allocate stack slots adjacent to the data
2883 // provided by our caller, and store the unallocated registers there.
2884 // If this is a variadic function, the va_list pointer will begin with
2885 // these values; otherwise, this reassembles a (byval) structure that
2886 // was split between registers and memory.
2887 // Return: The frame index registers were stored into.
2889 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2890 SDLoc dl, SDValue &Chain,
2891 const Value *OrigArg,
2892 unsigned InRegsParamRecordIdx,
2893 unsigned OffsetFromOrigArg,
2897 unsigned ByValStoreOffset,
2898 unsigned TotalArgRegsSaveSize) const {
2900 // Currently, two use-cases possible:
2901 // Case #1. Non-var-args function, and we meet first byval parameter.
2902 // Setup first unallocated register as first byval register;
2903 // eat all remained registers
2904 // (these two actions are performed by HandleByVal method).
2905 // Then, here, we initialize stack frame with
2906 // "store-reg" instructions.
2907 // Case #2. Var-args function, that doesn't contain byval parameters.
2908 // The same: eat all remained unallocated registers,
2909 // initialize stack frame.
2911 MachineFunction &MF = DAG.getMachineFunction();
2912 MachineFrameInfo *MFI = MF.getFrameInfo();
2913 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2914 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2915 unsigned RBegin, REnd;
2916 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2917 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2918 firstRegToSaveIndex = RBegin - ARM::R0;
2919 lastRegToSaveIndex = REnd - ARM::R0;
2921 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2922 (GPRArgRegs, array_lengthof(GPRArgRegs));
2923 lastRegToSaveIndex = 4;
2926 unsigned ArgRegsSize, ArgRegsSaveSize;
2927 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2928 ArgRegsSize, ArgRegsSaveSize);
2930 // Store any by-val regs to their spots on the stack so that they may be
2931 // loaded by deferencing the result of formal parameter pointer or va_next.
2932 // Note: once stack area for byval/varargs registers
2933 // was initialized, it can't be initialized again.
2934 if (ArgRegsSaveSize) {
2935 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2938 assert(AFI->getStoredByValParamsPadding() == 0 &&
2939 "The only parameter may be padded.");
2940 AFI->setStoredByValParamsPadding(Padding);
2943 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2946 (int64_t)TotalArgRegsSaveSize,
2948 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2950 MFI->CreateFixedObject(Padding,
2951 ArgOffset + ByValStoreOffset -
2952 (int64_t)ArgRegsSaveSize,
2956 SmallVector<SDValue, 4> MemOps;
2957 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2958 ++firstRegToSaveIndex, ++i) {
2959 const TargetRegisterClass *RC;
2960 if (AFI->isThumb1OnlyFunction())
2961 RC = &ARM::tGPRRegClass;
2963 RC = &ARM::GPRRegClass;
2965 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2966 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2968 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2969 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2971 MemOps.push_back(Store);
2972 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2973 DAG.getConstant(4, getPointerTy()));
2976 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2978 if (!MemOps.empty())
2979 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2983 // We cannot allocate a zero-byte object for the first variadic argument,
2984 // so just make up a size.
2987 // This will point to the next argument passed via stack.
2988 return MFI->CreateFixedObject(
2989 ArgSize, ArgOffset, !ForceMutable);
2993 // Setup stack frame, the va_list pointer will start from.
2995 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2996 SDLoc dl, SDValue &Chain,
2998 unsigned TotalArgRegsSaveSize,
2999 bool ForceMutable) const {
3000 MachineFunction &MF = DAG.getMachineFunction();
3001 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3003 // Try to store any remaining integer argument regs
3004 // to their spots on the stack so that they may be loaded by deferencing
3005 // the result of va_next.
3006 // If there is no regs to be stored, just point address after last
3007 // argument passed via stack.
3009 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3010 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3011 0, TotalArgRegsSaveSize);
3013 AFI->setVarArgsFrameIndex(FrameIndex);
3017 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3018 CallingConv::ID CallConv, bool isVarArg,
3019 const SmallVectorImpl<ISD::InputArg>
3021 SDLoc dl, SelectionDAG &DAG,
3022 SmallVectorImpl<SDValue> &InVals)
3024 MachineFunction &MF = DAG.getMachineFunction();
3025 MachineFrameInfo *MFI = MF.getFrameInfo();
3027 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3029 // Assign locations to all of the incoming arguments.
3030 SmallVector<CCValAssign, 16> ArgLocs;
3031 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3032 *DAG.getContext(), Prologue);
3033 CCInfo.AnalyzeFormalArguments(Ins,
3034 CCAssignFnForNode(CallConv, /* Return*/ false,
3037 SmallVector<SDValue, 16> ArgValues;
3038 int lastInsIndex = -1;
3040 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3041 unsigned CurArgIdx = 0;
3043 // Initially ArgRegsSaveSize is zero.
3044 // Then we increase this value each time we meet byval parameter.
3045 // We also increase this value in case of varargs function.
3046 AFI->setArgRegsSaveSize(0);
3048 unsigned ByValStoreOffset = 0;
3049 unsigned TotalArgRegsSaveSize = 0;
3050 unsigned ArgRegsSaveSizeMaxAlign = 4;
3052 // Calculate the amount of stack space that we need to allocate to store
3053 // byval and variadic arguments that are passed in registers.
3054 // We need to know this before we allocate the first byval or variadic
3055 // argument, as they will be allocated a stack slot below the CFA (Canonical
3056 // Frame Address, the stack pointer at entry to the function).
3057 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3058 CCValAssign &VA = ArgLocs[i];
3059 if (VA.isMemLoc()) {
3060 int index = VA.getValNo();
3061 if (index != lastInsIndex) {
3062 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3063 if (Flags.isByVal()) {
3064 unsigned ExtraArgRegsSize;
3065 unsigned ExtraArgRegsSaveSize;
3066 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProcessed(),
3067 Flags.getByValSize(),
3068 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3070 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3071 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3072 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3073 CCInfo.nextInRegsParam();
3075 lastInsIndex = index;
3079 CCInfo.rewindByValRegsInfo();
3081 if (isVarArg && MFI->hasVAStart()) {
3082 unsigned ExtraArgRegsSize;
3083 unsigned ExtraArgRegsSaveSize;
3084 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3085 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3086 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3088 // If the arg regs save area contains N-byte aligned values, the
3089 // bottom of it must be at least N-byte aligned.
3090 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3091 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3093 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3094 CCValAssign &VA = ArgLocs[i];
3095 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3096 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3097 // Arguments stored in registers.
3098 if (VA.isRegLoc()) {
3099 EVT RegVT = VA.getLocVT();
3101 if (VA.needsCustom()) {
3102 // f64 and vector types are split up into multiple registers or
3103 // combinations of registers and stack slots.
3104 if (VA.getLocVT() == MVT::v2f64) {
3105 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3107 VA = ArgLocs[++i]; // skip ahead to next loc
3109 if (VA.isMemLoc()) {
3110 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3111 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3112 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3113 MachinePointerInfo::getFixedStack(FI),
3114 false, false, false, 0);
3116 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3119 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3120 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3121 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3122 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3123 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3125 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3128 const TargetRegisterClass *RC;
3130 if (RegVT == MVT::f32)
3131 RC = &ARM::SPRRegClass;
3132 else if (RegVT == MVT::f64)
3133 RC = &ARM::DPRRegClass;
3134 else if (RegVT == MVT::v2f64)
3135 RC = &ARM::QPRRegClass;
3136 else if (RegVT == MVT::i32)
3137 RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3138 : &ARM::GPRRegClass;
3140 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3142 // Transform the arguments in physical registers into virtual ones.
3143 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3144 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3147 // If this is an 8 or 16-bit value, it is really passed promoted
3148 // to 32 bits. Insert an assert[sz]ext to capture this, then
3149 // truncate to the right size.
3150 switch (VA.getLocInfo()) {
3151 default: llvm_unreachable("Unknown loc info!");
3152 case CCValAssign::Full: break;
3153 case CCValAssign::BCvt:
3154 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3156 case CCValAssign::SExt:
3157 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3158 DAG.getValueType(VA.getValVT()));
3159 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3161 case CCValAssign::ZExt:
3162 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3163 DAG.getValueType(VA.getValVT()));
3164 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3168 InVals.push_back(ArgValue);
3170 } else { // VA.isRegLoc()
3173 assert(VA.isMemLoc());
3174 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3176 int index = ArgLocs[i].getValNo();
3178 // Some Ins[] entries become multiple ArgLoc[] entries.
3179 // Process them only once.
3180 if (index != lastInsIndex)
3182 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3183 // FIXME: For now, all byval parameter objects are marked mutable.
3184 // This can be changed with more analysis.
3185 // In case of tail call optimization mark all arguments mutable.
3186 // Since they could be overwritten by lowering of arguments in case of
3188 if (Flags.isByVal()) {
3189 unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3191 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3192 int FrameIndex = StoreByValRegs(
3193 CCInfo, DAG, dl, Chain, CurOrigArg,
3195 Ins[VA.getValNo()].PartOffset,
3196 VA.getLocMemOffset(),
3197 Flags.getByValSize(),
3198 true /*force mutable frames*/,
3200 TotalArgRegsSaveSize);
3201 ByValStoreOffset += Flags.getByValSize();
3202 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3203 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3204 CCInfo.nextInRegsParam();
3206 unsigned FIOffset = VA.getLocMemOffset();
3207 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3210 // Create load nodes to retrieve arguments from the stack.
3211 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3212 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3213 MachinePointerInfo::getFixedStack(FI),
3214 false, false, false, 0));
3216 lastInsIndex = index;
3222 if (isVarArg && MFI->hasVAStart())
3223 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3224 CCInfo.getNextStackOffset(),
3225 TotalArgRegsSaveSize);
3227 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3232 /// isFloatingPointZero - Return true if this is +0.0.
3233 static bool isFloatingPointZero(SDValue Op) {
3234 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3235 return CFP->getValueAPF().isPosZero();
3236 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3237 // Maybe this has already been legalized into the constant pool?
3238 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3239 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3240 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3241 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3242 return CFP->getValueAPF().isPosZero();
3244 } else if (Op->getOpcode() == ISD::BITCAST &&
3245 Op->getValueType(0) == MVT::f64) {
3246 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3247 // created by LowerConstantFP().
3248 SDValue BitcastOp = Op->getOperand(0);
3249 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3250 SDValue MoveOp = BitcastOp->getOperand(0);
3251 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3252 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3260 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3261 /// the given operands.
3263 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3264 SDValue &ARMcc, SelectionDAG &DAG,
3266 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3267 unsigned C = RHSC->getZExtValue();
3268 if (!isLegalICmpImmediate(C)) {
3269 // Constant does not fit, try adjusting it by one?
3274 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3275 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3276 RHS = DAG.getConstant(C-1, MVT::i32);
3281 if (C != 0 && isLegalICmpImmediate(C-1)) {
3282 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3283 RHS = DAG.getConstant(C-1, MVT::i32);
3288 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3289 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3290 RHS = DAG.getConstant(C+1, MVT::i32);
3295 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3296 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3297 RHS = DAG.getConstant(C+1, MVT::i32);
3304 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3305 ARMISD::NodeType CompareType;
3308 CompareType = ARMISD::CMP;
3313 CompareType = ARMISD::CMPZ;
3316 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3317 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3320 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3322 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3324 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3326 if (!isFloatingPointZero(RHS))
3327 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3329 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3330 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3333 /// duplicateCmp - Glue values can have only one use, so this function
3334 /// duplicates a comparison node.
3336 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3337 unsigned Opc = Cmp.getOpcode();
3339 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3340 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3342 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3343 Cmp = Cmp.getOperand(0);
3344 Opc = Cmp.getOpcode();
3345 if (Opc == ARMISD::CMPFP)
3346 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3348 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3349 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3351 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3354 std::pair<SDValue, SDValue>
3355 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3356 SDValue &ARMcc) const {
3357 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3359 SDValue Value, OverflowCmp;
3360 SDValue LHS = Op.getOperand(0);
3361 SDValue RHS = Op.getOperand(1);
3364 // FIXME: We are currently always generating CMPs because we don't support
3365 // generating CMN through the backend. This is not as good as the natural
3366 // CMP case because it causes a register dependency and cannot be folded
3369 switch (Op.getOpcode()) {
3371 llvm_unreachable("Unknown overflow instruction!");
3373 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3374 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3375 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3378 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3379 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3380 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3383 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3384 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3385 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3388 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3389 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3390 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3394 return std::make_pair(Value, OverflowCmp);
3399 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3400 // Let legalize expand this if it isn't a legal type yet.
3401 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3404 SDValue Value, OverflowCmp;
3406 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3407 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3408 // We use 0 and 1 as false and true values.
3409 SDValue TVal = DAG.getConstant(1, MVT::i32);
3410 SDValue FVal = DAG.getConstant(0, MVT::i32);
3411 EVT VT = Op.getValueType();
3413 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3414 ARMcc, CCR, OverflowCmp);
3416 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3417 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3421 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3422 SDValue Cond = Op.getOperand(0);
3423 SDValue SelectTrue = Op.getOperand(1);
3424 SDValue SelectFalse = Op.getOperand(2);
3426 unsigned Opc = Cond.getOpcode();
3428 if (Cond.getResNo() == 1 &&
3429 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3430 Opc == ISD::USUBO)) {
3431 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3434 SDValue Value, OverflowCmp;
3436 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3437 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3438 EVT VT = Op.getValueType();
3440 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3446 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3447 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3449 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3450 const ConstantSDNode *CMOVTrue =
3451 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3452 const ConstantSDNode *CMOVFalse =
3453 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3455 if (CMOVTrue && CMOVFalse) {
3456 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3457 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3461 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3463 False = SelectFalse;
3464 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3469 if (True.getNode() && False.getNode()) {
3470 EVT VT = Op.getValueType();
3471 SDValue ARMcc = Cond.getOperand(2);
3472 SDValue CCR = Cond.getOperand(3);
3473 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3474 assert(True.getValueType() == VT);
3475 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3480 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3481 // undefined bits before doing a full-word comparison with zero.
3482 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3483 DAG.getConstant(1, Cond.getValueType()));
3485 return DAG.getSelectCC(dl, Cond,
3486 DAG.getConstant(0, Cond.getValueType()),
3487 SelectTrue, SelectFalse, ISD::SETNE);
3490 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3491 if (CC == ISD::SETNE)
3493 return ISD::getSetCCInverse(CC, true);
3496 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3497 bool &swpCmpOps, bool &swpVselOps) {
3498 // Start by selecting the GE condition code for opcodes that return true for
3500 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3502 CondCode = ARMCC::GE;
3504 // and GT for opcodes that return false for 'equality'.
3505 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3507 CondCode = ARMCC::GT;
3509 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3510 // to swap the compare operands.
3511 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3515 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3516 // If we have an unordered opcode, we need to swap the operands to the VSEL
3517 // instruction (effectively negating the condition).
3519 // This also has the effect of swapping which one of 'less' or 'greater'
3520 // returns true, so we also swap the compare operands. It also switches
3521 // whether we return true for 'equality', so we compensate by picking the
3522 // opposite condition code to our original choice.
3523 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3524 CC == ISD::SETUGT) {
3525 swpCmpOps = !swpCmpOps;
3526 swpVselOps = !swpVselOps;
3527 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3530 // 'ordered' is 'anything but unordered', so use the VS condition code and
3531 // swap the VSEL operands.
3532 if (CC == ISD::SETO) {
3533 CondCode = ARMCC::VS;
3537 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3538 // code and swap the VSEL operands.
3539 if (CC == ISD::SETUNE) {
3540 CondCode = ARMCC::EQ;
3545 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3546 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3547 SDValue Cmp, SelectionDAG &DAG) const {
3548 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3549 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3550 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3551 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3552 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3554 SDValue TrueLow = TrueVal.getValue(0);
3555 SDValue TrueHigh = TrueVal.getValue(1);
3556 SDValue FalseLow = FalseVal.getValue(0);
3557 SDValue FalseHigh = FalseVal.getValue(1);
3559 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3561 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3562 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3564 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3566 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3571 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3572 EVT VT = Op.getValueType();
3573 SDValue LHS = Op.getOperand(0);
3574 SDValue RHS = Op.getOperand(1);
3575 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3576 SDValue TrueVal = Op.getOperand(2);
3577 SDValue FalseVal = Op.getOperand(3);
3580 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3581 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3584 // If softenSetCCOperands only returned one value, we should compare it to
3586 if (!RHS.getNode()) {
3587 RHS = DAG.getConstant(0, LHS.getValueType());
3592 if (LHS.getValueType() == MVT::i32) {
3593 // Try to generate VSEL on ARMv8.
3594 // The VSEL instruction can't use all the usual ARM condition
3595 // codes: it only has two bits to select the condition code, so it's
3596 // constrained to use only GE, GT, VS and EQ.
3598 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3599 // swap the operands of the previous compare instruction (effectively
3600 // inverting the compare condition, swapping 'less' and 'greater') and
3601 // sometimes need to swap the operands to the VSEL (which inverts the
3602 // condition in the sense of firing whenever the previous condition didn't)
3603 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3604 TrueVal.getValueType() == MVT::f64)) {
3605 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3606 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3607 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3608 CC = getInverseCCForVSEL(CC);
3609 std::swap(TrueVal, FalseVal);
3614 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3615 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3616 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3619 ARMCC::CondCodes CondCode, CondCode2;
3620 FPCCToARMCC(CC, CondCode, CondCode2);
3622 // Try to generate VSEL on ARMv8.
3623 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3624 TrueVal.getValueType() == MVT::f64)) {
3625 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3626 // same operands, as follows:
3627 // c = fcmp [ogt, olt, ugt, ult] a, b
3629 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3630 // handled differently than the original code sequence.
3631 if (getTargetMachine().Options.UnsafeFPMath) {
3632 if (LHS == TrueVal && RHS == FalseVal) {
3633 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3634 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3635 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3636 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3637 } else if (LHS == FalseVal && RHS == TrueVal) {
3638 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3639 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3640 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3641 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3645 bool swpCmpOps = false;
3646 bool swpVselOps = false;
3647 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3649 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3650 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3652 std::swap(LHS, RHS);
3654 std::swap(TrueVal, FalseVal);
3658 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3659 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3660 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3661 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3662 if (CondCode2 != ARMCC::AL) {
3663 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3664 // FIXME: Needs another CMP because flag can have but one use.
3665 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3666 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3671 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3672 /// to morph to an integer compare sequence.
3673 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3674 const ARMSubtarget *Subtarget) {
3675 SDNode *N = Op.getNode();
3676 if (!N->hasOneUse())
3677 // Otherwise it requires moving the value from fp to integer registers.
3679 if (!N->getNumValues())
3681 EVT VT = Op.getValueType();
3682 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3683 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3684 // vmrs are very slow, e.g. cortex-a8.
3687 if (isFloatingPointZero(Op)) {
3691 return ISD::isNormalLoad(N);
3694 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3695 if (isFloatingPointZero(Op))
3696 return DAG.getConstant(0, MVT::i32);
3698 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3699 return DAG.getLoad(MVT::i32, SDLoc(Op),
3700 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3701 Ld->isVolatile(), Ld->isNonTemporal(),
3702 Ld->isInvariant(), Ld->getAlignment());
3704 llvm_unreachable("Unknown VFP cmp argument!");
3707 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3708 SDValue &RetVal1, SDValue &RetVal2) {
3709 if (isFloatingPointZero(Op)) {
3710 RetVal1 = DAG.getConstant(0, MVT::i32);
3711 RetVal2 = DAG.getConstant(0, MVT::i32);
3715 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3716 SDValue Ptr = Ld->getBasePtr();
3717 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3718 Ld->getChain(), Ptr,
3719 Ld->getPointerInfo(),
3720 Ld->isVolatile(), Ld->isNonTemporal(),
3721 Ld->isInvariant(), Ld->getAlignment());
3723 EVT PtrType = Ptr.getValueType();
3724 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3725 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3726 PtrType, Ptr, DAG.getConstant(4, PtrType));
3727 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3728 Ld->getChain(), NewPtr,
3729 Ld->getPointerInfo().getWithOffset(4),
3730 Ld->isVolatile(), Ld->isNonTemporal(),
3731 Ld->isInvariant(), NewAlign);
3735 llvm_unreachable("Unknown VFP cmp argument!");
3738 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3739 /// f32 and even f64 comparisons to integer ones.
3741 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3742 SDValue Chain = Op.getOperand(0);
3743 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3744 SDValue LHS = Op.getOperand(2);
3745 SDValue RHS = Op.getOperand(3);
3746 SDValue Dest = Op.getOperand(4);
3749 bool LHSSeenZero = false;
3750 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3751 bool RHSSeenZero = false;
3752 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3753 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3754 // If unsafe fp math optimization is enabled and there are no other uses of
3755 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3756 // to an integer comparison.
3757 if (CC == ISD::SETOEQ)
3759 else if (CC == ISD::SETUNE)
3762 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3764 if (LHS.getValueType() == MVT::f32) {
3765 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3766 bitcastf32Toi32(LHS, DAG), Mask);
3767 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3768 bitcastf32Toi32(RHS, DAG), Mask);
3769 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3770 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3771 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3772 Chain, Dest, ARMcc, CCR, Cmp);
3777 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3778 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3779 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3780 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3781 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3782 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3783 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3784 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3785 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3791 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3792 SDValue Chain = Op.getOperand(0);
3793 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3794 SDValue LHS = Op.getOperand(2);
3795 SDValue RHS = Op.getOperand(3);
3796 SDValue Dest = Op.getOperand(4);
3799 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3800 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3803 // If softenSetCCOperands only returned one value, we should compare it to
3805 if (!RHS.getNode()) {
3806 RHS = DAG.getConstant(0, LHS.getValueType());
3811 if (LHS.getValueType() == MVT::i32) {
3813 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3814 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3815 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3816 Chain, Dest, ARMcc, CCR, Cmp);
3819 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3821 if (getTargetMachine().Options.UnsafeFPMath &&
3822 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3823 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3824 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3825 if (Result.getNode())
3829 ARMCC::CondCodes CondCode, CondCode2;
3830 FPCCToARMCC(CC, CondCode, CondCode2);
3832 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3833 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3834 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3835 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3836 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3837 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3838 if (CondCode2 != ARMCC::AL) {
3839 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3840 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3841 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3846 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3847 SDValue Chain = Op.getOperand(0);
3848 SDValue Table = Op.getOperand(1);
3849 SDValue Index = Op.getOperand(2);
3852 EVT PTy = getPointerTy();
3853 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3854 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3855 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3856 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3857 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3858 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3859 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3860 if (Subtarget->isThumb2()) {
3861 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3862 // which does another jump to the destination. This also makes it easier
3863 // to translate it to TBB / TBH later.
3864 // FIXME: This might not work if the function is extremely large.
3865 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3866 Addr, Op.getOperand(2), JTI, UId);
3868 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3869 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3870 MachinePointerInfo::getJumpTable(),
3871 false, false, false, 0);
3872 Chain = Addr.getValue(1);
3873 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3874 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3876 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3877 MachinePointerInfo::getJumpTable(),
3878 false, false, false, 0);
3879 Chain = Addr.getValue(1);
3880 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3884 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3885 EVT VT = Op.getValueType();
3888 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3889 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3891 return DAG.UnrollVectorOp(Op.getNode());
3894 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3895 "Invalid type for custom lowering!");
3896 if (VT != MVT::v4i16)
3897 return DAG.UnrollVectorOp(Op.getNode());
3899 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3900 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3903 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3904 EVT VT = Op.getValueType();
3906 return LowerVectorFP_TO_INT(Op, DAG);
3908 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3910 if (Op.getOpcode() == ISD::FP_TO_SINT)
3911 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3914 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3916 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3917 /*isSigned*/ false, SDLoc(Op)).first;
3923 switch (Op.getOpcode()) {
3924 default: llvm_unreachable("Invalid opcode!");
3925 case ISD::FP_TO_SINT:
3926 Opc = ARMISD::FTOSI;
3928 case ISD::FP_TO_UINT:
3929 Opc = ARMISD::FTOUI;
3932 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3933 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3936 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3937 EVT VT = Op.getValueType();
3940 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3941 if (VT.getVectorElementType() == MVT::f32)
3943 return DAG.UnrollVectorOp(Op.getNode());
3946 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3947 "Invalid type for custom lowering!");
3948 if (VT != MVT::v4f32)
3949 return DAG.UnrollVectorOp(Op.getNode());
3953 switch (Op.getOpcode()) {
3954 default: llvm_unreachable("Invalid opcode!");
3955 case ISD::SINT_TO_FP:
3956 CastOpc = ISD::SIGN_EXTEND;
3957 Opc = ISD::SINT_TO_FP;
3959 case ISD::UINT_TO_FP:
3960 CastOpc = ISD::ZERO_EXTEND;
3961 Opc = ISD::UINT_TO_FP;
3965 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3966 return DAG.getNode(Opc, dl, VT, Op);
3969 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3970 EVT VT = Op.getValueType();
3972 return LowerVectorINT_TO_FP(Op, DAG);
3974 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3976 if (Op.getOpcode() == ISD::SINT_TO_FP)
3977 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3980 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3982 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3983 /*isSigned*/ false, SDLoc(Op)).first;
3989 switch (Op.getOpcode()) {
3990 default: llvm_unreachable("Invalid opcode!");
3991 case ISD::SINT_TO_FP:
3992 Opc = ARMISD::SITOF;
3994 case ISD::UINT_TO_FP:
3995 Opc = ARMISD::UITOF;
3999 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
4000 return DAG.getNode(Opc, dl, VT, Op);
4003 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4004 // Implement fcopysign with a fabs and a conditional fneg.
4005 SDValue Tmp0 = Op.getOperand(0);
4006 SDValue Tmp1 = Op.getOperand(1);
4008 EVT VT = Op.getValueType();
4009 EVT SrcVT = Tmp1.getValueType();
4010 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4011 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4012 bool UseNEON = !InGPR && Subtarget->hasNEON();
4015 // Use VBSL to copy the sign bit.
4016 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4017 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4018 DAG.getTargetConstant(EncodedVal, MVT::i32));
4019 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4021 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4022 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4023 DAG.getConstant(32, MVT::i32));
4024 else /*if (VT == MVT::f32)*/
4025 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4026 if (SrcVT == MVT::f32) {
4027 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4029 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4030 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4031 DAG.getConstant(32, MVT::i32));
4032 } else if (VT == MVT::f32)
4033 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4034 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4035 DAG.getConstant(32, MVT::i32));
4036 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4037 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4039 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4041 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4042 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4043 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4045 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4046 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4047 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4048 if (VT == MVT::f32) {
4049 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4050 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4051 DAG.getConstant(0, MVT::i32));
4053 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4059 // Bitcast operand 1 to i32.
4060 if (SrcVT == MVT::f64)
4061 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4063 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4065 // Or in the signbit with integer operations.
4066 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4067 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4068 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4069 if (VT == MVT::f32) {
4070 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4071 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4072 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4073 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4076 // f64: Or the high part with signbit and then combine two parts.
4077 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4079 SDValue Lo = Tmp0.getValue(0);
4080 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4081 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4082 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4085 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4086 MachineFunction &MF = DAG.getMachineFunction();
4087 MachineFrameInfo *MFI = MF.getFrameInfo();
4088 MFI->setReturnAddressIsTaken(true);
4090 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4093 EVT VT = Op.getValueType();
4095 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4097 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4098 SDValue Offset = DAG.getConstant(4, MVT::i32);
4099 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4100 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4101 MachinePointerInfo(), false, false, false, 0);
4104 // Return LR, which contains the return address. Mark it an implicit live-in.
4105 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4106 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4109 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4110 const ARMBaseRegisterInfo &ARI =
4111 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4112 MachineFunction &MF = DAG.getMachineFunction();
4113 MachineFrameInfo *MFI = MF.getFrameInfo();
4114 MFI->setFrameAddressIsTaken(true);
4116 EVT VT = Op.getValueType();
4117 SDLoc dl(Op); // FIXME probably not meaningful
4118 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4119 unsigned FrameReg = ARI.getFrameRegister(MF);
4120 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4122 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4123 MachinePointerInfo(),
4124 false, false, false, 0);
4128 // FIXME? Maybe this could be a TableGen attribute on some registers and
4129 // this table could be generated automatically from RegInfo.
4130 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4132 unsigned Reg = StringSwitch<unsigned>(RegName)
4133 .Case("sp", ARM::SP)
4137 report_fatal_error("Invalid register name global variable");
4140 /// ExpandBITCAST - If the target supports VFP, this function is called to
4141 /// expand a bit convert where either the source or destination type is i64 to
4142 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4143 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4144 /// vectors), since the legalizer won't know what to do with that.
4145 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4146 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4148 SDValue Op = N->getOperand(0);
4150 // This function is only supposed to be called for i64 types, either as the
4151 // source or destination of the bit convert.
4152 EVT SrcVT = Op.getValueType();
4153 EVT DstVT = N->getValueType(0);
4154 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4155 "ExpandBITCAST called for non-i64 type");
4157 // Turn i64->f64 into VMOVDRR.
4158 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4159 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4160 DAG.getConstant(0, MVT::i32));
4161 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4162 DAG.getConstant(1, MVT::i32));
4163 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4164 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4167 // Turn f64->i64 into VMOVRRD.
4168 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4170 if (TLI.isBigEndian() && SrcVT.isVector() &&
4171 SrcVT.getVectorNumElements() > 1)
4172 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4173 DAG.getVTList(MVT::i32, MVT::i32),
4174 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4176 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4177 DAG.getVTList(MVT::i32, MVT::i32), Op);
4178 // Merge the pieces into a single i64 value.
4179 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4185 /// getZeroVector - Returns a vector of specified type with all zero elements.
4186 /// Zero vectors are used to represent vector negation and in those cases
4187 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4188 /// not support i64 elements, so sometimes the zero vectors will need to be
4189 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4191 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4192 assert(VT.isVector() && "Expected a vector type");
4193 // The canonical modified immediate encoding of a zero vector is....0!
4194 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4195 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4196 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4197 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4200 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4201 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4202 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4203 SelectionDAG &DAG) const {
4204 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4205 EVT VT = Op.getValueType();
4206 unsigned VTBits = VT.getSizeInBits();
4208 SDValue ShOpLo = Op.getOperand(0);
4209 SDValue ShOpHi = Op.getOperand(1);
4210 SDValue ShAmt = Op.getOperand(2);
4212 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4214 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4216 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4217 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4218 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4219 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4220 DAG.getConstant(VTBits, MVT::i32));
4221 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4222 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4223 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4225 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4226 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4228 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4229 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4232 SDValue Ops[2] = { Lo, Hi };
4233 return DAG.getMergeValues(Ops, dl);
4236 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4237 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4238 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4239 SelectionDAG &DAG) const {
4240 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4241 EVT VT = Op.getValueType();
4242 unsigned VTBits = VT.getSizeInBits();
4244 SDValue ShOpLo = Op.getOperand(0);
4245 SDValue ShOpHi = Op.getOperand(1);
4246 SDValue ShAmt = Op.getOperand(2);
4249 assert(Op.getOpcode() == ISD::SHL_PARTS);
4250 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4251 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4252 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4253 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4254 DAG.getConstant(VTBits, MVT::i32));
4255 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4256 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4258 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4259 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4260 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4262 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4263 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4266 SDValue Ops[2] = { Lo, Hi };
4267 return DAG.getMergeValues(Ops, dl);
4270 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4271 SelectionDAG &DAG) const {
4272 // The rounding mode is in bits 23:22 of the FPSCR.
4273 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4274 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4275 // so that the shift + and get folded into a bitfield extract.
4277 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4278 DAG.getConstant(Intrinsic::arm_get_fpscr,
4280 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4281 DAG.getConstant(1U << 22, MVT::i32));
4282 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4283 DAG.getConstant(22, MVT::i32));
4284 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4285 DAG.getConstant(3, MVT::i32));
4288 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4289 const ARMSubtarget *ST) {
4290 EVT VT = N->getValueType(0);
4293 if (!ST->hasV6T2Ops())
4296 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4297 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4300 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4301 /// for each 16-bit element from operand, repeated. The basic idea is to
4302 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4304 /// Trace for v4i16:
4305 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4306 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4307 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4308 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4309 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4310 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4311 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4312 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4313 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4314 EVT VT = N->getValueType(0);
4317 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4318 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4319 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4320 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4321 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4322 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4325 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4326 /// bit-count for each 16-bit element from the operand. We need slightly
4327 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4328 /// 64/128-bit registers.
4330 /// Trace for v4i16:
4331 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4332 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4333 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4334 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4335 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4336 EVT VT = N->getValueType(0);
4339 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4340 if (VT.is64BitVector()) {
4341 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4342 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4343 DAG.getIntPtrConstant(0));
4345 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4346 BitCounts, DAG.getIntPtrConstant(0));
4347 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4351 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4352 /// bit-count for each 32-bit element from the operand. The idea here is
4353 /// to split the vector into 16-bit elements, leverage the 16-bit count
4354 /// routine, and then combine the results.
4356 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4357 /// input = [v0 v1 ] (vi: 32-bit elements)
4358 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4359 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4360 /// vrev: N0 = [k1 k0 k3 k2 ]
4362 /// N1 =+[k1 k0 k3 k2 ]
4364 /// N2 =+[k1 k3 k0 k2 ]
4366 /// Extended =+[k1 k3 k0 k2 ]
4368 /// Extracted=+[k1 k3 ]
4370 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4371 EVT VT = N->getValueType(0);
4374 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4376 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4377 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4378 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4379 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4380 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4382 if (VT.is64BitVector()) {
4383 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4384 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4385 DAG.getIntPtrConstant(0));
4387 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4388 DAG.getIntPtrConstant(0));
4389 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4393 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4394 const ARMSubtarget *ST) {
4395 EVT VT = N->getValueType(0);
4397 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4398 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4399 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4400 "Unexpected type for custom ctpop lowering");
4402 if (VT.getVectorElementType() == MVT::i32)
4403 return lowerCTPOP32BitElements(N, DAG);
4405 return lowerCTPOP16BitElements(N, DAG);
4408 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4409 const ARMSubtarget *ST) {
4410 EVT VT = N->getValueType(0);
4416 // Lower vector shifts on NEON to use VSHL.
4417 assert(ST->hasNEON() && "unexpected vector shift");
4419 // Left shifts translate directly to the vshiftu intrinsic.
4420 if (N->getOpcode() == ISD::SHL)
4421 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4422 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4423 N->getOperand(0), N->getOperand(1));
4425 assert((N->getOpcode() == ISD::SRA ||
4426 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4428 // NEON uses the same intrinsics for both left and right shifts. For
4429 // right shifts, the shift amounts are negative, so negate the vector of
4431 EVT ShiftVT = N->getOperand(1).getValueType();
4432 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4433 getZeroVector(ShiftVT, DAG, dl),
4435 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4436 Intrinsic::arm_neon_vshifts :
4437 Intrinsic::arm_neon_vshiftu);
4438 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4439 DAG.getConstant(vshiftInt, MVT::i32),
4440 N->getOperand(0), NegatedCount);
4443 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4444 const ARMSubtarget *ST) {
4445 EVT VT = N->getValueType(0);
4448 // We can get here for a node like i32 = ISD::SHL i32, i64
4452 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4453 "Unknown shift to lower!");
4455 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4456 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4457 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4460 // If we are in thumb mode, we don't have RRX.
4461 if (ST->isThumb1Only()) return SDValue();
4463 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4464 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4465 DAG.getConstant(0, MVT::i32));
4466 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4467 DAG.getConstant(1, MVT::i32));
4469 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4470 // captures the result into a carry flag.
4471 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4472 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4474 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4475 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4477 // Merge the pieces into a single i64 value.
4478 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4481 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4482 SDValue TmpOp0, TmpOp1;
4483 bool Invert = false;
4487 SDValue Op0 = Op.getOperand(0);
4488 SDValue Op1 = Op.getOperand(1);
4489 SDValue CC = Op.getOperand(2);
4490 EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4491 EVT VT = Op.getValueType();
4492 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4495 if (Op1.getValueType().isFloatingPoint()) {
4496 switch (SetCCOpcode) {
4497 default: llvm_unreachable("Illegal FP comparison");
4499 case ISD::SETNE: Invert = true; // Fallthrough
4501 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4503 case ISD::SETLT: Swap = true; // Fallthrough
4505 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4507 case ISD::SETLE: Swap = true; // Fallthrough
4509 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4510 case ISD::SETUGE: Swap = true; // Fallthrough
4511 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4512 case ISD::SETUGT: Swap = true; // Fallthrough
4513 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4514 case ISD::SETUEQ: Invert = true; // Fallthrough
4516 // Expand this to (OLT | OGT).
4520 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4521 Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4523 case ISD::SETUO: Invert = true; // Fallthrough
4525 // Expand this to (OLT | OGE).
4529 Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4530 Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4534 // Integer comparisons.
4535 switch (SetCCOpcode) {
4536 default: llvm_unreachable("Illegal integer comparison");
4537 case ISD::SETNE: Invert = true;
4538 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4539 case ISD::SETLT: Swap = true;
4540 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4541 case ISD::SETLE: Swap = true;
4542 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4543 case ISD::SETULT: Swap = true;
4544 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4545 case ISD::SETULE: Swap = true;
4546 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4549 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4550 if (Opc == ARMISD::VCEQ) {
4553 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4555 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4558 // Ignore bitconvert.
4559 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4560 AndOp = AndOp.getOperand(0);
4562 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4564 Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4565 Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4572 std::swap(Op0, Op1);
4574 // If one of the operands is a constant vector zero, attempt to fold the
4575 // comparison to a specialized compare-against-zero form.
4577 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4579 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4580 if (Opc == ARMISD::VCGE)
4581 Opc = ARMISD::VCLEZ;
4582 else if (Opc == ARMISD::VCGT)
4583 Opc = ARMISD::VCLTZ;
4588 if (SingleOp.getNode()) {
4591 Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4593 Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4595 Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4597 Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4599 Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4601 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4604 Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4607 Result = DAG.getSExtOrTrunc(Result, dl, VT);
4610 Result = DAG.getNOT(dl, Result, VT);
4615 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4616 /// valid vector constant for a NEON instruction with a "modified immediate"
4617 /// operand (e.g., VMOV). If so, return the encoded value.
4618 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4619 unsigned SplatBitSize, SelectionDAG &DAG,
4620 EVT &VT, bool is128Bits, NEONModImmType type) {
4621 unsigned OpCmode, Imm;
4623 // SplatBitSize is set to the smallest size that splats the vector, so a
4624 // zero vector will always have SplatBitSize == 8. However, NEON modified
4625 // immediate instructions others than VMOV do not support the 8-bit encoding
4626 // of a zero vector, and the default encoding of zero is supposed to be the
4631 switch (SplatBitSize) {
4633 if (type != VMOVModImm)
4635 // Any 1-byte value is OK. Op=0, Cmode=1110.
4636 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4639 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4643 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4644 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4645 if ((SplatBits & ~0xff) == 0) {
4646 // Value = 0x00nn: Op=x, Cmode=100x.
4651 if ((SplatBits & ~0xff00) == 0) {
4652 // Value = 0xnn00: Op=x, Cmode=101x.
4654 Imm = SplatBits >> 8;
4660 // NEON's 32-bit VMOV supports splat values where:
4661 // * only one byte is nonzero, or
4662 // * the least significant byte is 0xff and the second byte is nonzero, or
4663 // * the least significant 2 bytes are 0xff and the third is nonzero.
4664 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4665 if ((SplatBits & ~0xff) == 0) {
4666 // Value = 0x000000nn: Op=x, Cmode=000x.
4671 if ((SplatBits & ~0xff00) == 0) {
4672 // Value = 0x0000nn00: Op=x, Cmode=001x.
4674 Imm = SplatBits >> 8;
4677 if ((SplatBits & ~0xff0000) == 0) {
4678 // Value = 0x00nn0000: Op=x, Cmode=010x.
4680 Imm = SplatBits >> 16;
4683 if ((SplatBits & ~0xff000000) == 0) {
4684 // Value = 0xnn000000: Op=x, Cmode=011x.
4686 Imm = SplatBits >> 24;
4690 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4691 if (type == OtherModImm) return SDValue();
4693 if ((SplatBits & ~0xffff) == 0 &&
4694 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4695 // Value = 0x0000nnff: Op=x, Cmode=1100.
4697 Imm = SplatBits >> 8;
4701 if ((SplatBits & ~0xffffff) == 0 &&
4702 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4703 // Value = 0x00nnffff: Op=x, Cmode=1101.
4705 Imm = SplatBits >> 16;
4709 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4710 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4711 // VMOV.I32. A (very) minor optimization would be to replicate the value
4712 // and fall through here to test for a valid 64-bit splat. But, then the
4713 // caller would also need to check and handle the change in size.
4717 if (type != VMOVModImm)
4719 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4720 uint64_t BitMask = 0xff;
4722 unsigned ImmMask = 1;
4724 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4725 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4728 } else if ((SplatBits & BitMask) != 0) {
4735 if (DAG.getTargetLoweringInfo().isBigEndian())
4736 // swap higher and lower 32 bit word
4737 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4739 // Op=1, Cmode=1110.
4741 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4746 llvm_unreachable("unexpected size for isNEONModifiedImm");
4749 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4750 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4753 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4754 const ARMSubtarget *ST) const {
4758 bool IsDouble = Op.getValueType() == MVT::f64;
4759 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4761 // Use the default (constant pool) lowering for double constants when we have
4763 if (IsDouble && Subtarget->isFPOnlySP())
4766 // Try splatting with a VMOV.f32...
4767 APFloat FPVal = CFP->getValueAPF();
4768 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4771 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4772 // We have code in place to select a valid ConstantFP already, no need to
4777 // It's a float and we are trying to use NEON operations where
4778 // possible. Lower it to a splat followed by an extract.
4780 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4781 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4783 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4784 DAG.getConstant(0, MVT::i32));
4787 // The rest of our options are NEON only, make sure that's allowed before
4789 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4793 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4795 // It wouldn't really be worth bothering for doubles except for one very
4796 // important value, which does happen to match: 0.0. So make sure we don't do
4798 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4801 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4802 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4804 if (NewVal != SDValue()) {
4806 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4809 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4811 // It's a float: cast and extract a vector element.
4812 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4814 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4815 DAG.getConstant(0, MVT::i32));
4818 // Finally, try a VMVN.i32
4819 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4821 if (NewVal != SDValue()) {
4823 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4826 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4828 // It's a float: cast and extract a vector element.
4829 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4831 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4832 DAG.getConstant(0, MVT::i32));
4838 // check if an VEXT instruction can handle the shuffle mask when the
4839 // vector sources of the shuffle are the same.
4840 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4841 unsigned NumElts = VT.getVectorNumElements();
4843 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4849 // If this is a VEXT shuffle, the immediate value is the index of the first
4850 // element. The other shuffle indices must be the successive elements after
4852 unsigned ExpectedElt = Imm;
4853 for (unsigned i = 1; i < NumElts; ++i) {
4854 // Increment the expected index. If it wraps around, just follow it
4855 // back to index zero and keep going.
4857 if (ExpectedElt == NumElts)
4860 if (M[i] < 0) continue; // ignore UNDEF indices
4861 if (ExpectedElt != static_cast<unsigned>(M[i]))
4869 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4870 bool &ReverseVEXT, unsigned &Imm) {
4871 unsigned NumElts = VT.getVectorNumElements();
4872 ReverseVEXT = false;
4874 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4880 // If this is a VEXT shuffle, the immediate value is the index of the first
4881 // element. The other shuffle indices must be the successive elements after
4883 unsigned ExpectedElt = Imm;
4884 for (unsigned i = 1; i < NumElts; ++i) {
4885 // Increment the expected index. If it wraps around, it may still be
4886 // a VEXT but the source vectors must be swapped.
4888 if (ExpectedElt == NumElts * 2) {
4893 if (M[i] < 0) continue; // ignore UNDEF indices
4894 if (ExpectedElt != static_cast<unsigned>(M[i]))
4898 // Adjust the index value if the source operands will be swapped.
4905 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4906 /// instruction with the specified blocksize. (The order of the elements
4907 /// within each block of the vector is reversed.)
4908 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4909 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4910 "Only possible block sizes for VREV are: 16, 32, 64");
4912 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4916 unsigned NumElts = VT.getVectorNumElements();
4917 unsigned BlockElts = M[0] + 1;
4918 // If the first shuffle index is UNDEF, be optimistic.
4920 BlockElts = BlockSize / EltSz;
4922 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4925 for (unsigned i = 0; i < NumElts; ++i) {
4926 if (M[i] < 0) continue; // ignore UNDEF indices
4927 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4934 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4935 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4936 // range, then 0 is placed into the resulting vector. So pretty much any mask
4937 // of 8 elements can work here.
4938 return VT == MVT::v8i8 && M.size() == 8;
4941 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4942 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4946 unsigned NumElts = VT.getVectorNumElements();
4947 WhichResult = (M[0] == 0 ? 0 : 1);
4948 for (unsigned i = 0; i < NumElts; i += 2) {
4949 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4950 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4956 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4957 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4958 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4959 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4960 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4964 unsigned NumElts = VT.getVectorNumElements();
4965 WhichResult = (M[0] == 0 ? 0 : 1);
4966 for (unsigned i = 0; i < NumElts; i += 2) {
4967 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4968 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4974 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4975 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4979 unsigned NumElts = VT.getVectorNumElements();
4980 WhichResult = (M[0] == 0 ? 0 : 1);
4981 for (unsigned i = 0; i != NumElts; ++i) {
4982 if (M[i] < 0) continue; // ignore UNDEF indices
4983 if ((unsigned) M[i] != 2 * i + WhichResult)
4987 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4988 if (VT.is64BitVector() && EltSz == 32)
4994 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4995 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4996 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4997 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4998 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5002 unsigned Half = VT.getVectorNumElements() / 2;
5003 WhichResult = (M[0] == 0 ? 0 : 1);
5004 for (unsigned j = 0; j != 2; ++j) {
5005 unsigned Idx = WhichResult;
5006 for (unsigned i = 0; i != Half; ++i) {
5007 int MIdx = M[i + j * Half];
5008 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5014 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5015 if (VT.is64BitVector() && EltSz == 32)
5021 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5022 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5026 unsigned NumElts = VT.getVectorNumElements();
5027 WhichResult = (M[0] == 0 ? 0 : 1);
5028 unsigned Idx = WhichResult * NumElts / 2;
5029 for (unsigned i = 0; i != NumElts; i += 2) {
5030 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5031 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5036 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5037 if (VT.is64BitVector() && EltSz == 32)
5043 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5044 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5045 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5046 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5047 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5051 unsigned NumElts = VT.getVectorNumElements();
5052 WhichResult = (M[0] == 0 ? 0 : 1);
5053 unsigned Idx = WhichResult * NumElts / 2;
5054 for (unsigned i = 0; i != NumElts; i += 2) {
5055 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5056 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5061 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5062 if (VT.is64BitVector() && EltSz == 32)
5068 /// \return true if this is a reverse operation on an vector.
5069 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5070 unsigned NumElts = VT.getVectorNumElements();
5071 // Make sure the mask has the right size.
5072 if (NumElts != M.size())
5075 // Look for <15, ..., 3, -1, 1, 0>.
5076 for (unsigned i = 0; i != NumElts; ++i)
5077 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5083 // If N is an integer constant that can be moved into a register in one
5084 // instruction, return an SDValue of such a constant (will become a MOV
5085 // instruction). Otherwise return null.
5086 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5087 const ARMSubtarget *ST, SDLoc dl) {
5089 if (!isa<ConstantSDNode>(N))
5091 Val = cast<ConstantSDNode>(N)->getZExtValue();
5093 if (ST->isThumb1Only()) {
5094 if (Val <= 255 || ~Val <= 255)
5095 return DAG.getConstant(Val, MVT::i32);
5097 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5098 return DAG.getConstant(Val, MVT::i32);
5103 // If this is a case we can't handle, return null and let the default
5104 // expansion code take care of it.
5105 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5106 const ARMSubtarget *ST) const {
5107 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5109 EVT VT = Op.getValueType();
5111 APInt SplatBits, SplatUndef;
5112 unsigned SplatBitSize;
5114 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5115 if (SplatBitSize <= 64) {
5116 // Check if an immediate VMOV works.
5118 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5119 SplatUndef.getZExtValue(), SplatBitSize,
5120 DAG, VmovVT, VT.is128BitVector(),
5122 if (Val.getNode()) {
5123 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5124 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5127 // Try an immediate VMVN.
5128 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5129 Val = isNEONModifiedImm(NegatedImm,
5130 SplatUndef.getZExtValue(), SplatBitSize,
5131 DAG, VmovVT, VT.is128BitVector(),
5133 if (Val.getNode()) {
5134 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5135 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5138 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5139 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5140 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5142 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5143 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5149 // Scan through the operands to see if only one value is used.
5151 // As an optimisation, even if more than one value is used it may be more
5152 // profitable to splat with one value then change some lanes.
5154 // Heuristically we decide to do this if the vector has a "dominant" value,
5155 // defined as splatted to more than half of the lanes.
5156 unsigned NumElts = VT.getVectorNumElements();
5157 bool isOnlyLowElement = true;
5158 bool usesOnlyOneValue = true;
5159 bool hasDominantValue = false;
5160 bool isConstant = true;
5162 // Map of the number of times a particular SDValue appears in the
5164 DenseMap<SDValue, unsigned> ValueCounts;
5166 for (unsigned i = 0; i < NumElts; ++i) {
5167 SDValue V = Op.getOperand(i);
5168 if (V.getOpcode() == ISD::UNDEF)
5171 isOnlyLowElement = false;
5172 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5175 ValueCounts.insert(std::make_pair(V, 0));
5176 unsigned &Count = ValueCounts[V];
5178 // Is this value dominant? (takes up more than half of the lanes)
5179 if (++Count > (NumElts / 2)) {
5180 hasDominantValue = true;
5184 if (ValueCounts.size() != 1)
5185 usesOnlyOneValue = false;
5186 if (!Value.getNode() && ValueCounts.size() > 0)
5187 Value = ValueCounts.begin()->first;
5189 if (ValueCounts.size() == 0)
5190 return DAG.getUNDEF(VT);
5192 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5193 // Keep going if we are hitting this case.
5194 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5195 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5197 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5199 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5200 // i32 and try again.
5201 if (hasDominantValue && EltSize <= 32) {
5205 // If we are VDUPing a value that comes directly from a vector, that will
5206 // cause an unnecessary move to and from a GPR, where instead we could
5207 // just use VDUPLANE. We can only do this if the lane being extracted
5208 // is at a constant index, as the VDUP from lane instructions only have
5209 // constant-index forms.
5210 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5211 isa<ConstantSDNode>(Value->getOperand(1))) {
5212 // We need to create a new undef vector to use for the VDUPLANE if the
5213 // size of the vector from which we get the value is different than the
5214 // size of the vector that we need to create. We will insert the element
5215 // such that the register coalescer will remove unnecessary copies.
5216 if (VT != Value->getOperand(0).getValueType()) {
5217 ConstantSDNode *constIndex;
5218 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5219 assert(constIndex && "The index is not a constant!");
5220 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5221 VT.getVectorNumElements();
5222 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5223 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5224 Value, DAG.getConstant(index, MVT::i32)),
5225 DAG.getConstant(index, MVT::i32));
5227 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5228 Value->getOperand(0), Value->getOperand(1));
5230 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5232 if (!usesOnlyOneValue) {
5233 // The dominant value was splatted as 'N', but we now have to insert
5234 // all differing elements.
5235 for (unsigned I = 0; I < NumElts; ++I) {
5236 if (Op.getOperand(I) == Value)
5238 SmallVector<SDValue, 3> Ops;
5240 Ops.push_back(Op.getOperand(I));
5241 Ops.push_back(DAG.getConstant(I, MVT::i32));
5242 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5247 if (VT.getVectorElementType().isFloatingPoint()) {
5248 SmallVector<SDValue, 8> Ops;
5249 for (unsigned i = 0; i < NumElts; ++i)
5250 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5252 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5253 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5254 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5256 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5258 if (usesOnlyOneValue) {
5259 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5260 if (isConstant && Val.getNode())
5261 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5265 // If all elements are constants and the case above didn't get hit, fall back
5266 // to the default expansion, which will generate a load from the constant
5271 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5273 SDValue shuffle = ReconstructShuffle(Op, DAG);
5274 if (shuffle != SDValue())
5278 // Vectors with 32- or 64-bit elements can be built by directly assigning
5279 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5280 // will be legalized.
5281 if (EltSize >= 32) {
5282 // Do the expansion with floating-point types, since that is what the VFP
5283 // registers are defined to use, and since i64 is not legal.
5284 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5285 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5286 SmallVector<SDValue, 8> Ops;
5287 for (unsigned i = 0; i < NumElts; ++i)
5288 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5289 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5290 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5293 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5294 // know the default expansion would otherwise fall back on something even
5295 // worse. For a vector with one or two non-undef values, that's
5296 // scalar_to_vector for the elements followed by a shuffle (provided the
5297 // shuffle is valid for the target) and materialization element by element
5298 // on the stack followed by a load for everything else.
5299 if (!isConstant && !usesOnlyOneValue) {
5300 SDValue Vec = DAG.getUNDEF(VT);
5301 for (unsigned i = 0 ; i < NumElts; ++i) {
5302 SDValue V = Op.getOperand(i);
5303 if (V.getOpcode() == ISD::UNDEF)
5305 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5306 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5314 // Gather data to see if the operation can be modelled as a
5315 // shuffle in combination with VEXTs.
5316 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5317 SelectionDAG &DAG) const {
5319 EVT VT = Op.getValueType();
5320 unsigned NumElts = VT.getVectorNumElements();
5322 SmallVector<SDValue, 2> SourceVecs;
5323 SmallVector<unsigned, 2> MinElts;
5324 SmallVector<unsigned, 2> MaxElts;
5326 for (unsigned i = 0; i < NumElts; ++i) {
5327 SDValue V = Op.getOperand(i);
5328 if (V.getOpcode() == ISD::UNDEF)
5330 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5331 // A shuffle can only come from building a vector from various
5332 // elements of other vectors.
5334 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5335 VT.getVectorElementType()) {
5336 // This code doesn't know how to handle shuffles where the vector
5337 // element types do not match (this happens because type legalization
5338 // promotes the return type of EXTRACT_VECTOR_ELT).
5339 // FIXME: It might be appropriate to extend this code to handle
5340 // mismatched types.
5344 // Record this extraction against the appropriate vector if possible...
5345 SDValue SourceVec = V.getOperand(0);
5346 // If the element number isn't a constant, we can't effectively
5347 // analyze what's going on.
5348 if (!isa<ConstantSDNode>(V.getOperand(1)))
5350 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5351 bool FoundSource = false;
5352 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5353 if (SourceVecs[j] == SourceVec) {
5354 if (MinElts[j] > EltNo)
5356 if (MaxElts[j] < EltNo)
5363 // Or record a new source if not...
5365 SourceVecs.push_back(SourceVec);
5366 MinElts.push_back(EltNo);
5367 MaxElts.push_back(EltNo);
5371 // Currently only do something sane when at most two source vectors
5373 if (SourceVecs.size() > 2)
5376 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5377 int VEXTOffsets[2] = {0, 0};
5379 // This loop extracts the usage patterns of the source vectors
5380 // and prepares appropriate SDValues for a shuffle if possible.
5381 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5382 if (SourceVecs[i].getValueType() == VT) {
5383 // No VEXT necessary
5384 ShuffleSrcs[i] = SourceVecs[i];
5387 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5388 // It probably isn't worth padding out a smaller vector just to
5389 // break it down again in a shuffle.
5393 // Since only 64-bit and 128-bit vectors are legal on ARM and
5394 // we've eliminated the other cases...
5395 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5396 "unexpected vector sizes in ReconstructShuffle");
5398 if (MaxElts[i] - MinElts[i] >= NumElts) {
5399 // Span too large for a VEXT to cope
5403 if (MinElts[i] >= NumElts) {
5404 // The extraction can just take the second half
5405 VEXTOffsets[i] = NumElts;
5406 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5408 DAG.getIntPtrConstant(NumElts));
5409 } else if (MaxElts[i] < NumElts) {
5410 // The extraction can just take the first half
5412 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5414 DAG.getIntPtrConstant(0));
5416 // An actual VEXT is needed
5417 VEXTOffsets[i] = MinElts[i];
5418 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5420 DAG.getIntPtrConstant(0));
5421 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5423 DAG.getIntPtrConstant(NumElts));
5424 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5425 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5429 SmallVector<int, 8> Mask;
5431 for (unsigned i = 0; i < NumElts; ++i) {
5432 SDValue Entry = Op.getOperand(i);
5433 if (Entry.getOpcode() == ISD::UNDEF) {
5438 SDValue ExtractVec = Entry.getOperand(0);
5439 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5440 .getOperand(1))->getSExtValue();
5441 if (ExtractVec == SourceVecs[0]) {
5442 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5444 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5448 // Final check before we try to produce nonsense...
5449 if (isShuffleMaskLegal(Mask, VT))
5450 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5456 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5457 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5458 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5459 /// are assumed to be legal.
5461 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5463 if (VT.getVectorNumElements() == 4 &&
5464 (VT.is128BitVector() || VT.is64BitVector())) {
5465 unsigned PFIndexes[4];
5466 for (unsigned i = 0; i != 4; ++i) {
5470 PFIndexes[i] = M[i];
5473 // Compute the index in the perfect shuffle table.
5474 unsigned PFTableIndex =
5475 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5476 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5477 unsigned Cost = (PFEntry >> 30);
5484 unsigned Imm, WhichResult;
5486 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5487 return (EltSize >= 32 ||
5488 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5489 isVREVMask(M, VT, 64) ||
5490 isVREVMask(M, VT, 32) ||
5491 isVREVMask(M, VT, 16) ||
5492 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5493 isVTBLMask(M, VT) ||
5494 isVTRNMask(M, VT, WhichResult) ||
5495 isVUZPMask(M, VT, WhichResult) ||
5496 isVZIPMask(M, VT, WhichResult) ||
5497 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5498 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5499 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5500 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5503 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5504 /// the specified operations to build the shuffle.
5505 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5506 SDValue RHS, SelectionDAG &DAG,
5508 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5509 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5510 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5513 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5522 OP_VUZPL, // VUZP, left result
5523 OP_VUZPR, // VUZP, right result
5524 OP_VZIPL, // VZIP, left result
5525 OP_VZIPR, // VZIP, right result
5526 OP_VTRNL, // VTRN, left result
5527 OP_VTRNR // VTRN, right result
5530 if (OpNum == OP_COPY) {
5531 if (LHSID == (1*9+2)*9+3) return LHS;
5532 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5536 SDValue OpLHS, OpRHS;
5537 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5538 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5539 EVT VT = OpLHS.getValueType();
5542 default: llvm_unreachable("Unknown shuffle opcode!");
5544 // VREV divides the vector in half and swaps within the half.
5545 if (VT.getVectorElementType() == MVT::i32 ||
5546 VT.getVectorElementType() == MVT::f32)
5547 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5548 // vrev <4 x i16> -> VREV32
5549 if (VT.getVectorElementType() == MVT::i16)
5550 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5551 // vrev <4 x i8> -> VREV16
5552 assert(VT.getVectorElementType() == MVT::i8);
5553 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5558 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5559 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5563 return DAG.getNode(ARMISD::VEXT, dl, VT,
5565 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5568 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5569 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5572 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5573 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5576 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5577 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5581 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5582 ArrayRef<int> ShuffleMask,
5583 SelectionDAG &DAG) {
5584 // Check to see if we can use the VTBL instruction.
5585 SDValue V1 = Op.getOperand(0);
5586 SDValue V2 = Op.getOperand(1);
5589 SmallVector<SDValue, 8> VTBLMask;
5590 for (ArrayRef<int>::iterator
5591 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5592 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5594 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5595 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5596 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5598 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5599 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5602 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5603 SelectionDAG &DAG) {
5605 SDValue OpLHS = Op.getOperand(0);
5606 EVT VT = OpLHS.getValueType();
5608 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5609 "Expect an v8i16/v16i8 type");
5610 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5611 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5612 // extract the first 8 bytes into the top double word and the last 8 bytes
5613 // into the bottom double word. The v8i16 case is similar.
5614 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5615 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5616 DAG.getConstant(ExtractNum, MVT::i32));
5619 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5620 SDValue V1 = Op.getOperand(0);
5621 SDValue V2 = Op.getOperand(1);
5623 EVT VT = Op.getValueType();
5624 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5626 // Convert shuffles that are directly supported on NEON to target-specific
5627 // DAG nodes, instead of keeping them as shuffles and matching them again
5628 // during code selection. This is more efficient and avoids the possibility
5629 // of inconsistencies between legalization and selection.
5630 // FIXME: floating-point vectors should be canonicalized to integer vectors
5631 // of the same time so that they get CSEd properly.
5632 ArrayRef<int> ShuffleMask = SVN->getMask();
5634 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5635 if (EltSize <= 32) {
5636 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5637 int Lane = SVN->getSplatIndex();
5638 // If this is undef splat, generate it via "just" vdup, if possible.
5639 if (Lane == -1) Lane = 0;
5641 // Test if V1 is a SCALAR_TO_VECTOR.
5642 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5643 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5645 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5646 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5648 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5649 !isa<ConstantSDNode>(V1.getOperand(0))) {
5650 bool IsScalarToVector = true;
5651 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5652 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5653 IsScalarToVector = false;
5656 if (IsScalarToVector)
5657 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5659 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5660 DAG.getConstant(Lane, MVT::i32));
5665 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5668 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5669 DAG.getConstant(Imm, MVT::i32));
5672 if (isVREVMask(ShuffleMask, VT, 64))
5673 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5674 if (isVREVMask(ShuffleMask, VT, 32))
5675 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5676 if (isVREVMask(ShuffleMask, VT, 16))
5677 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5679 if (V2->getOpcode() == ISD::UNDEF &&
5680 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5681 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5682 DAG.getConstant(Imm, MVT::i32));
5685 // Check for Neon shuffles that modify both input vectors in place.
5686 // If both results are used, i.e., if there are two shuffles with the same
5687 // source operands and with masks corresponding to both results of one of
5688 // these operations, DAG memoization will ensure that a single node is
5689 // used for both shuffles.
5690 unsigned WhichResult;
5691 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5692 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5693 V1, V2).getValue(WhichResult);
5694 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5695 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5696 V1, V2).getValue(WhichResult);
5697 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5698 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5699 V1, V2).getValue(WhichResult);
5701 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5702 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5703 V1, V1).getValue(WhichResult);
5704 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5705 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5706 V1, V1).getValue(WhichResult);
5707 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5708 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5709 V1, V1).getValue(WhichResult);
5712 // If the shuffle is not directly supported and it has 4 elements, use
5713 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5714 unsigned NumElts = VT.getVectorNumElements();
5716 unsigned PFIndexes[4];
5717 for (unsigned i = 0; i != 4; ++i) {
5718 if (ShuffleMask[i] < 0)
5721 PFIndexes[i] = ShuffleMask[i];
5724 // Compute the index in the perfect shuffle table.
5725 unsigned PFTableIndex =
5726 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5727 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5728 unsigned Cost = (PFEntry >> 30);
5731 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5734 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5735 if (EltSize >= 32) {
5736 // Do the expansion with floating-point types, since that is what the VFP
5737 // registers are defined to use, and since i64 is not legal.
5738 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5739 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5740 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5741 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5742 SmallVector<SDValue, 8> Ops;
5743 for (unsigned i = 0; i < NumElts; ++i) {
5744 if (ShuffleMask[i] < 0)
5745 Ops.push_back(DAG.getUNDEF(EltVT));
5747 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5748 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5749 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5752 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5753 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5756 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5757 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5759 if (VT == MVT::v8i8) {
5760 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5761 if (NewOp.getNode())
5768 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5769 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5770 SDValue Lane = Op.getOperand(2);
5771 if (!isa<ConstantSDNode>(Lane))
5777 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5778 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5779 SDValue Lane = Op.getOperand(1);
5780 if (!isa<ConstantSDNode>(Lane))
5783 SDValue Vec = Op.getOperand(0);
5784 if (Op.getValueType() == MVT::i32 &&
5785 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5787 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5793 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5794 // The only time a CONCAT_VECTORS operation can have legal types is when
5795 // two 64-bit vectors are concatenated to a 128-bit vector.
5796 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5797 "unexpected CONCAT_VECTORS");
5799 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5800 SDValue Op0 = Op.getOperand(0);
5801 SDValue Op1 = Op.getOperand(1);
5802 if (Op0.getOpcode() != ISD::UNDEF)
5803 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5804 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5805 DAG.getIntPtrConstant(0));
5806 if (Op1.getOpcode() != ISD::UNDEF)
5807 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5808 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5809 DAG.getIntPtrConstant(1));
5810 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5813 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5814 /// element has been zero/sign-extended, depending on the isSigned parameter,
5815 /// from an integer type half its size.
5816 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5818 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5819 EVT VT = N->getValueType(0);
5820 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5821 SDNode *BVN = N->getOperand(0).getNode();
5822 if (BVN->getValueType(0) != MVT::v4i32 ||
5823 BVN->getOpcode() != ISD::BUILD_VECTOR)
5825 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5826 unsigned HiElt = 1 - LoElt;
5827 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5828 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5829 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5830 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5831 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5834 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5835 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5838 if (Hi0->isNullValue() && Hi1->isNullValue())
5844 if (N->getOpcode() != ISD::BUILD_VECTOR)
5847 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5848 SDNode *Elt = N->getOperand(i).getNode();
5849 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5850 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5851 unsigned HalfSize = EltSize / 2;
5853 if (!isIntN(HalfSize, C->getSExtValue()))
5856 if (!isUIntN(HalfSize, C->getZExtValue()))
5867 /// isSignExtended - Check if a node is a vector value that is sign-extended
5868 /// or a constant BUILD_VECTOR with sign-extended elements.
5869 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5870 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5872 if (isExtendedBUILD_VECTOR(N, DAG, true))
5877 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5878 /// or a constant BUILD_VECTOR with zero-extended elements.
5879 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5880 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5882 if (isExtendedBUILD_VECTOR(N, DAG, false))
5887 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5888 if (OrigVT.getSizeInBits() >= 64)
5891 assert(OrigVT.isSimple() && "Expecting a simple value type");
5893 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5894 switch (OrigSimpleTy) {
5895 default: llvm_unreachable("Unexpected Vector Type");
5904 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5905 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5906 /// We insert the required extension here to get the vector to fill a D register.
5907 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5910 unsigned ExtOpcode) {
5911 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5912 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5913 // 64-bits we need to insert a new extension so that it will be 64-bits.
5914 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5915 if (OrigTy.getSizeInBits() >= 64)
5918 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5919 EVT NewVT = getExtensionTo64Bits(OrigTy);
5921 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5924 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5925 /// does not do any sign/zero extension. If the original vector is less
5926 /// than 64 bits, an appropriate extension will be added after the load to
5927 /// reach a total size of 64 bits. We have to add the extension separately
5928 /// because ARM does not have a sign/zero extending load for vectors.
5929 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5930 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5932 // The load already has the right type.
5933 if (ExtendedTy == LD->getMemoryVT())
5934 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5935 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5936 LD->isNonTemporal(), LD->isInvariant(),
5937 LD->getAlignment());
5939 // We need to create a zextload/sextload. We cannot just create a load
5940 // followed by a zext/zext node because LowerMUL is also run during normal
5941 // operation legalization where we can't create illegal types.
5942 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5943 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5944 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5945 LD->isNonTemporal(), LD->getAlignment());
5948 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5949 /// extending load, or BUILD_VECTOR with extended elements, return the
5950 /// unextended value. The unextended vector should be 64 bits so that it can
5951 /// be used as an operand to a VMULL instruction. If the original vector size
5952 /// before extension is less than 64 bits we add a an extension to resize
5953 /// the vector to 64 bits.
5954 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5955 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5956 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5957 N->getOperand(0)->getValueType(0),
5961 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5962 return SkipLoadExtensionForVMULL(LD, DAG);
5964 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5965 // have been legalized as a BITCAST from v4i32.
5966 if (N->getOpcode() == ISD::BITCAST) {
5967 SDNode *BVN = N->getOperand(0).getNode();
5968 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5969 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5970 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5971 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5972 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5974 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5975 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5976 EVT VT = N->getValueType(0);
5977 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5978 unsigned NumElts = VT.getVectorNumElements();
5979 MVT TruncVT = MVT::getIntegerVT(EltSize);
5980 SmallVector<SDValue, 8> Ops;
5981 for (unsigned i = 0; i != NumElts; ++i) {
5982 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5983 const APInt &CInt = C->getAPIntValue();
5984 // Element types smaller than 32 bits are not legal, so use i32 elements.
5985 // The values are implicitly truncated so sext vs. zext doesn't matter.
5986 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5988 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5989 MVT::getVectorVT(TruncVT, NumElts), Ops);
5992 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5993 unsigned Opcode = N->getOpcode();
5994 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5995 SDNode *N0 = N->getOperand(0).getNode();
5996 SDNode *N1 = N->getOperand(1).getNode();
5997 return N0->hasOneUse() && N1->hasOneUse() &&
5998 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6003 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6004 unsigned Opcode = N->getOpcode();
6005 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6006 SDNode *N0 = N->getOperand(0).getNode();
6007 SDNode *N1 = N->getOperand(1).getNode();
6008 return N0->hasOneUse() && N1->hasOneUse() &&
6009 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6014 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6015 // Multiplications are only custom-lowered for 128-bit vectors so that
6016 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6017 EVT VT = Op.getValueType();
6018 assert(VT.is128BitVector() && VT.isInteger() &&
6019 "unexpected type for custom-lowering ISD::MUL");
6020 SDNode *N0 = Op.getOperand(0).getNode();
6021 SDNode *N1 = Op.getOperand(1).getNode();
6022 unsigned NewOpc = 0;
6024 bool isN0SExt = isSignExtended(N0, DAG);
6025 bool isN1SExt = isSignExtended(N1, DAG);
6026 if (isN0SExt && isN1SExt)
6027 NewOpc = ARMISD::VMULLs;
6029 bool isN0ZExt = isZeroExtended(N0, DAG);
6030 bool isN1ZExt = isZeroExtended(N1, DAG);
6031 if (isN0ZExt && isN1ZExt)
6032 NewOpc = ARMISD::VMULLu;
6033 else if (isN1SExt || isN1ZExt) {
6034 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6035 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6036 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6037 NewOpc = ARMISD::VMULLs;
6039 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6040 NewOpc = ARMISD::VMULLu;
6042 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6044 NewOpc = ARMISD::VMULLu;
6050 if (VT == MVT::v2i64)
6051 // Fall through to expand this. It is not legal.
6054 // Other vector multiplications are legal.
6059 // Legalize to a VMULL instruction.
6062 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6064 Op0 = SkipExtensionForVMULL(N0, DAG);
6065 assert(Op0.getValueType().is64BitVector() &&
6066 Op1.getValueType().is64BitVector() &&
6067 "unexpected types for extended operands to VMULL");
6068 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6071 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6072 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6079 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6080 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6081 EVT Op1VT = Op1.getValueType();
6082 return DAG.getNode(N0->getOpcode(), DL, VT,
6083 DAG.getNode(NewOpc, DL, VT,
6084 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6085 DAG.getNode(NewOpc, DL, VT,
6086 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6090 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6092 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6093 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6094 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6095 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6096 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6097 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6098 // Get reciprocal estimate.
6099 // float4 recip = vrecpeq_f32(yf);
6100 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6101 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6102 // Because char has a smaller range than uchar, we can actually get away
6103 // without any newton steps. This requires that we use a weird bias
6104 // of 0xb000, however (again, this has been exhaustively tested).
6105 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6106 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6107 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6108 Y = DAG.getConstant(0xb000, MVT::i32);
6109 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6110 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6111 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6112 // Convert back to short.
6113 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6114 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6119 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6121 // Convert to float.
6122 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6123 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6124 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6125 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6126 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6127 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6129 // Use reciprocal estimate and one refinement step.
6130 // float4 recip = vrecpeq_f32(yf);
6131 // recip *= vrecpsq_f32(yf, recip);
6132 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6133 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6134 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6135 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6137 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6138 // Because short has a smaller range than ushort, we can actually get away
6139 // with only a single newton step. This requires that we use a weird bias
6140 // of 89, however (again, this has been exhaustively tested).
6141 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6142 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6143 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6144 N1 = DAG.getConstant(0x89, MVT::i32);
6145 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6146 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6147 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6148 // Convert back to integer and return.
6149 // return vmovn_s32(vcvt_s32_f32(result));
6150 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6151 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6155 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6156 EVT VT = Op.getValueType();
6157 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6158 "unexpected type for custom-lowering ISD::SDIV");
6161 SDValue N0 = Op.getOperand(0);
6162 SDValue N1 = Op.getOperand(1);
6165 if (VT == MVT::v8i8) {
6166 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6167 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6169 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6170 DAG.getIntPtrConstant(4));
6171 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6172 DAG.getIntPtrConstant(4));
6173 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6174 DAG.getIntPtrConstant(0));
6175 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6176 DAG.getIntPtrConstant(0));
6178 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6179 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6181 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6182 N0 = LowerCONCAT_VECTORS(N0, DAG);
6184 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6187 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6190 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6191 EVT VT = Op.getValueType();
6192 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6193 "unexpected type for custom-lowering ISD::UDIV");
6196 SDValue N0 = Op.getOperand(0);
6197 SDValue N1 = Op.getOperand(1);
6200 if (VT == MVT::v8i8) {
6201 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6202 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6204 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6205 DAG.getIntPtrConstant(4));
6206 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6207 DAG.getIntPtrConstant(4));
6208 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6209 DAG.getIntPtrConstant(0));
6210 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6211 DAG.getIntPtrConstant(0));
6213 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6214 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6216 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6217 N0 = LowerCONCAT_VECTORS(N0, DAG);
6219 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6220 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6225 // v4i16 sdiv ... Convert to float.
6226 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6227 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6228 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6229 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6230 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6231 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6233 // Use reciprocal estimate and two refinement steps.
6234 // float4 recip = vrecpeq_f32(yf);
6235 // recip *= vrecpsq_f32(yf, recip);
6236 // recip *= vrecpsq_f32(yf, recip);
6237 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6238 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6239 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6240 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6242 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6243 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6244 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6246 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6247 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6248 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6249 // and that it will never cause us to return an answer too large).
6250 // float4 result = as_float4(as_int4(xf*recip) + 2);
6251 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6252 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6253 N1 = DAG.getConstant(2, MVT::i32);
6254 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6255 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6256 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6257 // Convert back to integer and return.
6258 // return vmovn_u32(vcvt_s32_f32(result));
6259 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6260 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6264 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6265 EVT VT = Op.getNode()->getValueType(0);
6266 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6269 bool ExtraOp = false;
6270 switch (Op.getOpcode()) {
6271 default: llvm_unreachable("Invalid code");
6272 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6273 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6274 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6275 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6279 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6281 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6282 Op.getOperand(1), Op.getOperand(2));
6285 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6286 assert(Subtarget->isTargetDarwin());
6288 // For iOS, we want to call an alternative entry point: __sincos_stret,
6289 // return values are passed via sret.
6291 SDValue Arg = Op.getOperand(0);
6292 EVT ArgVT = Arg.getValueType();
6293 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6295 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6296 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6298 // Pair of floats / doubles used to pass the result.
6299 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6301 // Create stack object for sret.
6302 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6303 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6304 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6305 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6311 Entry.Ty = RetTy->getPointerTo();
6312 Entry.isSExt = false;
6313 Entry.isZExt = false;
6314 Entry.isSRet = true;
6315 Args.push_back(Entry);
6319 Entry.isSExt = false;
6320 Entry.isZExt = false;
6321 Args.push_back(Entry);
6323 const char *LibcallName = (ArgVT == MVT::f64)
6324 ? "__sincos_stret" : "__sincosf_stret";
6325 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6327 TargetLowering::CallLoweringInfo CLI(DAG);
6328 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6329 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6331 .setDiscardResult();
6333 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6335 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6336 MachinePointerInfo(), false, false, false, 0);
6338 // Address of cos field.
6339 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6340 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6341 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6342 MachinePointerInfo(), false, false, false, 0);
6344 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6345 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6346 LoadSin.getValue(0), LoadCos.getValue(0));
6349 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6350 // Monotonic load/store is legal for all targets
6351 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6354 // Acquire/Release load/store is not legal for targets without a
6355 // dmb or equivalent available.
6359 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6360 SmallVectorImpl<SDValue> &Results,
6362 const ARMSubtarget *Subtarget) {
6364 SDValue Cycles32, OutChain;
6366 if (Subtarget->hasPerfMon()) {
6367 // Under Power Management extensions, the cycle-count is:
6368 // mrc p15, #0, <Rt>, c9, c13, #0
6369 SDValue Ops[] = { N->getOperand(0), // Chain
6370 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6371 DAG.getConstant(15, MVT::i32),
6372 DAG.getConstant(0, MVT::i32),
6373 DAG.getConstant(9, MVT::i32),
6374 DAG.getConstant(13, MVT::i32),
6375 DAG.getConstant(0, MVT::i32)
6378 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6379 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6380 OutChain = Cycles32.getValue(1);
6382 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6383 // there are older ARM CPUs that have implementation-specific ways of
6384 // obtaining this information (FIXME!).
6385 Cycles32 = DAG.getConstant(0, MVT::i32);
6386 OutChain = DAG.getEntryNode();
6390 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6391 Cycles32, DAG.getConstant(0, MVT::i32));
6392 Results.push_back(Cycles64);
6393 Results.push_back(OutChain);
6396 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6397 switch (Op.getOpcode()) {
6398 default: llvm_unreachable("Don't know how to custom lower this!");
6399 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6400 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6401 case ISD::GlobalAddress:
6402 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6403 default: llvm_unreachable("unknown object format");
6405 return LowerGlobalAddressWindows(Op, DAG);
6407 return LowerGlobalAddressELF(Op, DAG);
6409 return LowerGlobalAddressDarwin(Op, DAG);
6411 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6412 case ISD::SELECT: return LowerSELECT(Op, DAG);
6413 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6414 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6415 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6416 case ISD::VASTART: return LowerVASTART(Op, DAG);
6417 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6418 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6419 case ISD::SINT_TO_FP:
6420 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6421 case ISD::FP_TO_SINT:
6422 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6423 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6424 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6425 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6426 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6427 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6428 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6429 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6431 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6434 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6435 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6436 case ISD::SRL_PARTS:
6437 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6438 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6439 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6440 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6441 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6442 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6443 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6444 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6445 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6446 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6447 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6448 case ISD::MUL: return LowerMUL(Op, DAG);
6449 case ISD::SDIV: return LowerSDIV(Op, DAG);
6450 case ISD::UDIV: return LowerUDIV(Op, DAG);
6454 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6459 return LowerXALUO(Op, DAG);
6460 case ISD::ATOMIC_LOAD:
6461 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6462 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6464 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6465 case ISD::DYNAMIC_STACKALLOC:
6466 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6467 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6468 llvm_unreachable("Don't know how to custom lower this!");
6469 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6470 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6474 /// ReplaceNodeResults - Replace the results of node with an illegal result
6475 /// type with new values built out of custom code.
6476 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6477 SmallVectorImpl<SDValue>&Results,
6478 SelectionDAG &DAG) const {
6480 switch (N->getOpcode()) {
6482 llvm_unreachable("Don't know how to custom expand this!");
6484 Res = ExpandBITCAST(N, DAG);
6488 Res = Expand64BitShift(N, DAG, Subtarget);
6490 case ISD::READCYCLECOUNTER:
6491 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6495 Results.push_back(Res);
6498 //===----------------------------------------------------------------------===//
6499 // ARM Scheduler Hooks
6500 //===----------------------------------------------------------------------===//
6502 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6503 /// registers the function context.
6504 void ARMTargetLowering::
6505 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6506 MachineBasicBlock *DispatchBB, int FI) const {
6507 const TargetInstrInfo *TII =
6508 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6509 DebugLoc dl = MI->getDebugLoc();
6510 MachineFunction *MF = MBB->getParent();
6511 MachineRegisterInfo *MRI = &MF->getRegInfo();
6512 MachineConstantPool *MCP = MF->getConstantPool();
6513 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6514 const Function *F = MF->getFunction();
6516 bool isThumb = Subtarget->isThumb();
6517 bool isThumb2 = Subtarget->isThumb2();
6519 unsigned PCLabelId = AFI->createPICLabelUId();
6520 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6521 ARMConstantPoolValue *CPV =
6522 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6523 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6525 const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6526 : &ARM::GPRRegClass;
6528 // Grab constant pool and fixed stack memory operands.
6529 MachineMemOperand *CPMMO =
6530 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6531 MachineMemOperand::MOLoad, 4, 4);
6533 MachineMemOperand *FIMMOSt =
6534 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6535 MachineMemOperand::MOStore, 4, 4);
6537 // Load the address of the dispatch MBB into the jump buffer.
6539 // Incoming value: jbuf
6540 // ldr.n r5, LCPI1_1
6543 // str r5, [$jbuf, #+4] ; &jbuf[1]
6544 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6545 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6546 .addConstantPoolIndex(CPI)
6547 .addMemOperand(CPMMO));
6548 // Set the low bit because of thumb mode.
6549 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6551 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6552 .addReg(NewVReg1, RegState::Kill)
6554 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6555 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6556 .addReg(NewVReg2, RegState::Kill)
6558 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6559 .addReg(NewVReg3, RegState::Kill)
6561 .addImm(36) // &jbuf[1] :: pc
6562 .addMemOperand(FIMMOSt));
6563 } else if (isThumb) {
6564 // Incoming value: jbuf
6565 // ldr.n r1, LCPI1_4
6569 // add r2, $jbuf, #+4 ; &jbuf[1]
6571 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6572 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6573 .addConstantPoolIndex(CPI)
6574 .addMemOperand(CPMMO));
6575 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6576 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6577 .addReg(NewVReg1, RegState::Kill)
6579 // Set the low bit because of thumb mode.
6580 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6581 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6582 .addReg(ARM::CPSR, RegState::Define)
6584 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6585 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6586 .addReg(ARM::CPSR, RegState::Define)
6587 .addReg(NewVReg2, RegState::Kill)
6588 .addReg(NewVReg3, RegState::Kill));
6589 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6590 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6592 .addImm(36); // &jbuf[1] :: pc
6593 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6594 .addReg(NewVReg4, RegState::Kill)
6595 .addReg(NewVReg5, RegState::Kill)
6597 .addMemOperand(FIMMOSt));
6599 // Incoming value: jbuf
6602 // str r1, [$jbuf, #+4] ; &jbuf[1]
6603 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6604 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6605 .addConstantPoolIndex(CPI)
6607 .addMemOperand(CPMMO));
6608 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6609 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6610 .addReg(NewVReg1, RegState::Kill)
6611 .addImm(PCLabelId));
6612 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6613 .addReg(NewVReg2, RegState::Kill)
6615 .addImm(36) // &jbuf[1] :: pc
6616 .addMemOperand(FIMMOSt));
6620 MachineBasicBlock *ARMTargetLowering::
6621 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6622 const TargetInstrInfo *TII =
6623 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6624 DebugLoc dl = MI->getDebugLoc();
6625 MachineFunction *MF = MBB->getParent();
6626 MachineRegisterInfo *MRI = &MF->getRegInfo();
6627 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6628 MachineFrameInfo *MFI = MF->getFrameInfo();
6629 int FI = MFI->getFunctionContextIndex();
6631 const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6632 : &ARM::GPRnopcRegClass;
6634 // Get a mapping of the call site numbers to all of the landing pads they're
6636 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6637 unsigned MaxCSNum = 0;
6638 MachineModuleInfo &MMI = MF->getMMI();
6639 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6641 if (!BB->isLandingPad()) continue;
6643 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6645 for (MachineBasicBlock::iterator
6646 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6647 if (!II->isEHLabel()) continue;
6649 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6650 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6652 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6653 for (SmallVectorImpl<unsigned>::iterator
6654 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6655 CSI != CSE; ++CSI) {
6656 CallSiteNumToLPad[*CSI].push_back(BB);
6657 MaxCSNum = std::max(MaxCSNum, *CSI);
6663 // Get an ordered list of the machine basic blocks for the jump table.
6664 std::vector<MachineBasicBlock*> LPadList;
6665 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6666 LPadList.reserve(CallSiteNumToLPad.size());
6667 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6668 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6669 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6670 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6671 LPadList.push_back(*II);
6672 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6676 assert(!LPadList.empty() &&
6677 "No landing pad destinations for the dispatch jump table!");
6679 // Create the jump table and associated information.
6680 MachineJumpTableInfo *JTI =
6681 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6682 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6683 unsigned UId = AFI->createJumpTableUId();
6684 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6686 // Create the MBBs for the dispatch code.
6688 // Shove the dispatch's address into the return slot in the function context.
6689 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6690 DispatchBB->setIsLandingPad();
6692 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6693 unsigned trap_opcode;
6694 if (Subtarget->isThumb())
6695 trap_opcode = ARM::tTRAP;
6697 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6699 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6700 DispatchBB->addSuccessor(TrapBB);
6702 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6703 DispatchBB->addSuccessor(DispContBB);
6706 MF->insert(MF->end(), DispatchBB);
6707 MF->insert(MF->end(), DispContBB);
6708 MF->insert(MF->end(), TrapBB);
6710 // Insert code into the entry block that creates and registers the function
6712 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6714 MachineMemOperand *FIMMOLd =
6715 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6716 MachineMemOperand::MOLoad |
6717 MachineMemOperand::MOVolatile, 4, 4);
6719 MachineInstrBuilder MIB;
6720 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6722 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6723 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6725 // Add a register mask with no preserved registers. This results in all
6726 // registers being marked as clobbered.
6727 MIB.addRegMask(RI.getNoPreservedMask());
6729 unsigned NumLPads = LPadList.size();
6730 if (Subtarget->isThumb2()) {
6731 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6732 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6735 .addMemOperand(FIMMOLd));
6737 if (NumLPads < 256) {
6738 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6740 .addImm(LPadList.size()));
6742 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6743 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6744 .addImm(NumLPads & 0xFFFF));
6746 unsigned VReg2 = VReg1;
6747 if ((NumLPads & 0xFFFF0000) != 0) {
6748 VReg2 = MRI->createVirtualRegister(TRC);
6749 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6751 .addImm(NumLPads >> 16));
6754 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6759 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6764 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6765 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6766 .addJumpTableIndex(MJTI)
6769 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6772 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6773 .addReg(NewVReg3, RegState::Kill)
6775 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6777 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6778 .addReg(NewVReg4, RegState::Kill)
6780 .addJumpTableIndex(MJTI)
6782 } else if (Subtarget->isThumb()) {
6783 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6784 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6787 .addMemOperand(FIMMOLd));
6789 if (NumLPads < 256) {
6790 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6794 MachineConstantPool *ConstantPool = MF->getConstantPool();
6795 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6796 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6798 // MachineConstantPool wants an explicit alignment.
6799 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6801 Align = getDataLayout()->getTypeAllocSize(C->getType());
6802 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6804 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6805 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6806 .addReg(VReg1, RegState::Define)
6807 .addConstantPoolIndex(Idx));
6808 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6813 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6818 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6819 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6820 .addReg(ARM::CPSR, RegState::Define)
6824 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6825 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6826 .addJumpTableIndex(MJTI)
6829 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6830 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6831 .addReg(ARM::CPSR, RegState::Define)
6832 .addReg(NewVReg2, RegState::Kill)
6835 MachineMemOperand *JTMMOLd =
6836 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6837 MachineMemOperand::MOLoad, 4, 4);
6839 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6840 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6841 .addReg(NewVReg4, RegState::Kill)
6843 .addMemOperand(JTMMOLd));
6845 unsigned NewVReg6 = NewVReg5;
6846 if (RelocM == Reloc::PIC_) {
6847 NewVReg6 = MRI->createVirtualRegister(TRC);
6848 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6849 .addReg(ARM::CPSR, RegState::Define)
6850 .addReg(NewVReg5, RegState::Kill)
6854 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6855 .addReg(NewVReg6, RegState::Kill)
6856 .addJumpTableIndex(MJTI)
6859 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6860 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6863 .addMemOperand(FIMMOLd));
6865 if (NumLPads < 256) {
6866 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6869 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6870 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6871 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6872 .addImm(NumLPads & 0xFFFF));
6874 unsigned VReg2 = VReg1;
6875 if ((NumLPads & 0xFFFF0000) != 0) {
6876 VReg2 = MRI->createVirtualRegister(TRC);
6877 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6879 .addImm(NumLPads >> 16));
6882 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6886 MachineConstantPool *ConstantPool = MF->getConstantPool();
6887 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6888 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6890 // MachineConstantPool wants an explicit alignment.
6891 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6893 Align = getDataLayout()->getTypeAllocSize(C->getType());
6894 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6896 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6897 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6898 .addReg(VReg1, RegState::Define)
6899 .addConstantPoolIndex(Idx)
6901 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6903 .addReg(VReg1, RegState::Kill));
6906 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6911 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6913 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6915 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6916 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6917 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6918 .addJumpTableIndex(MJTI)
6921 MachineMemOperand *JTMMOLd =
6922 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6923 MachineMemOperand::MOLoad, 4, 4);
6924 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6926 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6927 .addReg(NewVReg3, RegState::Kill)
6930 .addMemOperand(JTMMOLd));
6932 if (RelocM == Reloc::PIC_) {
6933 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6934 .addReg(NewVReg5, RegState::Kill)
6936 .addJumpTableIndex(MJTI)
6939 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6940 .addReg(NewVReg5, RegState::Kill)
6941 .addJumpTableIndex(MJTI)
6946 // Add the jump table entries as successors to the MBB.
6947 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6948 for (std::vector<MachineBasicBlock*>::iterator
6949 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6950 MachineBasicBlock *CurMBB = *I;
6951 if (SeenMBBs.insert(CurMBB).second)
6952 DispContBB->addSuccessor(CurMBB);
6955 // N.B. the order the invoke BBs are processed in doesn't matter here.
6956 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6957 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6958 for (MachineBasicBlock *BB : InvokeBBs) {
6960 // Remove the landing pad successor from the invoke block and replace it
6961 // with the new dispatch block.
6962 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6964 while (!Successors.empty()) {
6965 MachineBasicBlock *SMBB = Successors.pop_back_val();
6966 if (SMBB->isLandingPad()) {
6967 BB->removeSuccessor(SMBB);
6968 MBBLPads.push_back(SMBB);
6972 BB->addSuccessor(DispatchBB);
6974 // Find the invoke call and mark all of the callee-saved registers as
6975 // 'implicit defined' so that they're spilled. This prevents code from
6976 // moving instructions to before the EH block, where they will never be
6978 for (MachineBasicBlock::reverse_iterator
6979 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6980 if (!II->isCall()) continue;
6982 DenseMap<unsigned, bool> DefRegs;
6983 for (MachineInstr::mop_iterator
6984 OI = II->operands_begin(), OE = II->operands_end();
6986 if (!OI->isReg()) continue;
6987 DefRegs[OI->getReg()] = true;
6990 MachineInstrBuilder MIB(*MF, &*II);
6992 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6993 unsigned Reg = SavedRegs[i];
6994 if (Subtarget->isThumb2() &&
6995 !ARM::tGPRRegClass.contains(Reg) &&
6996 !ARM::hGPRRegClass.contains(Reg))
6998 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7000 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7003 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7010 // Mark all former landing pads as non-landing pads. The dispatch is the only
7012 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7013 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7014 (*I)->setIsLandingPad(false);
7016 // The instruction is gone now.
7017 MI->eraseFromParent();
7023 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7024 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7025 E = MBB->succ_end(); I != E; ++I)
7028 llvm_unreachable("Expecting a BB with two successors!");
7031 /// Return the load opcode for a given load size. If load size >= 8,
7032 /// neon opcode will be returned.
7033 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7035 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7036 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7038 return LdSize == 4 ? ARM::tLDRi
7039 : LdSize == 2 ? ARM::tLDRHi
7040 : LdSize == 1 ? ARM::tLDRBi : 0;
7042 return LdSize == 4 ? ARM::t2LDR_POST
7043 : LdSize == 2 ? ARM::t2LDRH_POST
7044 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7045 return LdSize == 4 ? ARM::LDR_POST_IMM
7046 : LdSize == 2 ? ARM::LDRH_POST
7047 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7050 /// Return the store opcode for a given store size. If store size >= 8,
7051 /// neon opcode will be returned.
7052 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7054 return StSize == 16 ? ARM::VST1q32wb_fixed
7055 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7057 return StSize == 4 ? ARM::tSTRi
7058 : StSize == 2 ? ARM::tSTRHi
7059 : StSize == 1 ? ARM::tSTRBi : 0;
7061 return StSize == 4 ? ARM::t2STR_POST
7062 : StSize == 2 ? ARM::t2STRH_POST
7063 : StSize == 1 ? ARM::t2STRB_POST : 0;
7064 return StSize == 4 ? ARM::STR_POST_IMM
7065 : StSize == 2 ? ARM::STRH_POST
7066 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7069 /// Emit a post-increment load operation with given size. The instructions
7070 /// will be added to BB at Pos.
7071 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7072 const TargetInstrInfo *TII, DebugLoc dl,
7073 unsigned LdSize, unsigned Data, unsigned AddrIn,
7074 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7075 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7076 assert(LdOpc != 0 && "Should have a load opcode");
7078 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7079 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7081 } else if (IsThumb1) {
7082 // load + update AddrIn
7083 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7084 .addReg(AddrIn).addImm(0));
7085 MachineInstrBuilder MIB =
7086 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7087 MIB = AddDefaultT1CC(MIB);
7088 MIB.addReg(AddrIn).addImm(LdSize);
7089 AddDefaultPred(MIB);
7090 } else if (IsThumb2) {
7091 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7092 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7095 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7096 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7097 .addReg(0).addImm(LdSize));
7101 /// Emit a post-increment store operation with given size. The instructions
7102 /// will be added to BB at Pos.
7103 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7104 const TargetInstrInfo *TII, DebugLoc dl,
7105 unsigned StSize, unsigned Data, unsigned AddrIn,
7106 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7107 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7108 assert(StOpc != 0 && "Should have a store opcode");
7110 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7111 .addReg(AddrIn).addImm(0).addReg(Data));
7112 } else if (IsThumb1) {
7113 // store + update AddrIn
7114 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7115 .addReg(AddrIn).addImm(0));
7116 MachineInstrBuilder MIB =
7117 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7118 MIB = AddDefaultT1CC(MIB);
7119 MIB.addReg(AddrIn).addImm(StSize);
7120 AddDefaultPred(MIB);
7121 } else if (IsThumb2) {
7122 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7123 .addReg(Data).addReg(AddrIn).addImm(StSize));
7125 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7126 .addReg(Data).addReg(AddrIn).addReg(0)
7132 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7133 MachineBasicBlock *BB) const {
7134 // This pseudo instruction has 3 operands: dst, src, size
7135 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7136 // Otherwise, we will generate unrolled scalar copies.
7137 const TargetInstrInfo *TII =
7138 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7139 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7140 MachineFunction::iterator It = BB;
7143 unsigned dest = MI->getOperand(0).getReg();
7144 unsigned src = MI->getOperand(1).getReg();
7145 unsigned SizeVal = MI->getOperand(2).getImm();
7146 unsigned Align = MI->getOperand(3).getImm();
7147 DebugLoc dl = MI->getDebugLoc();
7149 MachineFunction *MF = BB->getParent();
7150 MachineRegisterInfo &MRI = MF->getRegInfo();
7151 unsigned UnitSize = 0;
7152 const TargetRegisterClass *TRC = nullptr;
7153 const TargetRegisterClass *VecTRC = nullptr;
7155 bool IsThumb1 = Subtarget->isThumb1Only();
7156 bool IsThumb2 = Subtarget->isThumb2();
7160 } else if (Align & 2) {
7163 // Check whether we can use NEON instructions.
7164 if (!MF->getFunction()->getAttributes().
7165 hasAttribute(AttributeSet::FunctionIndex,
7166 Attribute::NoImplicitFloat) &&
7167 Subtarget->hasNEON()) {
7168 if ((Align % 16 == 0) && SizeVal >= 16)
7170 else if ((Align % 8 == 0) && SizeVal >= 8)
7173 // Can't use NEON instructions.
7178 // Select the correct opcode and register class for unit size load/store
7179 bool IsNeon = UnitSize >= 8;
7180 TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7182 VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7183 : UnitSize == 8 ? &ARM::DPRRegClass
7186 unsigned BytesLeft = SizeVal % UnitSize;
7187 unsigned LoopSize = SizeVal - BytesLeft;
7189 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7190 // Use LDR and STR to copy.
7191 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7192 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7193 unsigned srcIn = src;
7194 unsigned destIn = dest;
7195 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7196 unsigned srcOut = MRI.createVirtualRegister(TRC);
7197 unsigned destOut = MRI.createVirtualRegister(TRC);
7198 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7199 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7200 IsThumb1, IsThumb2);
7201 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7202 IsThumb1, IsThumb2);
7207 // Handle the leftover bytes with LDRB and STRB.
7208 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7209 // [destOut] = STRB_POST(scratch, destIn, 1)
7210 for (unsigned i = 0; i < BytesLeft; i++) {
7211 unsigned srcOut = MRI.createVirtualRegister(TRC);
7212 unsigned destOut = MRI.createVirtualRegister(TRC);
7213 unsigned scratch = MRI.createVirtualRegister(TRC);
7214 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7215 IsThumb1, IsThumb2);
7216 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7217 IsThumb1, IsThumb2);
7221 MI->eraseFromParent(); // The instruction is gone now.
7225 // Expand the pseudo op to a loop.
7228 // movw varEnd, # --> with thumb2
7230 // ldrcp varEnd, idx --> without thumb2
7231 // fallthrough --> loopMBB
7233 // PHI varPhi, varEnd, varLoop
7234 // PHI srcPhi, src, srcLoop
7235 // PHI destPhi, dst, destLoop
7236 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7237 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7238 // subs varLoop, varPhi, #UnitSize
7240 // fallthrough --> exitMBB
7242 // epilogue to handle left-over bytes
7243 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7244 // [destOut] = STRB_POST(scratch, destLoop, 1)
7245 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7246 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7247 MF->insert(It, loopMBB);
7248 MF->insert(It, exitMBB);
7250 // Transfer the remainder of BB and its successor edges to exitMBB.
7251 exitMBB->splice(exitMBB->begin(), BB,
7252 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7253 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7255 // Load an immediate to varEnd.
7256 unsigned varEnd = MRI.createVirtualRegister(TRC);
7258 unsigned Vtmp = varEnd;
7259 if ((LoopSize & 0xFFFF0000) != 0)
7260 Vtmp = MRI.createVirtualRegister(TRC);
7261 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7262 .addImm(LoopSize & 0xFFFF));
7264 if ((LoopSize & 0xFFFF0000) != 0)
7265 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7266 .addReg(Vtmp).addImm(LoopSize >> 16));
7268 MachineConstantPool *ConstantPool = MF->getConstantPool();
7269 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7270 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7272 // MachineConstantPool wants an explicit alignment.
7273 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7275 Align = getDataLayout()->getTypeAllocSize(C->getType());
7276 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7279 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7280 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7282 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7283 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7285 BB->addSuccessor(loopMBB);
7287 // Generate the loop body:
7288 // varPhi = PHI(varLoop, varEnd)
7289 // srcPhi = PHI(srcLoop, src)
7290 // destPhi = PHI(destLoop, dst)
7291 MachineBasicBlock *entryBB = BB;
7293 unsigned varLoop = MRI.createVirtualRegister(TRC);
7294 unsigned varPhi = MRI.createVirtualRegister(TRC);
7295 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7296 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7297 unsigned destLoop = MRI.createVirtualRegister(TRC);
7298 unsigned destPhi = MRI.createVirtualRegister(TRC);
7300 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7301 .addReg(varLoop).addMBB(loopMBB)
7302 .addReg(varEnd).addMBB(entryBB);
7303 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7304 .addReg(srcLoop).addMBB(loopMBB)
7305 .addReg(src).addMBB(entryBB);
7306 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7307 .addReg(destLoop).addMBB(loopMBB)
7308 .addReg(dest).addMBB(entryBB);
7310 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7311 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7312 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7313 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7314 IsThumb1, IsThumb2);
7315 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7316 IsThumb1, IsThumb2);
7318 // Decrement loop variable by UnitSize.
7320 MachineInstrBuilder MIB =
7321 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7322 MIB = AddDefaultT1CC(MIB);
7323 MIB.addReg(varPhi).addImm(UnitSize);
7324 AddDefaultPred(MIB);
7326 MachineInstrBuilder MIB =
7327 BuildMI(*BB, BB->end(), dl,
7328 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7329 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7330 MIB->getOperand(5).setReg(ARM::CPSR);
7331 MIB->getOperand(5).setIsDef(true);
7333 BuildMI(*BB, BB->end(), dl,
7334 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7335 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7337 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7338 BB->addSuccessor(loopMBB);
7339 BB->addSuccessor(exitMBB);
7341 // Add epilogue to handle BytesLeft.
7343 MachineInstr *StartOfExit = exitMBB->begin();
7345 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7346 // [destOut] = STRB_POST(scratch, destLoop, 1)
7347 unsigned srcIn = srcLoop;
7348 unsigned destIn = destLoop;
7349 for (unsigned i = 0; i < BytesLeft; i++) {
7350 unsigned srcOut = MRI.createVirtualRegister(TRC);
7351 unsigned destOut = MRI.createVirtualRegister(TRC);
7352 unsigned scratch = MRI.createVirtualRegister(TRC);
7353 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7354 IsThumb1, IsThumb2);
7355 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7356 IsThumb1, IsThumb2);
7361 MI->eraseFromParent(); // The instruction is gone now.
7366 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7367 MachineBasicBlock *MBB) const {
7368 const TargetMachine &TM = getTargetMachine();
7369 const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7370 DebugLoc DL = MI->getDebugLoc();
7372 assert(Subtarget->isTargetWindows() &&
7373 "__chkstk is only supported on Windows");
7374 assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7376 // __chkstk takes the number of words to allocate on the stack in R4, and
7377 // returns the stack adjustment in number of bytes in R4. This will not
7378 // clober any other registers (other than the obvious lr).
7380 // Although, technically, IP should be considered a register which may be
7381 // clobbered, the call itself will not touch it. Windows on ARM is a pure
7382 // thumb-2 environment, so there is no interworking required. As a result, we
7383 // do not expect a veneer to be emitted by the linker, clobbering IP.
7385 // Each module receives its own copy of __chkstk, so no import thunk is
7386 // required, again, ensuring that IP is not clobbered.
7388 // Finally, although some linkers may theoretically provide a trampoline for
7389 // out of range calls (which is quite common due to a 32M range limitation of
7390 // branches for Thumb), we can generate the long-call version via
7391 // -mcmodel=large, alleviating the need for the trampoline which may clobber
7394 switch (TM.getCodeModel()) {
7395 case CodeModel::Small:
7396 case CodeModel::Medium:
7397 case CodeModel::Default:
7398 case CodeModel::Kernel:
7399 BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7400 .addImm((unsigned)ARMCC::AL).addReg(0)
7401 .addExternalSymbol("__chkstk")
7402 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7403 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7404 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7406 case CodeModel::Large:
7407 case CodeModel::JITDefault: {
7408 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7409 unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7411 BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7412 .addExternalSymbol("__chkstk");
7413 BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7414 .addImm((unsigned)ARMCC::AL).addReg(0)
7415 .addReg(Reg, RegState::Kill)
7416 .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7417 .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7418 .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7423 AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7425 .addReg(ARM::SP).addReg(ARM::R4)));
7427 MI->eraseFromParent();
7432 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7433 MachineBasicBlock *BB) const {
7434 const TargetInstrInfo *TII =
7435 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7436 DebugLoc dl = MI->getDebugLoc();
7437 bool isThumb2 = Subtarget->isThumb2();
7438 switch (MI->getOpcode()) {
7441 llvm_unreachable("Unexpected instr type to insert");
7443 // The Thumb2 pre-indexed stores have the same MI operands, they just
7444 // define them differently in the .td files from the isel patterns, so
7445 // they need pseudos.
7446 case ARM::t2STR_preidx:
7447 MI->setDesc(TII->get(ARM::t2STR_PRE));
7449 case ARM::t2STRB_preidx:
7450 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7452 case ARM::t2STRH_preidx:
7453 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7456 case ARM::STRi_preidx:
7457 case ARM::STRBi_preidx: {
7458 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7459 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7460 // Decode the offset.
7461 unsigned Offset = MI->getOperand(4).getImm();
7462 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7463 Offset = ARM_AM::getAM2Offset(Offset);
7467 MachineMemOperand *MMO = *MI->memoperands_begin();
7468 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7469 .addOperand(MI->getOperand(0)) // Rn_wb
7470 .addOperand(MI->getOperand(1)) // Rt
7471 .addOperand(MI->getOperand(2)) // Rn
7472 .addImm(Offset) // offset (skip GPR==zero_reg)
7473 .addOperand(MI->getOperand(5)) // pred
7474 .addOperand(MI->getOperand(6))
7475 .addMemOperand(MMO);
7476 MI->eraseFromParent();
7479 case ARM::STRr_preidx:
7480 case ARM::STRBr_preidx:
7481 case ARM::STRH_preidx: {
7483 switch (MI->getOpcode()) {
7484 default: llvm_unreachable("unexpected opcode!");
7485 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7486 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7487 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7489 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7490 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7491 MIB.addOperand(MI->getOperand(i));
7492 MI->eraseFromParent();
7496 case ARM::tMOVCCr_pseudo: {
7497 // To "insert" a SELECT_CC instruction, we actually have to insert the
7498 // diamond control-flow pattern. The incoming instruction knows the
7499 // destination vreg to set, the condition code register to branch on, the
7500 // true/false values to select between, and a branch opcode to use.
7501 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7502 MachineFunction::iterator It = BB;
7508 // cmpTY ccX, r1, r2
7510 // fallthrough --> copy0MBB
7511 MachineBasicBlock *thisMBB = BB;
7512 MachineFunction *F = BB->getParent();
7513 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7514 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7515 F->insert(It, copy0MBB);
7516 F->insert(It, sinkMBB);
7518 // Transfer the remainder of BB and its successor edges to sinkMBB.
7519 sinkMBB->splice(sinkMBB->begin(), BB,
7520 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7521 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7523 BB->addSuccessor(copy0MBB);
7524 BB->addSuccessor(sinkMBB);
7526 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7527 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7530 // %FalseValue = ...
7531 // # fallthrough to sinkMBB
7534 // Update machine-CFG edges
7535 BB->addSuccessor(sinkMBB);
7538 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7541 BuildMI(*BB, BB->begin(), dl,
7542 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7543 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7544 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7546 MI->eraseFromParent(); // The pseudo instruction is gone now.
7551 case ARM::BCCZi64: {
7552 // If there is an unconditional branch to the other successor, remove it.
7553 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7555 // Compare both parts that make up the double comparison separately for
7557 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7559 unsigned LHS1 = MI->getOperand(1).getReg();
7560 unsigned LHS2 = MI->getOperand(2).getReg();
7562 AddDefaultPred(BuildMI(BB, dl,
7563 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7564 .addReg(LHS1).addImm(0));
7565 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7566 .addReg(LHS2).addImm(0)
7567 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7569 unsigned RHS1 = MI->getOperand(3).getReg();
7570 unsigned RHS2 = MI->getOperand(4).getReg();
7571 AddDefaultPred(BuildMI(BB, dl,
7572 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7573 .addReg(LHS1).addReg(RHS1));
7574 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7575 .addReg(LHS2).addReg(RHS2)
7576 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7579 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7580 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7581 if (MI->getOperand(0).getImm() == ARMCC::NE)
7582 std::swap(destMBB, exitMBB);
7584 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7585 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7587 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7589 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7591 MI->eraseFromParent(); // The pseudo instruction is gone now.
7595 case ARM::Int_eh_sjlj_setjmp:
7596 case ARM::Int_eh_sjlj_setjmp_nofp:
7597 case ARM::tInt_eh_sjlj_setjmp:
7598 case ARM::t2Int_eh_sjlj_setjmp:
7599 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7600 EmitSjLjDispatchBlock(MI, BB);
7605 // To insert an ABS instruction, we have to insert the
7606 // diamond control-flow pattern. The incoming instruction knows the
7607 // source vreg to test against 0, the destination vreg to set,
7608 // the condition code register to branch on, the
7609 // true/false values to select between, and a branch opcode to use.
7614 // BCC (branch to SinkBB if V0 >= 0)
7615 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7616 // SinkBB: V1 = PHI(V2, V3)
7617 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7618 MachineFunction::iterator BBI = BB;
7620 MachineFunction *Fn = BB->getParent();
7621 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7622 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7623 Fn->insert(BBI, RSBBB);
7624 Fn->insert(BBI, SinkBB);
7626 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7627 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7628 bool isThumb2 = Subtarget->isThumb2();
7629 MachineRegisterInfo &MRI = Fn->getRegInfo();
7630 // In Thumb mode S must not be specified if source register is the SP or
7631 // PC and if destination register is the SP, so restrict register class
7632 unsigned NewRsbDstReg =
7633 MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7635 // Transfer the remainder of BB and its successor edges to sinkMBB.
7636 SinkBB->splice(SinkBB->begin(), BB,
7637 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7638 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7640 BB->addSuccessor(RSBBB);
7641 BB->addSuccessor(SinkBB);
7643 // fall through to SinkMBB
7644 RSBBB->addSuccessor(SinkBB);
7646 // insert a cmp at the end of BB
7647 AddDefaultPred(BuildMI(BB, dl,
7648 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7649 .addReg(ABSSrcReg).addImm(0));
7651 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7653 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7654 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7656 // insert rsbri in RSBBB
7657 // Note: BCC and rsbri will be converted into predicated rsbmi
7658 // by if-conversion pass
7659 BuildMI(*RSBBB, RSBBB->begin(), dl,
7660 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7661 .addReg(ABSSrcReg, RegState::Kill)
7662 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7664 // insert PHI in SinkBB,
7665 // reuse ABSDstReg to not change uses of ABS instruction
7666 BuildMI(*SinkBB, SinkBB->begin(), dl,
7667 TII->get(ARM::PHI), ABSDstReg)
7668 .addReg(NewRsbDstReg).addMBB(RSBBB)
7669 .addReg(ABSSrcReg).addMBB(BB);
7671 // remove ABS instruction
7672 MI->eraseFromParent();
7674 // return last added BB
7677 case ARM::COPY_STRUCT_BYVAL_I32:
7679 return EmitStructByval(MI, BB);
7680 case ARM::WIN__CHKSTK:
7681 return EmitLowered__chkstk(MI, BB);
7685 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7686 SDNode *Node) const {
7687 const MCInstrDesc *MCID = &MI->getDesc();
7688 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7689 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7690 // operand is still set to noreg. If needed, set the optional operand's
7691 // register to CPSR, and remove the redundant implicit def.
7693 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7695 // Rename pseudo opcodes.
7696 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7698 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7699 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7700 MCID = &TII->get(NewOpc);
7702 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7703 "converted opcode should be the same except for cc_out");
7707 // Add the optional cc_out operand
7708 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7710 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7712 // Any ARM instruction that sets the 's' bit should specify an optional
7713 // "cc_out" operand in the last operand position.
7714 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7715 assert(!NewOpc && "Optional cc_out operand required");
7718 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7719 // since we already have an optional CPSR def.
7720 bool definesCPSR = false;
7721 bool deadCPSR = false;
7722 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7724 const MachineOperand &MO = MI->getOperand(i);
7725 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7729 MI->RemoveOperand(i);
7734 assert(!NewOpc && "Optional cc_out operand required");
7737 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7739 assert(!MI->getOperand(ccOutIdx).getReg() &&
7740 "expect uninitialized optional cc_out operand");
7744 // If this instruction was defined with an optional CPSR def and its dag node
7745 // had a live implicit CPSR def, then activate the optional CPSR def.
7746 MachineOperand &MO = MI->getOperand(ccOutIdx);
7747 MO.setReg(ARM::CPSR);
7751 //===----------------------------------------------------------------------===//
7752 // ARM Optimization Hooks
7753 //===----------------------------------------------------------------------===//
7755 // Helper function that checks if N is a null or all ones constant.
7756 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7757 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7760 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7763 // Return true if N is conditionally 0 or all ones.
7764 // Detects these expressions where cc is an i1 value:
7766 // (select cc 0, y) [AllOnes=0]
7767 // (select cc y, 0) [AllOnes=0]
7768 // (zext cc) [AllOnes=0]
7769 // (sext cc) [AllOnes=0/1]
7770 // (select cc -1, y) [AllOnes=1]
7771 // (select cc y, -1) [AllOnes=1]
7773 // Invert is set when N is the null/all ones constant when CC is false.
7774 // OtherOp is set to the alternative value of N.
7775 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7776 SDValue &CC, bool &Invert,
7778 SelectionDAG &DAG) {
7779 switch (N->getOpcode()) {
7780 default: return false;
7782 CC = N->getOperand(0);
7783 SDValue N1 = N->getOperand(1);
7784 SDValue N2 = N->getOperand(2);
7785 if (isZeroOrAllOnes(N1, AllOnes)) {
7790 if (isZeroOrAllOnes(N2, AllOnes)) {
7797 case ISD::ZERO_EXTEND:
7798 // (zext cc) can never be the all ones value.
7802 case ISD::SIGN_EXTEND: {
7803 EVT VT = N->getValueType(0);
7804 CC = N->getOperand(0);
7805 if (CC.getValueType() != MVT::i1)
7809 // When looking for an AllOnes constant, N is an sext, and the 'other'
7811 OtherOp = DAG.getConstant(0, VT);
7812 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7813 // When looking for a 0 constant, N can be zext or sext.
7814 OtherOp = DAG.getConstant(1, VT);
7816 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7822 // Combine a constant select operand into its use:
7824 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7825 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7826 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7827 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7828 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7830 // The transform is rejected if the select doesn't have a constant operand that
7831 // is null, or all ones when AllOnes is set.
7833 // Also recognize sext/zext from i1:
7835 // (add (zext cc), x) -> (select cc (add x, 1), x)
7836 // (add (sext cc), x) -> (select cc (add x, -1), x)
7838 // These transformations eventually create predicated instructions.
7840 // @param N The node to transform.
7841 // @param Slct The N operand that is a select.
7842 // @param OtherOp The other N operand (x above).
7843 // @param DCI Context.
7844 // @param AllOnes Require the select constant to be all ones instead of null.
7845 // @returns The new node, or SDValue() on failure.
7847 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7848 TargetLowering::DAGCombinerInfo &DCI,
7849 bool AllOnes = false) {
7850 SelectionDAG &DAG = DCI.DAG;
7851 EVT VT = N->getValueType(0);
7852 SDValue NonConstantVal;
7855 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7856 NonConstantVal, DAG))
7859 // Slct is now know to be the desired identity constant when CC is true.
7860 SDValue TrueVal = OtherOp;
7861 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7862 OtherOp, NonConstantVal);
7863 // Unless SwapSelectOps says CC should be false.
7865 std::swap(TrueVal, FalseVal);
7867 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7868 CCOp, TrueVal, FalseVal);
7871 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7873 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7874 TargetLowering::DAGCombinerInfo &DCI) {
7875 SDValue N0 = N->getOperand(0);
7876 SDValue N1 = N->getOperand(1);
7877 if (N0.getNode()->hasOneUse()) {
7878 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7879 if (Result.getNode())
7882 if (N1.getNode()->hasOneUse()) {
7883 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7884 if (Result.getNode())
7890 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7891 // (only after legalization).
7892 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7893 TargetLowering::DAGCombinerInfo &DCI,
7894 const ARMSubtarget *Subtarget) {
7896 // Only perform optimization if after legalize, and if NEON is available. We
7897 // also expected both operands to be BUILD_VECTORs.
7898 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7899 || N0.getOpcode() != ISD::BUILD_VECTOR
7900 || N1.getOpcode() != ISD::BUILD_VECTOR)
7903 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7904 EVT VT = N->getValueType(0);
7905 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7908 // Check that the vector operands are of the right form.
7909 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7910 // operands, where N is the size of the formed vector.
7911 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7912 // index such that we have a pair wise add pattern.
7914 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7915 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7917 SDValue Vec = N0->getOperand(0)->getOperand(0);
7918 SDNode *V = Vec.getNode();
7919 unsigned nextIndex = 0;
7921 // For each operands to the ADD which are BUILD_VECTORs,
7922 // check to see if each of their operands are an EXTRACT_VECTOR with
7923 // the same vector and appropriate index.
7924 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7925 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7926 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7928 SDValue ExtVec0 = N0->getOperand(i);
7929 SDValue ExtVec1 = N1->getOperand(i);
7931 // First operand is the vector, verify its the same.
7932 if (V != ExtVec0->getOperand(0).getNode() ||
7933 V != ExtVec1->getOperand(0).getNode())
7936 // Second is the constant, verify its correct.
7937 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7938 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7940 // For the constant, we want to see all the even or all the odd.
7941 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7942 || C1->getZExtValue() != nextIndex+1)
7951 // Create VPADDL node.
7952 SelectionDAG &DAG = DCI.DAG;
7953 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7955 // Build operand list.
7956 SmallVector<SDValue, 8> Ops;
7957 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7958 TLI.getPointerTy()));
7960 // Input is the vector.
7963 // Get widened type and narrowed type.
7965 unsigned numElem = VT.getVectorNumElements();
7967 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7968 switch (inputLaneType.getSimpleVT().SimpleTy) {
7969 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7970 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7971 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7973 llvm_unreachable("Invalid vector element type for padd optimization.");
7976 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7977 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7978 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7981 static SDValue findMUL_LOHI(SDValue V) {
7982 if (V->getOpcode() == ISD::UMUL_LOHI ||
7983 V->getOpcode() == ISD::SMUL_LOHI)
7988 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7989 TargetLowering::DAGCombinerInfo &DCI,
7990 const ARMSubtarget *Subtarget) {
7992 if (Subtarget->isThumb1Only()) return SDValue();
7994 // Only perform the checks after legalize when the pattern is available.
7995 if (DCI.isBeforeLegalize()) return SDValue();
7997 // Look for multiply add opportunities.
7998 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7999 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8000 // a glue link from the first add to the second add.
8001 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8002 // a S/UMLAL instruction.
8005 // \ / \ [no multiline comment]
8011 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8012 SDValue AddcOp0 = AddcNode->getOperand(0);
8013 SDValue AddcOp1 = AddcNode->getOperand(1);
8015 // Check if the two operands are from the same mul_lohi node.
8016 if (AddcOp0.getNode() == AddcOp1.getNode())
8019 assert(AddcNode->getNumValues() == 2 &&
8020 AddcNode->getValueType(0) == MVT::i32 &&
8021 "Expect ADDC with two result values. First: i32");
8023 // Check that we have a glued ADDC node.
8024 if (AddcNode->getValueType(1) != MVT::Glue)
8027 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8028 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8029 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8030 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8031 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8034 // Look for the glued ADDE.
8035 SDNode* AddeNode = AddcNode->getGluedUser();
8039 // Make sure it is really an ADDE.
8040 if (AddeNode->getOpcode() != ISD::ADDE)
8043 assert(AddeNode->getNumOperands() == 3 &&
8044 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8045 "ADDE node has the wrong inputs");
8047 // Check for the triangle shape.
8048 SDValue AddeOp0 = AddeNode->getOperand(0);
8049 SDValue AddeOp1 = AddeNode->getOperand(1);
8051 // Make sure that the ADDE operands are not coming from the same node.
8052 if (AddeOp0.getNode() == AddeOp1.getNode())
8055 // Find the MUL_LOHI node walking up ADDE's operands.
8056 bool IsLeftOperandMUL = false;
8057 SDValue MULOp = findMUL_LOHI(AddeOp0);
8058 if (MULOp == SDValue())
8059 MULOp = findMUL_LOHI(AddeOp1);
8061 IsLeftOperandMUL = true;
8062 if (MULOp == SDValue())
8065 // Figure out the right opcode.
8066 unsigned Opc = MULOp->getOpcode();
8067 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8069 // Figure out the high and low input values to the MLAL node.
8070 SDValue* HiMul = &MULOp;
8071 SDValue* HiAdd = nullptr;
8072 SDValue* LoMul = nullptr;
8073 SDValue* LowAdd = nullptr;
8075 if (IsLeftOperandMUL)
8081 if (AddcOp0->getOpcode() == Opc) {
8085 if (AddcOp1->getOpcode() == Opc) {
8093 if (LoMul->getNode() != HiMul->getNode())
8096 // Create the merged node.
8097 SelectionDAG &DAG = DCI.DAG;
8099 // Build operand list.
8100 SmallVector<SDValue, 8> Ops;
8101 Ops.push_back(LoMul->getOperand(0));
8102 Ops.push_back(LoMul->getOperand(1));
8103 Ops.push_back(*LowAdd);
8104 Ops.push_back(*HiAdd);
8106 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8107 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8109 // Replace the ADDs' nodes uses by the MLA node's values.
8110 SDValue HiMLALResult(MLALNode.getNode(), 1);
8111 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8113 SDValue LoMLALResult(MLALNode.getNode(), 0);
8114 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8116 // Return original node to notify the driver to stop replacing.
8117 SDValue resNode(AddcNode, 0);
8121 /// PerformADDCCombine - Target-specific dag combine transform from
8122 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8123 static SDValue PerformADDCCombine(SDNode *N,
8124 TargetLowering::DAGCombinerInfo &DCI,
8125 const ARMSubtarget *Subtarget) {
8127 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8131 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8132 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8133 /// called with the default operands, and if that fails, with commuted
8135 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8136 TargetLowering::DAGCombinerInfo &DCI,
8137 const ARMSubtarget *Subtarget){
8139 // Attempt to create vpaddl for this add.
8140 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8141 if (Result.getNode())
8144 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8145 if (N0.getNode()->hasOneUse()) {
8146 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8147 if (Result.getNode()) return Result;
8152 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8154 static SDValue PerformADDCombine(SDNode *N,
8155 TargetLowering::DAGCombinerInfo &DCI,
8156 const ARMSubtarget *Subtarget) {
8157 SDValue N0 = N->getOperand(0);
8158 SDValue N1 = N->getOperand(1);
8160 // First try with the default operand order.
8161 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8162 if (Result.getNode())
8165 // If that didn't work, try again with the operands commuted.
8166 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8169 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8171 static SDValue PerformSUBCombine(SDNode *N,
8172 TargetLowering::DAGCombinerInfo &DCI) {
8173 SDValue N0 = N->getOperand(0);
8174 SDValue N1 = N->getOperand(1);
8176 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8177 if (N1.getNode()->hasOneUse()) {
8178 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8179 if (Result.getNode()) return Result;
8185 /// PerformVMULCombine
8186 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8187 /// special multiplier accumulator forwarding.
8193 // However, for (A + B) * (A + B),
8200 static SDValue PerformVMULCombine(SDNode *N,
8201 TargetLowering::DAGCombinerInfo &DCI,
8202 const ARMSubtarget *Subtarget) {
8203 if (!Subtarget->hasVMLxForwarding())
8206 SelectionDAG &DAG = DCI.DAG;
8207 SDValue N0 = N->getOperand(0);
8208 SDValue N1 = N->getOperand(1);
8209 unsigned Opcode = N0.getOpcode();
8210 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8211 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8212 Opcode = N1.getOpcode();
8213 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8214 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8222 EVT VT = N->getValueType(0);
8224 SDValue N00 = N0->getOperand(0);
8225 SDValue N01 = N0->getOperand(1);
8226 return DAG.getNode(Opcode, DL, VT,
8227 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8228 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8231 static SDValue PerformMULCombine(SDNode *N,
8232 TargetLowering::DAGCombinerInfo &DCI,
8233 const ARMSubtarget *Subtarget) {
8234 SelectionDAG &DAG = DCI.DAG;
8236 if (Subtarget->isThumb1Only())
8239 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8242 EVT VT = N->getValueType(0);
8243 if (VT.is64BitVector() || VT.is128BitVector())
8244 return PerformVMULCombine(N, DCI, Subtarget);
8248 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8252 int64_t MulAmt = C->getSExtValue();
8253 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8255 ShiftAmt = ShiftAmt & (32 - 1);
8256 SDValue V = N->getOperand(0);
8260 MulAmt >>= ShiftAmt;
8263 if (isPowerOf2_32(MulAmt - 1)) {
8264 // (mul x, 2^N + 1) => (add (shl x, N), x)
8265 Res = DAG.getNode(ISD::ADD, DL, VT,
8267 DAG.getNode(ISD::SHL, DL, VT,
8269 DAG.getConstant(Log2_32(MulAmt - 1),
8271 } else if (isPowerOf2_32(MulAmt + 1)) {
8272 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8273 Res = DAG.getNode(ISD::SUB, DL, VT,
8274 DAG.getNode(ISD::SHL, DL, VT,
8276 DAG.getConstant(Log2_32(MulAmt + 1),
8282 uint64_t MulAmtAbs = -MulAmt;
8283 if (isPowerOf2_32(MulAmtAbs + 1)) {
8284 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8285 Res = DAG.getNode(ISD::SUB, DL, VT,
8287 DAG.getNode(ISD::SHL, DL, VT,
8289 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8291 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8292 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8293 Res = DAG.getNode(ISD::ADD, DL, VT,
8295 DAG.getNode(ISD::SHL, DL, VT,
8297 DAG.getConstant(Log2_32(MulAmtAbs-1),
8299 Res = DAG.getNode(ISD::SUB, DL, VT,
8300 DAG.getConstant(0, MVT::i32),Res);
8307 Res = DAG.getNode(ISD::SHL, DL, VT,
8308 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8310 // Do not add new nodes to DAG combiner worklist.
8311 DCI.CombineTo(N, Res, false);
8315 static SDValue PerformANDCombine(SDNode *N,
8316 TargetLowering::DAGCombinerInfo &DCI,
8317 const ARMSubtarget *Subtarget) {
8319 // Attempt to use immediate-form VBIC
8320 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8322 EVT VT = N->getValueType(0);
8323 SelectionDAG &DAG = DCI.DAG;
8325 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8328 APInt SplatBits, SplatUndef;
8329 unsigned SplatBitSize;
8332 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8333 if (SplatBitSize <= 64) {
8335 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8336 SplatUndef.getZExtValue(), SplatBitSize,
8337 DAG, VbicVT, VT.is128BitVector(),
8339 if (Val.getNode()) {
8341 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8342 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8343 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8348 if (!Subtarget->isThumb1Only()) {
8349 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8350 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8351 if (Result.getNode())
8358 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8359 static SDValue PerformORCombine(SDNode *N,
8360 TargetLowering::DAGCombinerInfo &DCI,
8361 const ARMSubtarget *Subtarget) {
8362 // Attempt to use immediate-form VORR
8363 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8365 EVT VT = N->getValueType(0);
8366 SelectionDAG &DAG = DCI.DAG;
8368 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8371 APInt SplatBits, SplatUndef;
8372 unsigned SplatBitSize;
8374 if (BVN && Subtarget->hasNEON() &&
8375 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8376 if (SplatBitSize <= 64) {
8378 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8379 SplatUndef.getZExtValue(), SplatBitSize,
8380 DAG, VorrVT, VT.is128BitVector(),
8382 if (Val.getNode()) {
8384 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8385 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8386 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8391 if (!Subtarget->isThumb1Only()) {
8392 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8393 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8394 if (Result.getNode())
8398 // The code below optimizes (or (and X, Y), Z).
8399 // The AND operand needs to have a single user to make these optimizations
8401 SDValue N0 = N->getOperand(0);
8402 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8404 SDValue N1 = N->getOperand(1);
8406 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8407 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8408 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8410 unsigned SplatBitSize;
8413 APInt SplatBits0, SplatBits1;
8414 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8415 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8416 // Ensure that the second operand of both ands are constants
8417 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8418 HasAnyUndefs) && !HasAnyUndefs) {
8419 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8420 HasAnyUndefs) && !HasAnyUndefs) {
8421 // Ensure that the bit width of the constants are the same and that
8422 // the splat arguments are logical inverses as per the pattern we
8423 // are trying to simplify.
8424 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8425 SplatBits0 == ~SplatBits1) {
8426 // Canonicalize the vector type to make instruction selection
8428 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8429 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8433 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8439 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8442 // BFI is only available on V6T2+
8443 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8447 // 1) or (and A, mask), val => ARMbfi A, val, mask
8448 // iff (val & mask) == val
8450 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8451 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8452 // && mask == ~mask2
8453 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8454 // && ~mask == mask2
8455 // (i.e., copy a bitfield value into another bitfield of the same width)
8460 SDValue N00 = N0.getOperand(0);
8462 // The value and the mask need to be constants so we can verify this is
8463 // actually a bitfield set. If the mask is 0xffff, we can do better
8464 // via a movt instruction, so don't use BFI in that case.
8465 SDValue MaskOp = N0.getOperand(1);
8466 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8469 unsigned Mask = MaskC->getZExtValue();
8473 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8474 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8476 unsigned Val = N1C->getZExtValue();
8477 if ((Val & ~Mask) != Val)
8480 if (ARM::isBitFieldInvertedMask(Mask)) {
8481 Val >>= countTrailingZeros(~Mask);
8483 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8484 DAG.getConstant(Val, MVT::i32),
8485 DAG.getConstant(Mask, MVT::i32));
8487 // Do not add new nodes to DAG combiner worklist.
8488 DCI.CombineTo(N, Res, false);
8491 } else if (N1.getOpcode() == ISD::AND) {
8492 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8493 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8496 unsigned Mask2 = N11C->getZExtValue();
8498 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8500 if (ARM::isBitFieldInvertedMask(Mask) &&
8502 // The pack halfword instruction works better for masks that fit it,
8503 // so use that when it's available.
8504 if (Subtarget->hasT2ExtractPack() &&
8505 (Mask == 0xffff || Mask == 0xffff0000))
8508 unsigned amt = countTrailingZeros(Mask2);
8509 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8510 DAG.getConstant(amt, MVT::i32));
8511 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8512 DAG.getConstant(Mask, MVT::i32));
8513 // Do not add new nodes to DAG combiner worklist.
8514 DCI.CombineTo(N, Res, false);
8516 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8518 // The pack halfword instruction works better for masks that fit it,
8519 // so use that when it's available.
8520 if (Subtarget->hasT2ExtractPack() &&
8521 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8524 unsigned lsb = countTrailingZeros(Mask);
8525 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8526 DAG.getConstant(lsb, MVT::i32));
8527 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8528 DAG.getConstant(Mask2, MVT::i32));
8529 // Do not add new nodes to DAG combiner worklist.
8530 DCI.CombineTo(N, Res, false);
8535 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8536 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8537 ARM::isBitFieldInvertedMask(~Mask)) {
8538 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8539 // where lsb(mask) == #shamt and masked bits of B are known zero.
8540 SDValue ShAmt = N00.getOperand(1);
8541 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8542 unsigned LSB = countTrailingZeros(Mask);
8546 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8547 DAG.getConstant(~Mask, MVT::i32));
8549 // Do not add new nodes to DAG combiner worklist.
8550 DCI.CombineTo(N, Res, false);
8556 static SDValue PerformXORCombine(SDNode *N,
8557 TargetLowering::DAGCombinerInfo &DCI,
8558 const ARMSubtarget *Subtarget) {
8559 EVT VT = N->getValueType(0);
8560 SelectionDAG &DAG = DCI.DAG;
8562 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8565 if (!Subtarget->isThumb1Only()) {
8566 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8567 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8568 if (Result.getNode())
8575 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8576 /// the bits being cleared by the AND are not demanded by the BFI.
8577 static SDValue PerformBFICombine(SDNode *N,
8578 TargetLowering::DAGCombinerInfo &DCI) {
8579 SDValue N1 = N->getOperand(1);
8580 if (N1.getOpcode() == ISD::AND) {
8581 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8584 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8585 unsigned LSB = countTrailingZeros(~InvMask);
8586 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8588 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8589 "undefined behavior");
8590 unsigned Mask = (1u << Width) - 1;
8591 unsigned Mask2 = N11C->getZExtValue();
8592 if ((Mask & (~Mask2)) == 0)
8593 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8594 N->getOperand(0), N1.getOperand(0),
8600 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8601 /// ARMISD::VMOVRRD.
8602 static SDValue PerformVMOVRRDCombine(SDNode *N,
8603 TargetLowering::DAGCombinerInfo &DCI,
8604 const ARMSubtarget *Subtarget) {
8605 // vmovrrd(vmovdrr x, y) -> x,y
8606 SDValue InDouble = N->getOperand(0);
8607 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8608 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8610 // vmovrrd(load f64) -> (load i32), (load i32)
8611 SDNode *InNode = InDouble.getNode();
8612 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8613 InNode->getValueType(0) == MVT::f64 &&
8614 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8615 !cast<LoadSDNode>(InNode)->isVolatile()) {
8616 // TODO: Should this be done for non-FrameIndex operands?
8617 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8619 SelectionDAG &DAG = DCI.DAG;
8621 SDValue BasePtr = LD->getBasePtr();
8622 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8623 LD->getPointerInfo(), LD->isVolatile(),
8624 LD->isNonTemporal(), LD->isInvariant(),
8625 LD->getAlignment());
8627 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8628 DAG.getConstant(4, MVT::i32));
8629 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8630 LD->getPointerInfo(), LD->isVolatile(),
8631 LD->isNonTemporal(), LD->isInvariant(),
8632 std::min(4U, LD->getAlignment() / 2));
8634 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8635 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8636 std::swap (NewLD1, NewLD2);
8637 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8644 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8645 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8646 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8647 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8648 SDValue Op0 = N->getOperand(0);
8649 SDValue Op1 = N->getOperand(1);
8650 if (Op0.getOpcode() == ISD::BITCAST)
8651 Op0 = Op0.getOperand(0);
8652 if (Op1.getOpcode() == ISD::BITCAST)
8653 Op1 = Op1.getOperand(0);
8654 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8655 Op0.getNode() == Op1.getNode() &&
8656 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8657 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8658 N->getValueType(0), Op0.getOperand(0));
8662 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8663 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8664 /// i64 vector to have f64 elements, since the value can then be loaded
8665 /// directly into a VFP register.
8666 static bool hasNormalLoadOperand(SDNode *N) {
8667 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8668 for (unsigned i = 0; i < NumElts; ++i) {
8669 SDNode *Elt = N->getOperand(i).getNode();
8670 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8676 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8677 /// ISD::BUILD_VECTOR.
8678 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8679 TargetLowering::DAGCombinerInfo &DCI,
8680 const ARMSubtarget *Subtarget) {
8681 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8682 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8683 // into a pair of GPRs, which is fine when the value is used as a scalar,
8684 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8685 SelectionDAG &DAG = DCI.DAG;
8686 if (N->getNumOperands() == 2) {
8687 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8692 // Load i64 elements as f64 values so that type legalization does not split
8693 // them up into i32 values.
8694 EVT VT = N->getValueType(0);
8695 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8698 SmallVector<SDValue, 8> Ops;
8699 unsigned NumElts = VT.getVectorNumElements();
8700 for (unsigned i = 0; i < NumElts; ++i) {
8701 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8703 // Make the DAGCombiner fold the bitcast.
8704 DCI.AddToWorklist(V.getNode());
8706 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8707 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8708 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8711 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8713 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8714 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8715 // At that time, we may have inserted bitcasts from integer to float.
8716 // If these bitcasts have survived DAGCombine, change the lowering of this
8717 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8718 // force to use floating point types.
8720 // Make sure we can change the type of the vector.
8721 // This is possible iff:
8722 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8723 // 1.1. Vector is used only once.
8724 // 1.2. Use is a bit convert to an integer type.
8725 // 2. The size of its operands are 32-bits (64-bits are not legal).
8726 EVT VT = N->getValueType(0);
8727 EVT EltVT = VT.getVectorElementType();
8729 // Check 1.1. and 2.
8730 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8733 // By construction, the input type must be float.
8734 assert(EltVT == MVT::f32 && "Unexpected type!");
8737 SDNode *Use = *N->use_begin();
8738 if (Use->getOpcode() != ISD::BITCAST ||
8739 Use->getValueType(0).isFloatingPoint())
8742 // Check profitability.
8743 // Model is, if more than half of the relevant operands are bitcast from
8744 // i32, turn the build_vector into a sequence of insert_vector_elt.
8745 // Relevant operands are everything that is not statically
8746 // (i.e., at compile time) bitcasted.
8747 unsigned NumOfBitCastedElts = 0;
8748 unsigned NumElts = VT.getVectorNumElements();
8749 unsigned NumOfRelevantElts = NumElts;
8750 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8751 SDValue Elt = N->getOperand(Idx);
8752 if (Elt->getOpcode() == ISD::BITCAST) {
8753 // Assume only bit cast to i32 will go away.
8754 if (Elt->getOperand(0).getValueType() == MVT::i32)
8755 ++NumOfBitCastedElts;
8756 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8757 // Constants are statically casted, thus do not count them as
8758 // relevant operands.
8759 --NumOfRelevantElts;
8762 // Check if more than half of the elements require a non-free bitcast.
8763 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8766 SelectionDAG &DAG = DCI.DAG;
8767 // Create the new vector type.
8768 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8769 // Check if the type is legal.
8770 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8771 if (!TLI.isTypeLegal(VecVT))
8775 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8776 // => BITCAST INSERT_VECTOR_ELT
8777 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8779 SDValue Vec = DAG.getUNDEF(VecVT);
8781 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8782 SDValue V = N->getOperand(Idx);
8783 if (V.getOpcode() == ISD::UNDEF)
8785 if (V.getOpcode() == ISD::BITCAST &&
8786 V->getOperand(0).getValueType() == MVT::i32)
8787 // Fold obvious case.
8788 V = V.getOperand(0);
8790 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8791 // Make the DAGCombiner fold the bitcasts.
8792 DCI.AddToWorklist(V.getNode());
8794 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8795 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8797 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8798 // Make the DAGCombiner fold the bitcasts.
8799 DCI.AddToWorklist(Vec.getNode());
8803 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8804 /// ISD::INSERT_VECTOR_ELT.
8805 static SDValue PerformInsertEltCombine(SDNode *N,
8806 TargetLowering::DAGCombinerInfo &DCI) {
8807 // Bitcast an i64 load inserted into a vector to f64.
8808 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8809 EVT VT = N->getValueType(0);
8810 SDNode *Elt = N->getOperand(1).getNode();
8811 if (VT.getVectorElementType() != MVT::i64 ||
8812 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8815 SelectionDAG &DAG = DCI.DAG;
8817 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8818 VT.getVectorNumElements());
8819 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8820 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8821 // Make the DAGCombiner fold the bitcasts.
8822 DCI.AddToWorklist(Vec.getNode());
8823 DCI.AddToWorklist(V.getNode());
8824 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8825 Vec, V, N->getOperand(2));
8826 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8829 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8830 /// ISD::VECTOR_SHUFFLE.
8831 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8832 // The LLVM shufflevector instruction does not require the shuffle mask
8833 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8834 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8835 // operands do not match the mask length, they are extended by concatenating
8836 // them with undef vectors. That is probably the right thing for other
8837 // targets, but for NEON it is better to concatenate two double-register
8838 // size vector operands into a single quad-register size vector. Do that
8839 // transformation here:
8840 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8841 // shuffle(concat(v1, v2), undef)
8842 SDValue Op0 = N->getOperand(0);
8843 SDValue Op1 = N->getOperand(1);
8844 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8845 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8846 Op0.getNumOperands() != 2 ||
8847 Op1.getNumOperands() != 2)
8849 SDValue Concat0Op1 = Op0.getOperand(1);
8850 SDValue Concat1Op1 = Op1.getOperand(1);
8851 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8852 Concat1Op1.getOpcode() != ISD::UNDEF)
8854 // Skip the transformation if any of the types are illegal.
8855 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8856 EVT VT = N->getValueType(0);
8857 if (!TLI.isTypeLegal(VT) ||
8858 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8859 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8862 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8863 Op0.getOperand(0), Op1.getOperand(0));
8864 // Translate the shuffle mask.
8865 SmallVector<int, 16> NewMask;
8866 unsigned NumElts = VT.getVectorNumElements();
8867 unsigned HalfElts = NumElts/2;
8868 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8869 for (unsigned n = 0; n < NumElts; ++n) {
8870 int MaskElt = SVN->getMaskElt(n);
8872 if (MaskElt < (int)HalfElts)
8874 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8875 NewElt = HalfElts + MaskElt - NumElts;
8876 NewMask.push_back(NewElt);
8878 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8879 DAG.getUNDEF(VT), NewMask.data());
8882 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8883 /// NEON load/store intrinsics to merge base address updates.
8884 static SDValue CombineBaseUpdate(SDNode *N,
8885 TargetLowering::DAGCombinerInfo &DCI) {
8886 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8889 SelectionDAG &DAG = DCI.DAG;
8890 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8891 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8892 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8893 SDValue Addr = N->getOperand(AddrOpIdx);
8895 // Search for a use of the address operand that is an increment.
8896 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8897 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8899 if (User->getOpcode() != ISD::ADD ||
8900 UI.getUse().getResNo() != Addr.getResNo())
8903 // Check that the add is independent of the load/store. Otherwise, folding
8904 // it would create a cycle.
8905 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8908 // Find the new opcode for the updating load/store.
8910 bool isLaneOp = false;
8911 unsigned NewOpc = 0;
8912 unsigned NumVecs = 0;
8914 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8916 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8917 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8919 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8921 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8923 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8925 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8926 NumVecs = 2; isLaneOp = true; break;
8927 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8928 NumVecs = 3; isLaneOp = true; break;
8929 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8930 NumVecs = 4; isLaneOp = true; break;
8931 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8932 NumVecs = 1; isLoad = false; break;
8933 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8934 NumVecs = 2; isLoad = false; break;
8935 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8936 NumVecs = 3; isLoad = false; break;
8937 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8938 NumVecs = 4; isLoad = false; break;
8939 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8940 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8941 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8942 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8943 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8944 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8948 switch (N->getOpcode()) {
8949 default: llvm_unreachable("unexpected opcode for Neon base update");
8950 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8951 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8952 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8956 // Find the size of memory referenced by the load/store.
8959 VecTy = N->getValueType(0);
8961 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8962 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8964 NumBytes /= VecTy.getVectorNumElements();
8966 // If the increment is a constant, it must match the memory ref size.
8967 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8968 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8969 uint64_t IncVal = CInc->getZExtValue();
8970 if (IncVal != NumBytes)
8972 } else if (NumBytes >= 3 * 16) {
8973 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8974 // separate instructions that make it harder to use a non-constant update.
8978 // Create the new updating load/store node.
8980 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8982 for (n = 0; n < NumResultVecs; ++n)
8984 Tys[n++] = MVT::i32;
8985 Tys[n] = MVT::Other;
8986 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
8987 SmallVector<SDValue, 8> Ops;
8988 Ops.push_back(N->getOperand(0)); // incoming chain
8989 Ops.push_back(N->getOperand(AddrOpIdx));
8991 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8992 Ops.push_back(N->getOperand(i));
8994 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8995 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8996 Ops, MemInt->getMemoryVT(),
8997 MemInt->getMemOperand());
9000 std::vector<SDValue> NewResults;
9001 for (unsigned i = 0; i < NumResultVecs; ++i) {
9002 NewResults.push_back(SDValue(UpdN.getNode(), i));
9004 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9005 DCI.CombineTo(N, NewResults);
9006 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9013 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9014 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9015 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9017 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9018 SelectionDAG &DAG = DCI.DAG;
9019 EVT VT = N->getValueType(0);
9020 // vldN-dup instructions only support 64-bit vectors for N > 1.
9021 if (!VT.is64BitVector())
9024 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9025 SDNode *VLD = N->getOperand(0).getNode();
9026 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9028 unsigned NumVecs = 0;
9029 unsigned NewOpc = 0;
9030 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9031 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9033 NewOpc = ARMISD::VLD2DUP;
9034 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9036 NewOpc = ARMISD::VLD3DUP;
9037 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9039 NewOpc = ARMISD::VLD4DUP;
9044 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9045 // numbers match the load.
9046 unsigned VLDLaneNo =
9047 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9048 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9050 // Ignore uses of the chain result.
9051 if (UI.getUse().getResNo() == NumVecs)
9054 if (User->getOpcode() != ARMISD::VDUPLANE ||
9055 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9059 // Create the vldN-dup node.
9062 for (n = 0; n < NumVecs; ++n)
9064 Tys[n] = MVT::Other;
9065 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9066 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9067 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9068 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9069 Ops, VLDMemInt->getMemoryVT(),
9070 VLDMemInt->getMemOperand());
9073 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9075 unsigned ResNo = UI.getUse().getResNo();
9076 // Ignore uses of the chain result.
9077 if (ResNo == NumVecs)
9080 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9083 // Now the vldN-lane intrinsic is dead except for its chain result.
9084 // Update uses of the chain.
9085 std::vector<SDValue> VLDDupResults;
9086 for (unsigned n = 0; n < NumVecs; ++n)
9087 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9088 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9089 DCI.CombineTo(VLD, VLDDupResults);
9094 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9095 /// ARMISD::VDUPLANE.
9096 static SDValue PerformVDUPLANECombine(SDNode *N,
9097 TargetLowering::DAGCombinerInfo &DCI) {
9098 SDValue Op = N->getOperand(0);
9100 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9101 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9102 if (CombineVLDDUP(N, DCI))
9103 return SDValue(N, 0);
9105 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9106 // redundant. Ignore bit_converts for now; element sizes are checked below.
9107 while (Op.getOpcode() == ISD::BITCAST)
9108 Op = Op.getOperand(0);
9109 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9112 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9113 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9114 // The canonical VMOV for a zero vector uses a 32-bit element size.
9115 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9117 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9119 EVT VT = N->getValueType(0);
9120 if (EltSize > VT.getVectorElementType().getSizeInBits())
9123 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9126 /// PerformSTORECombine - Target-specific dag combine xforms for
9128 static SDValue PerformSTORECombine(SDNode *N,
9129 TargetLowering::DAGCombinerInfo &DCI) {
9130 StoreSDNode *St = cast<StoreSDNode>(N);
9131 if (St->isVolatile())
9134 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9135 // pack all of the elements in one place. Next, store to memory in fewer
9137 SDValue StVal = St->getValue();
9138 EVT VT = StVal.getValueType();
9139 if (St->isTruncatingStore() && VT.isVector()) {
9140 SelectionDAG &DAG = DCI.DAG;
9141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9142 EVT StVT = St->getMemoryVT();
9143 unsigned NumElems = VT.getVectorNumElements();
9144 assert(StVT != VT && "Cannot truncate to the same type");
9145 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9146 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9148 // From, To sizes and ElemCount must be pow of two
9149 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9151 // We are going to use the original vector elt for storing.
9152 // Accumulated smaller vector elements must be a multiple of the store size.
9153 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9155 unsigned SizeRatio = FromEltSz / ToEltSz;
9156 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9158 // Create a type on which we perform the shuffle.
9159 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9160 NumElems*SizeRatio);
9161 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9164 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9165 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9166 for (unsigned i = 0; i < NumElems; ++i)
9167 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
9169 // Can't shuffle using an illegal type.
9170 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9172 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9173 DAG.getUNDEF(WideVec.getValueType()),
9175 // At this point all of the data is stored at the bottom of the
9176 // register. We now need to save it to mem.
9178 // Find the largest store unit
9179 MVT StoreType = MVT::i8;
9180 for (MVT Tp : MVT::integer_valuetypes()) {
9181 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9184 // Didn't find a legal store type.
9185 if (!TLI.isTypeLegal(StoreType))
9188 // Bitcast the original vector into a vector of store-size units
9189 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9190 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9191 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9192 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9193 SmallVector<SDValue, 8> Chains;
9194 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9195 TLI.getPointerTy());
9196 SDValue BasePtr = St->getBasePtr();
9198 // Perform one or more big stores into memory.
9199 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9200 for (unsigned I = 0; I < E; I++) {
9201 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9202 StoreType, ShuffWide,
9203 DAG.getIntPtrConstant(I));
9204 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9205 St->getPointerInfo(), St->isVolatile(),
9206 St->isNonTemporal(), St->getAlignment());
9207 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9209 Chains.push_back(Ch);
9211 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9214 if (!ISD::isNormalStore(St))
9217 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9218 // ARM stores of arguments in the same cache line.
9219 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9220 StVal.getNode()->hasOneUse()) {
9221 SelectionDAG &DAG = DCI.DAG;
9222 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
9224 SDValue BasePtr = St->getBasePtr();
9225 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9226 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9227 BasePtr, St->getPointerInfo(), St->isVolatile(),
9228 St->isNonTemporal(), St->getAlignment());
9230 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9231 DAG.getConstant(4, MVT::i32));
9232 return DAG.getStore(NewST1.getValue(0), DL,
9233 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9234 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9235 St->isNonTemporal(),
9236 std::min(4U, St->getAlignment() / 2));
9239 if (StVal.getValueType() == MVT::i64 &&
9240 StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9242 // Bitcast an i64 store extracted from a vector to f64.
9243 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9244 SelectionDAG &DAG = DCI.DAG;
9246 SDValue IntVec = StVal.getOperand(0);
9247 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9248 IntVec.getValueType().getVectorNumElements());
9249 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9250 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9251 Vec, StVal.getOperand(1));
9253 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9254 // Make the DAGCombiner fold the bitcasts.
9255 DCI.AddToWorklist(Vec.getNode());
9256 DCI.AddToWorklist(ExtElt.getNode());
9257 DCI.AddToWorklist(V.getNode());
9258 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9259 St->getPointerInfo(), St->isVolatile(),
9260 St->isNonTemporal(), St->getAlignment(),
9267 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9268 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9269 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9273 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9275 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9280 APFloat APF = C->getValueAPF();
9281 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9282 != APFloat::opOK || !isExact)
9285 c0 = (I == 0) ? cN : c0;
9286 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9293 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9294 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9295 /// when the VMUL has a constant operand that is a power of 2.
9297 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9298 /// vmul.f32 d16, d17, d16
9299 /// vcvt.s32.f32 d16, d16
9301 /// vcvt.s32.f32 d16, d16, #3
9302 static SDValue PerformVCVTCombine(SDNode *N,
9303 TargetLowering::DAGCombinerInfo &DCI,
9304 const ARMSubtarget *Subtarget) {
9305 SelectionDAG &DAG = DCI.DAG;
9306 SDValue Op = N->getOperand(0);
9308 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9309 Op.getOpcode() != ISD::FMUL)
9313 SDValue N0 = Op->getOperand(0);
9314 SDValue ConstVec = Op->getOperand(1);
9315 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9317 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9318 !isConstVecPow2(ConstVec, isSigned, C))
9321 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9322 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9323 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9324 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9326 // These instructions only exist converting from f32 to i32. We can handle
9327 // smaller integers by generating an extra truncate, but larger ones would
9328 // be lossy. We also can't handle more then 4 lanes, since these intructions
9329 // only support v2i32/v4i32 types.
9333 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9334 Intrinsic::arm_neon_vcvtfp2fxu;
9335 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9336 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9337 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9338 DAG.getConstant(Log2_64(C), MVT::i32));
9340 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9341 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9346 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9347 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9348 /// when the VDIV has a constant operand that is a power of 2.
9350 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9351 /// vcvt.f32.s32 d16, d16
9352 /// vdiv.f32 d16, d17, d16
9354 /// vcvt.f32.s32 d16, d16, #3
9355 static SDValue PerformVDIVCombine(SDNode *N,
9356 TargetLowering::DAGCombinerInfo &DCI,
9357 const ARMSubtarget *Subtarget) {
9358 SelectionDAG &DAG = DCI.DAG;
9359 SDValue Op = N->getOperand(0);
9360 unsigned OpOpcode = Op.getNode()->getOpcode();
9362 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9363 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9367 SDValue ConstVec = N->getOperand(1);
9368 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9370 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9371 !isConstVecPow2(ConstVec, isSigned, C))
9374 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9375 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9376 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9377 // These instructions only exist converting from i32 to f32. We can handle
9378 // smaller integers by generating an extra extend, but larger ones would
9383 SDValue ConvInput = Op.getOperand(0);
9384 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9385 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9386 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9387 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9390 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9391 Intrinsic::arm_neon_vcvtfxu2fp;
9392 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9394 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9395 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9398 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9399 /// operand of a vector shift operation, where all the elements of the
9400 /// build_vector must have the same constant integer value.
9401 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9402 // Ignore bit_converts.
9403 while (Op.getOpcode() == ISD::BITCAST)
9404 Op = Op.getOperand(0);
9405 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9406 APInt SplatBits, SplatUndef;
9407 unsigned SplatBitSize;
9409 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9410 HasAnyUndefs, ElementBits) ||
9411 SplatBitSize > ElementBits)
9413 Cnt = SplatBits.getSExtValue();
9417 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9418 /// operand of a vector shift left operation. That value must be in the range:
9419 /// 0 <= Value < ElementBits for a left shift; or
9420 /// 0 <= Value <= ElementBits for a long left shift.
9421 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9422 assert(VT.isVector() && "vector shift count is not a vector type");
9423 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9424 if (! getVShiftImm(Op, ElementBits, Cnt))
9426 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9429 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9430 /// operand of a vector shift right operation. For a shift opcode, the value
9431 /// is positive, but for an intrinsic the value count must be negative. The
9432 /// absolute value must be in the range:
9433 /// 1 <= |Value| <= ElementBits for a right shift; or
9434 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9435 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9437 assert(VT.isVector() && "vector shift count is not a vector type");
9438 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9439 if (! getVShiftImm(Op, ElementBits, Cnt))
9443 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9446 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9447 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9448 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9451 // Don't do anything for most intrinsics.
9454 // Vector shifts: check for immediate versions and lower them.
9455 // Note: This is done during DAG combining instead of DAG legalizing because
9456 // the build_vectors for 64-bit vector element shift counts are generally
9457 // not legal, and it is hard to see their values after they get legalized to
9458 // loads from a constant pool.
9459 case Intrinsic::arm_neon_vshifts:
9460 case Intrinsic::arm_neon_vshiftu:
9461 case Intrinsic::arm_neon_vrshifts:
9462 case Intrinsic::arm_neon_vrshiftu:
9463 case Intrinsic::arm_neon_vrshiftn:
9464 case Intrinsic::arm_neon_vqshifts:
9465 case Intrinsic::arm_neon_vqshiftu:
9466 case Intrinsic::arm_neon_vqshiftsu:
9467 case Intrinsic::arm_neon_vqshiftns:
9468 case Intrinsic::arm_neon_vqshiftnu:
9469 case Intrinsic::arm_neon_vqshiftnsu:
9470 case Intrinsic::arm_neon_vqrshiftns:
9471 case Intrinsic::arm_neon_vqrshiftnu:
9472 case Intrinsic::arm_neon_vqrshiftnsu: {
9473 EVT VT = N->getOperand(1).getValueType();
9475 unsigned VShiftOpc = 0;
9478 case Intrinsic::arm_neon_vshifts:
9479 case Intrinsic::arm_neon_vshiftu:
9480 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9481 VShiftOpc = ARMISD::VSHL;
9484 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9485 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9486 ARMISD::VSHRs : ARMISD::VSHRu);
9491 case Intrinsic::arm_neon_vrshifts:
9492 case Intrinsic::arm_neon_vrshiftu:
9493 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9497 case Intrinsic::arm_neon_vqshifts:
9498 case Intrinsic::arm_neon_vqshiftu:
9499 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9503 case Intrinsic::arm_neon_vqshiftsu:
9504 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9506 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9508 case Intrinsic::arm_neon_vrshiftn:
9509 case Intrinsic::arm_neon_vqshiftns:
9510 case Intrinsic::arm_neon_vqshiftnu:
9511 case Intrinsic::arm_neon_vqshiftnsu:
9512 case Intrinsic::arm_neon_vqrshiftns:
9513 case Intrinsic::arm_neon_vqrshiftnu:
9514 case Intrinsic::arm_neon_vqrshiftnsu:
9515 // Narrowing shifts require an immediate right shift.
9516 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9518 llvm_unreachable("invalid shift count for narrowing vector shift "
9522 llvm_unreachable("unhandled vector shift");
9526 case Intrinsic::arm_neon_vshifts:
9527 case Intrinsic::arm_neon_vshiftu:
9528 // Opcode already set above.
9530 case Intrinsic::arm_neon_vrshifts:
9531 VShiftOpc = ARMISD::VRSHRs; break;
9532 case Intrinsic::arm_neon_vrshiftu:
9533 VShiftOpc = ARMISD::VRSHRu; break;
9534 case Intrinsic::arm_neon_vrshiftn:
9535 VShiftOpc = ARMISD::VRSHRN; break;
9536 case Intrinsic::arm_neon_vqshifts:
9537 VShiftOpc = ARMISD::VQSHLs; break;
9538 case Intrinsic::arm_neon_vqshiftu:
9539 VShiftOpc = ARMISD::VQSHLu; break;
9540 case Intrinsic::arm_neon_vqshiftsu:
9541 VShiftOpc = ARMISD::VQSHLsu; break;
9542 case Intrinsic::arm_neon_vqshiftns:
9543 VShiftOpc = ARMISD::VQSHRNs; break;
9544 case Intrinsic::arm_neon_vqshiftnu:
9545 VShiftOpc = ARMISD::VQSHRNu; break;
9546 case Intrinsic::arm_neon_vqshiftnsu:
9547 VShiftOpc = ARMISD::VQSHRNsu; break;
9548 case Intrinsic::arm_neon_vqrshiftns:
9549 VShiftOpc = ARMISD::VQRSHRNs; break;
9550 case Intrinsic::arm_neon_vqrshiftnu:
9551 VShiftOpc = ARMISD::VQRSHRNu; break;
9552 case Intrinsic::arm_neon_vqrshiftnsu:
9553 VShiftOpc = ARMISD::VQRSHRNsu; break;
9556 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9557 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9560 case Intrinsic::arm_neon_vshiftins: {
9561 EVT VT = N->getOperand(1).getValueType();
9563 unsigned VShiftOpc = 0;
9565 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9566 VShiftOpc = ARMISD::VSLI;
9567 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9568 VShiftOpc = ARMISD::VSRI;
9570 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9573 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9574 N->getOperand(1), N->getOperand(2),
9575 DAG.getConstant(Cnt, MVT::i32));
9578 case Intrinsic::arm_neon_vqrshifts:
9579 case Intrinsic::arm_neon_vqrshiftu:
9580 // No immediate versions of these to check for.
9587 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9588 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9589 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9590 /// vector element shift counts are generally not legal, and it is hard to see
9591 /// their values after they get legalized to loads from a constant pool.
9592 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9593 const ARMSubtarget *ST) {
9594 EVT VT = N->getValueType(0);
9595 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9596 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9597 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9598 SDValue N1 = N->getOperand(1);
9599 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9600 SDValue N0 = N->getOperand(0);
9601 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9602 DAG.MaskedValueIsZero(N0.getOperand(0),
9603 APInt::getHighBitsSet(32, 16)))
9604 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9608 // Nothing to be done for scalar shifts.
9609 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9610 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9613 assert(ST->hasNEON() && "unexpected vector shift");
9616 switch (N->getOpcode()) {
9617 default: llvm_unreachable("unexpected shift opcode");
9620 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9621 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9622 DAG.getConstant(Cnt, MVT::i32));
9627 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9628 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9629 ARMISD::VSHRs : ARMISD::VSHRu);
9630 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9631 DAG.getConstant(Cnt, MVT::i32));
9637 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9638 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9639 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9640 const ARMSubtarget *ST) {
9641 SDValue N0 = N->getOperand(0);
9643 // Check for sign- and zero-extensions of vector extract operations of 8-
9644 // and 16-bit vector elements. NEON supports these directly. They are
9645 // handled during DAG combining because type legalization will promote them
9646 // to 32-bit types and it is messy to recognize the operations after that.
9647 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9648 SDValue Vec = N0.getOperand(0);
9649 SDValue Lane = N0.getOperand(1);
9650 EVT VT = N->getValueType(0);
9651 EVT EltVT = N0.getValueType();
9652 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9654 if (VT == MVT::i32 &&
9655 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9656 TLI.isTypeLegal(Vec.getValueType()) &&
9657 isa<ConstantSDNode>(Lane)) {
9660 switch (N->getOpcode()) {
9661 default: llvm_unreachable("unexpected opcode");
9662 case ISD::SIGN_EXTEND:
9663 Opc = ARMISD::VGETLANEs;
9665 case ISD::ZERO_EXTEND:
9666 case ISD::ANY_EXTEND:
9667 Opc = ARMISD::VGETLANEu;
9670 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9677 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9678 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9679 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9680 const ARMSubtarget *ST) {
9681 // If the target supports NEON, try to use vmax/vmin instructions for f32
9682 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9683 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9684 // a NaN; only do the transformation when it matches that behavior.
9686 // For now only do this when using NEON for FP operations; if using VFP, it
9687 // is not obvious that the benefit outweighs the cost of switching to the
9689 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9690 N->getValueType(0) != MVT::f32)
9693 SDValue CondLHS = N->getOperand(0);
9694 SDValue CondRHS = N->getOperand(1);
9695 SDValue LHS = N->getOperand(2);
9696 SDValue RHS = N->getOperand(3);
9697 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9699 unsigned Opcode = 0;
9701 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9702 IsReversed = false; // x CC y ? x : y
9703 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9704 IsReversed = true ; // x CC y ? y : x
9718 // If LHS is NaN, an ordered comparison will be false and the result will
9719 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9720 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9721 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9722 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9724 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9725 // will return -0, so vmin can only be used for unsafe math or if one of
9726 // the operands is known to be nonzero.
9727 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9728 !DAG.getTarget().Options.UnsafeFPMath &&
9729 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9731 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9740 // If LHS is NaN, an ordered comparison will be false and the result will
9741 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9742 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9743 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9744 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9746 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9747 // will return +0, so vmax can only be used for unsafe math or if one of
9748 // the operands is known to be nonzero.
9749 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9750 !DAG.getTarget().Options.UnsafeFPMath &&
9751 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9753 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9759 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9762 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9764 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9765 SDValue Cmp = N->getOperand(4);
9766 if (Cmp.getOpcode() != ARMISD::CMPZ)
9767 // Only looking at EQ and NE cases.
9770 EVT VT = N->getValueType(0);
9772 SDValue LHS = Cmp.getOperand(0);
9773 SDValue RHS = Cmp.getOperand(1);
9774 SDValue FalseVal = N->getOperand(0);
9775 SDValue TrueVal = N->getOperand(1);
9776 SDValue ARMcc = N->getOperand(2);
9777 ARMCC::CondCodes CC =
9778 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9796 /// FIXME: Turn this into a target neutral optimization?
9798 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9799 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9800 N->getOperand(3), Cmp);
9801 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9803 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9804 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9805 N->getOperand(3), NewCmp);
9808 if (Res.getNode()) {
9809 APInt KnownZero, KnownOne;
9810 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9811 // Capture demanded bits information that would be otherwise lost.
9812 if (KnownZero == 0xfffffffe)
9813 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9814 DAG.getValueType(MVT::i1));
9815 else if (KnownZero == 0xffffff00)
9816 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9817 DAG.getValueType(MVT::i8));
9818 else if (KnownZero == 0xffff0000)
9819 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9820 DAG.getValueType(MVT::i16));
9826 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9827 DAGCombinerInfo &DCI) const {
9828 switch (N->getOpcode()) {
9830 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9831 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9832 case ISD::SUB: return PerformSUBCombine(N, DCI);
9833 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9834 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9835 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9836 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9837 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9838 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9839 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9840 case ISD::STORE: return PerformSTORECombine(N, DCI);
9841 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9842 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9843 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9844 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9845 case ISD::FP_TO_SINT:
9846 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9847 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9848 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9851 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9852 case ISD::SIGN_EXTEND:
9853 case ISD::ZERO_EXTEND:
9854 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9855 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9856 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9857 case ARMISD::VLD2DUP:
9858 case ARMISD::VLD3DUP:
9859 case ARMISD::VLD4DUP:
9860 return CombineBaseUpdate(N, DCI);
9861 case ARMISD::BUILD_VECTOR:
9862 return PerformARMBUILD_VECTORCombine(N, DCI);
9863 case ISD::INTRINSIC_VOID:
9864 case ISD::INTRINSIC_W_CHAIN:
9865 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9866 case Intrinsic::arm_neon_vld1:
9867 case Intrinsic::arm_neon_vld2:
9868 case Intrinsic::arm_neon_vld3:
9869 case Intrinsic::arm_neon_vld4:
9870 case Intrinsic::arm_neon_vld2lane:
9871 case Intrinsic::arm_neon_vld3lane:
9872 case Intrinsic::arm_neon_vld4lane:
9873 case Intrinsic::arm_neon_vst1:
9874 case Intrinsic::arm_neon_vst2:
9875 case Intrinsic::arm_neon_vst3:
9876 case Intrinsic::arm_neon_vst4:
9877 case Intrinsic::arm_neon_vst2lane:
9878 case Intrinsic::arm_neon_vst3lane:
9879 case Intrinsic::arm_neon_vst4lane:
9880 return CombineBaseUpdate(N, DCI);
9888 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9890 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9893 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9897 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9898 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9900 switch (VT.getSimpleVT().SimpleTy) {
9906 // Unaligned access can use (for example) LRDB, LRDH, LDR
9907 if (AllowsUnaligned) {
9909 *Fast = Subtarget->hasV7Ops();
9916 // For any little-endian targets with neon, we can support unaligned ld/st
9917 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9918 // A big-endian target may also explicitly support unaligned accesses
9919 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9929 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9930 unsigned AlignCheck) {
9931 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9932 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9935 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9936 unsigned DstAlign, unsigned SrcAlign,
9937 bool IsMemset, bool ZeroMemset,
9939 MachineFunction &MF) const {
9940 const Function *F = MF.getFunction();
9942 // See if we can use NEON instructions for this...
9943 if ((!IsMemset || ZeroMemset) &&
9944 Subtarget->hasNEON() &&
9945 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9946 Attribute::NoImplicitFloat)) {
9949 (memOpAlign(SrcAlign, DstAlign, 16) ||
9950 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9952 } else if (Size >= 8 &&
9953 (memOpAlign(SrcAlign, DstAlign, 8) ||
9954 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9960 // Lowering to i32/i16 if the size permits.
9966 // Let the target-independent logic figure it out.
9970 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9971 if (Val.getOpcode() != ISD::LOAD)
9974 EVT VT1 = Val.getValueType();
9975 if (!VT1.isSimple() || !VT1.isInteger() ||
9976 !VT2.isSimple() || !VT2.isInteger())
9979 switch (VT1.getSimpleVT().SimpleTy) {
9984 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9991 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9992 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9995 if (!isTypeLegal(EVT::getEVT(Ty1)))
9998 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10000 // Assuming the caller doesn't have a zeroext or signext return parameter,
10001 // truncation all the way down to i1 is valid.
10006 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10010 unsigned Scale = 1;
10011 switch (VT.getSimpleVT().SimpleTy) {
10012 default: return false;
10027 if ((V & (Scale - 1)) != 0)
10030 return V == (V & ((1LL << 5) - 1));
10033 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10034 const ARMSubtarget *Subtarget) {
10035 bool isNeg = false;
10041 switch (VT.getSimpleVT().SimpleTy) {
10042 default: return false;
10047 // + imm12 or - imm8
10049 return V == (V & ((1LL << 8) - 1));
10050 return V == (V & ((1LL << 12) - 1));
10053 // Same as ARM mode. FIXME: NEON?
10054 if (!Subtarget->hasVFP2())
10059 return V == (V & ((1LL << 8) - 1));
10063 /// isLegalAddressImmediate - Return true if the integer value can be used
10064 /// as the offset of the target addressing mode for load / store of the
10066 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10067 const ARMSubtarget *Subtarget) {
10071 if (!VT.isSimple())
10074 if (Subtarget->isThumb1Only())
10075 return isLegalT1AddressImmediate(V, VT);
10076 else if (Subtarget->isThumb2())
10077 return isLegalT2AddressImmediate(V, VT, Subtarget);
10082 switch (VT.getSimpleVT().SimpleTy) {
10083 default: return false;
10088 return V == (V & ((1LL << 12) - 1));
10091 return V == (V & ((1LL << 8) - 1));
10094 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10099 return V == (V & ((1LL << 8) - 1));
10103 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10105 int Scale = AM.Scale;
10109 switch (VT.getSimpleVT().SimpleTy) {
10110 default: return false;
10118 Scale = Scale & ~1;
10119 return Scale == 2 || Scale == 4 || Scale == 8;
10122 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10126 // Note, we allow "void" uses (basically, uses that aren't loads or
10127 // stores), because arm allows folding a scale into many arithmetic
10128 // operations. This should be made more precise and revisited later.
10130 // Allow r << imm, but the imm has to be a multiple of two.
10131 if (Scale & 1) return false;
10132 return isPowerOf2_32(Scale);
10136 /// isLegalAddressingMode - Return true if the addressing mode represented
10137 /// by AM is legal for this target, for a load/store of the specified type.
10138 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10140 EVT VT = getValueType(Ty, true);
10141 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10144 // Can never fold addr of global into load/store.
10148 switch (AM.Scale) {
10149 case 0: // no scale reg, must be "r+i" or "r", or "i".
10152 if (Subtarget->isThumb1Only())
10156 // ARM doesn't support any R+R*scale+imm addr modes.
10160 if (!VT.isSimple())
10163 if (Subtarget->isThumb2())
10164 return isLegalT2ScaledAddressingMode(AM, VT);
10166 int Scale = AM.Scale;
10167 switch (VT.getSimpleVT().SimpleTy) {
10168 default: return false;
10172 if (Scale < 0) Scale = -Scale;
10176 return isPowerOf2_32(Scale & ~1);
10180 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10185 // Note, we allow "void" uses (basically, uses that aren't loads or
10186 // stores), because arm allows folding a scale into many arithmetic
10187 // operations. This should be made more precise and revisited later.
10189 // Allow r << imm, but the imm has to be a multiple of two.
10190 if (Scale & 1) return false;
10191 return isPowerOf2_32(Scale);
10197 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10198 /// icmp immediate, that is the target has icmp instructions which can compare
10199 /// a register against the immediate without having to materialize the
10200 /// immediate into a register.
10201 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10202 // Thumb2 and ARM modes can use cmn for negative immediates.
10203 if (!Subtarget->isThumb())
10204 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10205 if (Subtarget->isThumb2())
10206 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10207 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10208 return Imm >= 0 && Imm <= 255;
10211 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10212 /// *or sub* immediate, that is the target has add or sub instructions which can
10213 /// add a register with the immediate without having to materialize the
10214 /// immediate into a register.
10215 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10216 // Same encoding for add/sub, just flip the sign.
10217 int64_t AbsImm = llvm::abs64(Imm);
10218 if (!Subtarget->isThumb())
10219 return ARM_AM::getSOImmVal(AbsImm) != -1;
10220 if (Subtarget->isThumb2())
10221 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10222 // Thumb1 only has 8-bit unsigned immediate.
10223 return AbsImm >= 0 && AbsImm <= 255;
10226 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10227 bool isSEXTLoad, SDValue &Base,
10228 SDValue &Offset, bool &isInc,
10229 SelectionDAG &DAG) {
10230 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10233 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10234 // AddressingMode 3
10235 Base = Ptr->getOperand(0);
10236 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10237 int RHSC = (int)RHS->getZExtValue();
10238 if (RHSC < 0 && RHSC > -256) {
10239 assert(Ptr->getOpcode() == ISD::ADD);
10241 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10245 isInc = (Ptr->getOpcode() == ISD::ADD);
10246 Offset = Ptr->getOperand(1);
10248 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10249 // AddressingMode 2
10250 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10251 int RHSC = (int)RHS->getZExtValue();
10252 if (RHSC < 0 && RHSC > -0x1000) {
10253 assert(Ptr->getOpcode() == ISD::ADD);
10255 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10256 Base = Ptr->getOperand(0);
10261 if (Ptr->getOpcode() == ISD::ADD) {
10263 ARM_AM::ShiftOpc ShOpcVal=
10264 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10265 if (ShOpcVal != ARM_AM::no_shift) {
10266 Base = Ptr->getOperand(1);
10267 Offset = Ptr->getOperand(0);
10269 Base = Ptr->getOperand(0);
10270 Offset = Ptr->getOperand(1);
10275 isInc = (Ptr->getOpcode() == ISD::ADD);
10276 Base = Ptr->getOperand(0);
10277 Offset = Ptr->getOperand(1);
10281 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10285 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10286 bool isSEXTLoad, SDValue &Base,
10287 SDValue &Offset, bool &isInc,
10288 SelectionDAG &DAG) {
10289 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10292 Base = Ptr->getOperand(0);
10293 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10294 int RHSC = (int)RHS->getZExtValue();
10295 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10296 assert(Ptr->getOpcode() == ISD::ADD);
10298 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10300 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10301 isInc = Ptr->getOpcode() == ISD::ADD;
10302 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10310 /// getPreIndexedAddressParts - returns true by value, base pointer and
10311 /// offset pointer and addressing mode by reference if the node's address
10312 /// can be legally represented as pre-indexed load / store address.
10314 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10316 ISD::MemIndexedMode &AM,
10317 SelectionDAG &DAG) const {
10318 if (Subtarget->isThumb1Only())
10323 bool isSEXTLoad = false;
10324 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10325 Ptr = LD->getBasePtr();
10326 VT = LD->getMemoryVT();
10327 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10328 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10329 Ptr = ST->getBasePtr();
10330 VT = ST->getMemoryVT();
10335 bool isLegal = false;
10336 if (Subtarget->isThumb2())
10337 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10338 Offset, isInc, DAG);
10340 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10341 Offset, isInc, DAG);
10345 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10349 /// getPostIndexedAddressParts - returns true by value, base pointer and
10350 /// offset pointer and addressing mode by reference if this node can be
10351 /// combined with a load / store to form a post-indexed load / store.
10352 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10355 ISD::MemIndexedMode &AM,
10356 SelectionDAG &DAG) const {
10357 if (Subtarget->isThumb1Only())
10362 bool isSEXTLoad = false;
10363 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10364 VT = LD->getMemoryVT();
10365 Ptr = LD->getBasePtr();
10366 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10367 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10368 VT = ST->getMemoryVT();
10369 Ptr = ST->getBasePtr();
10374 bool isLegal = false;
10375 if (Subtarget->isThumb2())
10376 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10379 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10385 // Swap base ptr and offset to catch more post-index load / store when
10386 // it's legal. In Thumb2 mode, offset must be an immediate.
10387 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10388 !Subtarget->isThumb2())
10389 std::swap(Base, Offset);
10391 // Post-indexed load / store update the base pointer.
10396 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10400 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10403 const SelectionDAG &DAG,
10404 unsigned Depth) const {
10405 unsigned BitWidth = KnownOne.getBitWidth();
10406 KnownZero = KnownOne = APInt(BitWidth, 0);
10407 switch (Op.getOpcode()) {
10413 // These nodes' second result is a boolean
10414 if (Op.getResNo() == 0)
10416 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10418 case ARMISD::CMOV: {
10419 // Bits are known zero/one if known on the LHS and RHS.
10420 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10421 if (KnownZero == 0 && KnownOne == 0) return;
10423 APInt KnownZeroRHS, KnownOneRHS;
10424 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10425 KnownZero &= KnownZeroRHS;
10426 KnownOne &= KnownOneRHS;
10429 case ISD::INTRINSIC_W_CHAIN: {
10430 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10431 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10434 case Intrinsic::arm_ldaex:
10435 case Intrinsic::arm_ldrex: {
10436 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10437 unsigned MemBits = VT.getScalarType().getSizeInBits();
10438 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10446 //===----------------------------------------------------------------------===//
10447 // ARM Inline Assembly Support
10448 //===----------------------------------------------------------------------===//
10450 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10451 // Looking for "rev" which is V6+.
10452 if (!Subtarget->hasV6Ops())
10455 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10456 std::string AsmStr = IA->getAsmString();
10457 SmallVector<StringRef, 4> AsmPieces;
10458 SplitString(AsmStr, AsmPieces, ";\n");
10460 switch (AsmPieces.size()) {
10461 default: return false;
10463 AsmStr = AsmPieces[0];
10465 SplitString(AsmStr, AsmPieces, " \t,");
10468 if (AsmPieces.size() == 3 &&
10469 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10470 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10471 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10472 if (Ty && Ty->getBitWidth() == 32)
10473 return IntrinsicLowering::LowerToByteSwap(CI);
10481 /// getConstraintType - Given a constraint letter, return the type of
10482 /// constraint it is for this target.
10483 ARMTargetLowering::ConstraintType
10484 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10485 if (Constraint.size() == 1) {
10486 switch (Constraint[0]) {
10488 case 'l': return C_RegisterClass;
10489 case 'w': return C_RegisterClass;
10490 case 'h': return C_RegisterClass;
10491 case 'x': return C_RegisterClass;
10492 case 't': return C_RegisterClass;
10493 case 'j': return C_Other; // Constant for movw.
10494 // An address with a single base register. Due to the way we
10495 // currently handle addresses it is the same as an 'r' memory constraint.
10496 case 'Q': return C_Memory;
10498 } else if (Constraint.size() == 2) {
10499 switch (Constraint[0]) {
10501 // All 'U+' constraints are addresses.
10502 case 'U': return C_Memory;
10505 return TargetLowering::getConstraintType(Constraint);
10508 /// Examine constraint type and operand type and determine a weight value.
10509 /// This object must already have been set up with the operand type
10510 /// and the current alternative constraint selected.
10511 TargetLowering::ConstraintWeight
10512 ARMTargetLowering::getSingleConstraintMatchWeight(
10513 AsmOperandInfo &info, const char *constraint) const {
10514 ConstraintWeight weight = CW_Invalid;
10515 Value *CallOperandVal = info.CallOperandVal;
10516 // If we don't have a value, we can't do a match,
10517 // but allow it at the lowest weight.
10518 if (!CallOperandVal)
10520 Type *type = CallOperandVal->getType();
10521 // Look at the constraint type.
10522 switch (*constraint) {
10524 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10527 if (type->isIntegerTy()) {
10528 if (Subtarget->isThumb())
10529 weight = CW_SpecificReg;
10531 weight = CW_Register;
10535 if (type->isFloatingPointTy())
10536 weight = CW_Register;
10542 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10544 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10546 if (Constraint.size() == 1) {
10547 // GCC ARM Constraint Letters
10548 switch (Constraint[0]) {
10549 case 'l': // Low regs or general regs.
10550 if (Subtarget->isThumb())
10551 return RCPair(0U, &ARM::tGPRRegClass);
10552 return RCPair(0U, &ARM::GPRRegClass);
10553 case 'h': // High regs or no regs.
10554 if (Subtarget->isThumb())
10555 return RCPair(0U, &ARM::hGPRRegClass);
10558 if (Subtarget->isThumb1Only())
10559 return RCPair(0U, &ARM::tGPRRegClass);
10560 return RCPair(0U, &ARM::GPRRegClass);
10562 if (VT == MVT::Other)
10564 if (VT == MVT::f32)
10565 return RCPair(0U, &ARM::SPRRegClass);
10566 if (VT.getSizeInBits() == 64)
10567 return RCPair(0U, &ARM::DPRRegClass);
10568 if (VT.getSizeInBits() == 128)
10569 return RCPair(0U, &ARM::QPRRegClass);
10572 if (VT == MVT::Other)
10574 if (VT == MVT::f32)
10575 return RCPair(0U, &ARM::SPR_8RegClass);
10576 if (VT.getSizeInBits() == 64)
10577 return RCPair(0U, &ARM::DPR_8RegClass);
10578 if (VT.getSizeInBits() == 128)
10579 return RCPair(0U, &ARM::QPR_8RegClass);
10582 if (VT == MVT::f32)
10583 return RCPair(0U, &ARM::SPRRegClass);
10587 if (StringRef("{cc}").equals_lower(Constraint))
10588 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10590 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10593 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10594 /// vector. If it is invalid, don't add anything to Ops.
10595 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10596 std::string &Constraint,
10597 std::vector<SDValue>&Ops,
10598 SelectionDAG &DAG) const {
10601 // Currently only support length 1 constraints.
10602 if (Constraint.length() != 1) return;
10604 char ConstraintLetter = Constraint[0];
10605 switch (ConstraintLetter) {
10608 case 'I': case 'J': case 'K': case 'L':
10609 case 'M': case 'N': case 'O':
10610 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10614 int64_t CVal64 = C->getSExtValue();
10615 int CVal = (int) CVal64;
10616 // None of these constraints allow values larger than 32 bits. Check
10617 // that the value fits in an int.
10618 if (CVal != CVal64)
10621 switch (ConstraintLetter) {
10623 // Constant suitable for movw, must be between 0 and
10625 if (Subtarget->hasV6T2Ops())
10626 if (CVal >= 0 && CVal <= 65535)
10630 if (Subtarget->isThumb1Only()) {
10631 // This must be a constant between 0 and 255, for ADD
10633 if (CVal >= 0 && CVal <= 255)
10635 } else if (Subtarget->isThumb2()) {
10636 // A constant that can be used as an immediate value in a
10637 // data-processing instruction.
10638 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10641 // A constant that can be used as an immediate value in a
10642 // data-processing instruction.
10643 if (ARM_AM::getSOImmVal(CVal) != -1)
10649 if (Subtarget->isThumb()) { // FIXME thumb2
10650 // This must be a constant between -255 and -1, for negated ADD
10651 // immediates. This can be used in GCC with an "n" modifier that
10652 // prints the negated value, for use with SUB instructions. It is
10653 // not useful otherwise but is implemented for compatibility.
10654 if (CVal >= -255 && CVal <= -1)
10657 // This must be a constant between -4095 and 4095. It is not clear
10658 // what this constraint is intended for. Implemented for
10659 // compatibility with GCC.
10660 if (CVal >= -4095 && CVal <= 4095)
10666 if (Subtarget->isThumb1Only()) {
10667 // A 32-bit value where only one byte has a nonzero value. Exclude
10668 // zero to match GCC. This constraint is used by GCC internally for
10669 // constants that can be loaded with a move/shift combination.
10670 // It is not useful otherwise but is implemented for compatibility.
10671 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10673 } else if (Subtarget->isThumb2()) {
10674 // A constant whose bitwise inverse can be used as an immediate
10675 // value in a data-processing instruction. This can be used in GCC
10676 // with a "B" modifier that prints the inverted value, for use with
10677 // BIC and MVN instructions. It is not useful otherwise but is
10678 // implemented for compatibility.
10679 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10682 // A constant whose bitwise inverse can be used as an immediate
10683 // value in a data-processing instruction. This can be used in GCC
10684 // with a "B" modifier that prints the inverted value, for use with
10685 // BIC and MVN instructions. It is not useful otherwise but is
10686 // implemented for compatibility.
10687 if (ARM_AM::getSOImmVal(~CVal) != -1)
10693 if (Subtarget->isThumb1Only()) {
10694 // This must be a constant between -7 and 7,
10695 // for 3-operand ADD/SUB immediate instructions.
10696 if (CVal >= -7 && CVal < 7)
10698 } else if (Subtarget->isThumb2()) {
10699 // A constant whose negation can be used as an immediate value in a
10700 // data-processing instruction. This can be used in GCC with an "n"
10701 // modifier that prints the negated value, for use with SUB
10702 // instructions. It is not useful otherwise but is implemented for
10704 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10707 // A constant whose negation can be used as an immediate value in a
10708 // data-processing instruction. This can be used in GCC with an "n"
10709 // modifier that prints the negated value, for use with SUB
10710 // instructions. It is not useful otherwise but is implemented for
10712 if (ARM_AM::getSOImmVal(-CVal) != -1)
10718 if (Subtarget->isThumb()) { // FIXME thumb2
10719 // This must be a multiple of 4 between 0 and 1020, for
10720 // ADD sp + immediate.
10721 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10724 // A power of two or a constant between 0 and 32. This is used in
10725 // GCC for the shift amount on shifted register operands, but it is
10726 // useful in general for any shift amounts.
10727 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10733 if (Subtarget->isThumb()) { // FIXME thumb2
10734 // This must be a constant between 0 and 31, for shift amounts.
10735 if (CVal >= 0 && CVal <= 31)
10741 if (Subtarget->isThumb()) { // FIXME thumb2
10742 // This must be a multiple of 4 between -508 and 508, for
10743 // ADD/SUB sp = sp + immediate.
10744 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10749 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10753 if (Result.getNode()) {
10754 Ops.push_back(Result);
10757 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10760 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10761 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10762 unsigned Opcode = Op->getOpcode();
10763 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10764 "Invalid opcode for Div/Rem lowering");
10765 bool isSigned = (Opcode == ISD::SDIVREM);
10766 EVT VT = Op->getValueType(0);
10767 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10770 switch (VT.getSimpleVT().SimpleTy) {
10771 default: llvm_unreachable("Unexpected request for libcall!");
10772 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10773 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10774 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10775 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10778 SDValue InChain = DAG.getEntryNode();
10780 TargetLowering::ArgListTy Args;
10781 TargetLowering::ArgListEntry Entry;
10782 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10783 EVT ArgVT = Op->getOperand(i).getValueType();
10784 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10785 Entry.Node = Op->getOperand(i);
10787 Entry.isSExt = isSigned;
10788 Entry.isZExt = !isSigned;
10789 Args.push_back(Entry);
10792 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10795 Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
10798 TargetLowering::CallLoweringInfo CLI(DAG);
10799 CLI.setDebugLoc(dl).setChain(InChain)
10800 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10801 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10803 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10804 return CallInfo.first;
10808 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10809 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10813 SDValue Chain = Op.getOperand(0);
10814 SDValue Size = Op.getOperand(1);
10816 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10817 DAG.getConstant(2, MVT::i32));
10820 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10821 Flag = Chain.getValue(1);
10823 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10824 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10826 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10827 Chain = NewSP.getValue(1);
10829 SDValue Ops[2] = { NewSP, Chain };
10830 return DAG.getMergeValues(Ops, DL);
10833 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10834 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10835 "Unexpected type for custom-lowering FP_EXTEND");
10838 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10840 SDValue SrcVal = Op.getOperand(0);
10841 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10842 /*isSigned*/ false, SDLoc(Op)).first;
10845 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10846 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10847 Subtarget->isFPOnlySP() &&
10848 "Unexpected type for custom-lowering FP_ROUND");
10851 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10853 SDValue SrcVal = Op.getOperand(0);
10854 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10855 /*isSigned*/ false, SDLoc(Op)).first;
10859 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10860 // The ARM target isn't yet aware of offsets.
10864 bool ARM::isBitFieldInvertedMask(unsigned v) {
10865 if (v == 0xffffffff)
10868 // there can be 1's on either or both "outsides", all the "inside"
10869 // bits must be 0's
10870 unsigned TO = CountTrailingOnes_32(v);
10871 unsigned LO = CountLeadingOnes_32(v);
10872 v = (v >> TO) << TO;
10873 v = (v << LO) >> LO;
10877 /// isFPImmLegal - Returns true if the target can instruction select the
10878 /// specified FP immediate natively. If false, the legalizer will
10879 /// materialize the FP immediate as a load from a constant pool.
10880 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10881 if (!Subtarget->hasVFP3())
10883 if (VT == MVT::f32)
10884 return ARM_AM::getFP32Imm(Imm) != -1;
10885 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10886 return ARM_AM::getFP64Imm(Imm) != -1;
10890 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10891 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10892 /// specified in the intrinsic calls.
10893 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10895 unsigned Intrinsic) const {
10896 switch (Intrinsic) {
10897 case Intrinsic::arm_neon_vld1:
10898 case Intrinsic::arm_neon_vld2:
10899 case Intrinsic::arm_neon_vld3:
10900 case Intrinsic::arm_neon_vld4:
10901 case Intrinsic::arm_neon_vld2lane:
10902 case Intrinsic::arm_neon_vld3lane:
10903 case Intrinsic::arm_neon_vld4lane: {
10904 Info.opc = ISD::INTRINSIC_W_CHAIN;
10905 // Conservatively set memVT to the entire set of vectors loaded.
10906 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10907 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10908 Info.ptrVal = I.getArgOperand(0);
10910 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10911 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10912 Info.vol = false; // volatile loads with NEON intrinsics not supported
10913 Info.readMem = true;
10914 Info.writeMem = false;
10917 case Intrinsic::arm_neon_vst1:
10918 case Intrinsic::arm_neon_vst2:
10919 case Intrinsic::arm_neon_vst3:
10920 case Intrinsic::arm_neon_vst4:
10921 case Intrinsic::arm_neon_vst2lane:
10922 case Intrinsic::arm_neon_vst3lane:
10923 case Intrinsic::arm_neon_vst4lane: {
10924 Info.opc = ISD::INTRINSIC_VOID;
10925 // Conservatively set memVT to the entire set of vectors stored.
10926 unsigned NumElts = 0;
10927 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10928 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10929 if (!ArgTy->isVectorTy())
10931 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10933 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10934 Info.ptrVal = I.getArgOperand(0);
10936 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10937 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10938 Info.vol = false; // volatile stores with NEON intrinsics not supported
10939 Info.readMem = false;
10940 Info.writeMem = true;
10943 case Intrinsic::arm_ldaex:
10944 case Intrinsic::arm_ldrex: {
10945 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10946 Info.opc = ISD::INTRINSIC_W_CHAIN;
10947 Info.memVT = MVT::getVT(PtrTy->getElementType());
10948 Info.ptrVal = I.getArgOperand(0);
10950 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10952 Info.readMem = true;
10953 Info.writeMem = false;
10956 case Intrinsic::arm_stlex:
10957 case Intrinsic::arm_strex: {
10958 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10959 Info.opc = ISD::INTRINSIC_W_CHAIN;
10960 Info.memVT = MVT::getVT(PtrTy->getElementType());
10961 Info.ptrVal = I.getArgOperand(1);
10963 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10965 Info.readMem = false;
10966 Info.writeMem = true;
10969 case Intrinsic::arm_stlexd:
10970 case Intrinsic::arm_strexd: {
10971 Info.opc = ISD::INTRINSIC_W_CHAIN;
10972 Info.memVT = MVT::i64;
10973 Info.ptrVal = I.getArgOperand(2);
10977 Info.readMem = false;
10978 Info.writeMem = true;
10981 case Intrinsic::arm_ldaexd:
10982 case Intrinsic::arm_ldrexd: {
10983 Info.opc = ISD::INTRINSIC_W_CHAIN;
10984 Info.memVT = MVT::i64;
10985 Info.ptrVal = I.getArgOperand(0);
10989 Info.readMem = true;
10990 Info.writeMem = false;
11000 /// \brief Returns true if it is beneficial to convert a load of a constant
11001 /// to just the constant itself.
11002 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11004 assert(Ty->isIntegerTy());
11006 unsigned Bits = Ty->getPrimitiveSizeInBits();
11007 if (Bits == 0 || Bits > 32)
11012 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11014 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11015 ARM_MB::MemBOpt Domain) const {
11016 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11018 // First, if the target has no DMB, see what fallback we can use.
11019 if (!Subtarget->hasDataBarrier()) {
11020 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11021 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11023 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11024 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11025 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11026 Builder.getInt32(0), Builder.getInt32(7),
11027 Builder.getInt32(10), Builder.getInt32(5)};
11028 return Builder.CreateCall(MCR, args);
11030 // Instead of using barriers, atomic accesses on these subtargets use
11032 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11035 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11036 // Only a full system barrier exists in the M-class architectures.
11037 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11038 Constant *CDomain = Builder.getInt32(Domain);
11039 return Builder.CreateCall(DMB, CDomain);
11043 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11044 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11045 AtomicOrdering Ord, bool IsStore,
11046 bool IsLoad) const {
11047 if (!getInsertFencesForAtomic())
11053 llvm_unreachable("Invalid fence: unordered/non-atomic");
11056 return nullptr; // Nothing to do
11057 case SequentiallyConsistent:
11059 return nullptr; // Nothing to do
11062 case AcquireRelease:
11063 if (Subtarget->isSwift())
11064 return makeDMB(Builder, ARM_MB::ISHST);
11065 // FIXME: add a comment with a link to documentation justifying this.
11067 return makeDMB(Builder, ARM_MB::ISH);
11069 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11072 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11073 AtomicOrdering Ord, bool IsStore,
11074 bool IsLoad) const {
11075 if (!getInsertFencesForAtomic())
11081 llvm_unreachable("Invalid fence: unordered/not-atomic");
11084 return nullptr; // Nothing to do
11086 case AcquireRelease:
11087 case SequentiallyConsistent:
11088 return makeDMB(Builder, ARM_MB::ISH);
11090 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11093 // Loads and stores less than 64-bits are already atomic; ones above that
11094 // are doomed anyway, so defer to the default libcall and blame the OS when
11095 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11096 // anything for those.
11097 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11098 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11099 return (Size == 64) && !Subtarget->isMClass();
11102 // Loads and stores less than 64-bits are already atomic; ones above that
11103 // are doomed anyway, so defer to the default libcall and blame the OS when
11104 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11105 // anything for those.
11106 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11107 // guarantee, see DDI0406C ARM architecture reference manual,
11108 // sections A8.8.72-74 LDRD)
11109 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11110 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11111 return (Size == 64) && !Subtarget->isMClass();
11114 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11115 // and up to 64 bits on the non-M profiles
11116 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11117 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11118 return Size <= (Subtarget->isMClass() ? 32U : 64U);
11121 // This has so far only been implemented for MachO.
11122 bool ARMTargetLowering::useLoadStackGuardNode() const {
11123 return Subtarget->isTargetMachO();
11126 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11127 unsigned &Cost) const {
11128 // If we do not have NEON, vector types are not natively supported.
11129 if (!Subtarget->hasNEON())
11132 // Floating point values and vector values map to the same register file.
11133 // Therefore, althought we could do a store extract of a vector type, this is
11134 // better to leave at float as we have more freedom in the addressing mode for
11136 if (VectorTy->isFPOrFPVectorTy())
11139 // If the index is unknown at compile time, this is very expensive to lower
11140 // and it is not possible to combine the store with the extract.
11141 if (!isa<ConstantInt>(Idx))
11144 assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11145 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11146 // We can do a store + vector extract on any vector that fits perfectly in a D
11148 if (BitWidth == 64 || BitWidth == 128) {
11155 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11156 AtomicOrdering Ord) const {
11157 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11158 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11159 bool IsAcquire = isAtLeastAcquire(Ord);
11161 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11162 // intrinsic must return {i32, i32} and we have to recombine them into a
11163 // single i64 here.
11164 if (ValTy->getPrimitiveSizeInBits() == 64) {
11165 Intrinsic::ID Int =
11166 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11167 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11169 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11170 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11172 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11173 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11174 if (!Subtarget->isLittle())
11175 std::swap (Lo, Hi);
11176 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11177 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11178 return Builder.CreateOr(
11179 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11182 Type *Tys[] = { Addr->getType() };
11183 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11184 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11186 return Builder.CreateTruncOrBitCast(
11187 Builder.CreateCall(Ldrex, Addr),
11188 cast<PointerType>(Addr->getType())->getElementType());
11191 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11193 AtomicOrdering Ord) const {
11194 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11195 bool IsRelease = isAtLeastRelease(Ord);
11197 // Since the intrinsics must have legal type, the i64 intrinsics take two
11198 // parameters: "i32, i32". We must marshal Val into the appropriate form
11199 // before the call.
11200 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11201 Intrinsic::ID Int =
11202 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11203 Function *Strex = Intrinsic::getDeclaration(M, Int);
11204 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11206 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11207 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11208 if (!Subtarget->isLittle())
11209 std::swap (Lo, Hi);
11210 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11211 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11214 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11215 Type *Tys[] = { Addr->getType() };
11216 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11218 return Builder.CreateCall2(
11219 Strex, Builder.CreateZExtOrBitCast(
11220 Val, Strex->getFunctionType()->getParamType(0)),
11232 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11233 uint64_t &Members) {
11234 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11235 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11236 uint64_t SubMembers = 0;
11237 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11239 Members += SubMembers;
11241 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11242 uint64_t SubMembers = 0;
11243 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11245 Members += SubMembers * AT->getNumElements();
11246 } else if (Ty->isFloatTy()) {
11247 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11251 } else if (Ty->isDoubleTy()) {
11252 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11256 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11263 return VT->getBitWidth() == 64;
11265 return VT->getBitWidth() == 128;
11267 switch (VT->getBitWidth()) {
11280 return (Members > 0 && Members <= 4);
11283 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11284 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11285 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11286 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11287 CallingConv::ARM_AAPCS_VFP)
11290 HABaseType Base = HA_UNKNOWN;
11291 uint64_t Members = 0;
11292 bool result = isHomogeneousAggregate(Ty, Base, Members);
11293 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());