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 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160 if (TT.isOSBinFormatMachO())
161 return new TargetLoweringObjectFileMachO();
162 if (TT.isOSWindows())
163 return new TargetLoweringObjectFileCOFF();
164 return new ARMElfTargetObjectFile();
167 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM)
168 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169 Subtarget = &TM.getSubtarget<ARMSubtarget>();
170 RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171 Itins = TM.getSubtargetImpl()->getInstrItineraryData();
173 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
175 if (Subtarget->isTargetMachO()) {
176 // Uses VFP for Thumb libfuncs if available.
177 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179 // Single-precision floating-point arithmetic.
180 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
185 // Double-precision floating-point arithmetic.
186 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
191 // Single-precision comparisons.
192 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
199 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
201 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
210 // Double-precision comparisons.
211 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
218 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
220 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
229 // Floating-point to integer conversions.
230 // i64 conversions are done via library routines even when generating VFP
231 // instructions, so use the same ones.
232 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
237 // Conversions between floating types.
238 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
241 // Integer to floating-point conversions.
242 // i64 conversions are done via library routines even when generating VFP
243 // instructions, so use the same ones.
244 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245 // e.g., __floatunsidf vs. __floatunssidfvfp.
246 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
253 // These libcalls are not available in 32-bit.
254 setLibcallName(RTLIB::SHL_I128, nullptr);
255 setLibcallName(RTLIB::SRL_I128, nullptr);
256 setLibcallName(RTLIB::SRA_I128, nullptr);
258 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259 !Subtarget->isTargetWindows()) {
260 static const struct {
261 const RTLIB::Libcall Op;
262 const char * const Name;
263 const CallingConv::ID CC;
264 const ISD::CondCode Cond;
266 // Double-precision floating-point arithmetic helper functions
267 // RTABI chapter 4.1.2, Table 2
268 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
273 // Double-precision floating-point comparison helper functions
274 // RTABI chapter 4.1.2, Table 3
275 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
284 // Single-precision floating-point arithmetic helper functions
285 // RTABI chapter 4.1.2, Table 4
286 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
291 // Single-precision floating-point comparison helper functions
292 // RTABI chapter 4.1.2, Table 5
293 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
302 // Floating-point to integer conversions.
303 // RTABI chapter 4.1.2, Table 6
304 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313 // Conversions between floating types.
314 // RTABI chapter 4.1.2, Table 7
315 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316 { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
319 // Integer to floating-point conversions.
320 // RTABI chapter 4.1.2, Table 8
321 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330 // Long long helper functions
331 // RTABI chapter 4.2, Table 9
332 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
337 // Integer division functions
338 // RTABI chapter 4.3.1
339 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 // RTABI chapter 4.3.4
350 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
355 for (const auto &LC : LibraryCalls) {
356 setLibcallName(LC.Op, LC.Name);
357 setLibcallCallingConv(LC.Op, LC.CC);
358 if (LC.Cond != ISD::SETCC_INVALID)
359 setCmpLibcallCC(LC.Op, LC.Cond);
363 if (Subtarget->isTargetWindows()) {
364 static const struct {
365 const RTLIB::Libcall Op;
366 const char * const Name;
367 const CallingConv::ID CC;
369 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
379 for (const auto &LC : LibraryCalls) {
380 setLibcallName(LC.Op, LC.Name);
381 setLibcallCallingConv(LC.Op, LC.CC);
385 // Use divmod compiler-rt calls for iOS 5.0 and later.
386 if (Subtarget->getTargetTriple().isiOS() &&
387 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
392 // The half <-> float conversion functions are always soft-float, but are
393 // needed for some targets which use a hard-float calling convention by
395 if (Subtarget->isAAPCS_ABI()) {
396 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
397 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
398 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
400 setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
401 setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
402 setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
405 if (Subtarget->isThumb1Only())
406 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
408 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
409 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
410 !Subtarget->isThumb1Only()) {
411 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
412 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
415 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419 setTruncStoreAction((MVT::SimpleValueType)VT,
420 (MVT::SimpleValueType)InnerVT, Expand);
421 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
425 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
430 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
433 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
436 if (Subtarget->hasNEON()) {
437 addDRTypeForNEON(MVT::v2f32);
438 addDRTypeForNEON(MVT::v8i8);
439 addDRTypeForNEON(MVT::v4i16);
440 addDRTypeForNEON(MVT::v2i32);
441 addDRTypeForNEON(MVT::v1i64);
443 addQRTypeForNEON(MVT::v4f32);
444 addQRTypeForNEON(MVT::v2f64);
445 addQRTypeForNEON(MVT::v16i8);
446 addQRTypeForNEON(MVT::v8i16);
447 addQRTypeForNEON(MVT::v4i32);
448 addQRTypeForNEON(MVT::v2i64);
450 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451 // neither Neon nor VFP support any arithmetic operations on it.
452 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453 // supported for v4f32.
454 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457 // FIXME: Code duplication: FDIV and FREM are expanded always, see
458 // ARMTargetLowering::addTypeForNEON method for details.
459 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461 // FIXME: Create unittest.
462 // In another words, find a way when "copysign" appears in DAG with vector
464 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465 // FIXME: Code duplication: SETCC has custom operation action, see
466 // ARMTargetLowering::addTypeForNEON method for details.
467 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468 // FIXME: Create unittest for FNEG and for FABS.
469 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
489 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
505 // Mark v2f32 intrinsics.
506 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
522 // Neon does not support some operations on v1i64 and v2i64 types.
523 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524 // Custom handling for some quad-vector types to detect VMULL.
525 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528 // Custom handling for some vector types to avoid expensive expansions
529 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536 // a destination type that is wider than the source, and nor does
537 // it have a FP_TO_[SU]INT instruction with a narrower destination than
539 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
544 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
545 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
547 // NEON does not have single instruction CTPOP for vectors with element
548 // types wider than 8-bits. However, custom lowering can leverage the
549 // v8i8/v16i8 vcnt instruction.
550 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
551 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
552 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
553 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
555 // NEON only has FMA instructions as of VFP4.
556 if (!Subtarget->hasVFP4()) {
557 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
561 setTargetDAGCombine(ISD::INTRINSIC_VOID);
562 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564 setTargetDAGCombine(ISD::SHL);
565 setTargetDAGCombine(ISD::SRL);
566 setTargetDAGCombine(ISD::SRA);
567 setTargetDAGCombine(ISD::SIGN_EXTEND);
568 setTargetDAGCombine(ISD::ZERO_EXTEND);
569 setTargetDAGCombine(ISD::ANY_EXTEND);
570 setTargetDAGCombine(ISD::SELECT_CC);
571 setTargetDAGCombine(ISD::BUILD_VECTOR);
572 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574 setTargetDAGCombine(ISD::STORE);
575 setTargetDAGCombine(ISD::FP_TO_SINT);
576 setTargetDAGCombine(ISD::FP_TO_UINT);
577 setTargetDAGCombine(ISD::FDIV);
579 // It is legal to extload from v4i8 to v4i16 or v4i32.
580 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581 MVT::v4i16, MVT::v2i16,
583 for (unsigned i = 0; i < 6; ++i) {
584 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
590 // ARM and Thumb2 support UMLAL/SMLAL.
591 if (!Subtarget->isThumb1Only())
592 setTargetDAGCombine(ISD::ADDC);
594 if (Subtarget->isFPOnlySP()) {
595 // When targetting a floating-point unit with only single-precision
596 // operations, f64 is legal for the few double-precision instructions which
597 // are present However, no double-precision operations other than moves,
598 // loads and stores are provided by the hardware.
599 setOperationAction(ISD::FADD, MVT::f64, Expand);
600 setOperationAction(ISD::FSUB, MVT::f64, Expand);
601 setOperationAction(ISD::FMUL, MVT::f64, Expand);
602 setOperationAction(ISD::FMA, MVT::f64, Expand);
603 setOperationAction(ISD::FDIV, MVT::f64, Expand);
604 setOperationAction(ISD::FREM, MVT::f64, Expand);
605 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
606 setOperationAction(ISD::FGETSIGN, MVT::f64, Expand);
607 setOperationAction(ISD::FNEG, MVT::f64, Expand);
608 setOperationAction(ISD::FABS, MVT::f64, Expand);
609 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
610 setOperationAction(ISD::FSIN, MVT::f64, Expand);
611 setOperationAction(ISD::FCOS, MVT::f64, Expand);
612 setOperationAction(ISD::FPOWI, MVT::f64, Expand);
613 setOperationAction(ISD::FPOW, MVT::f64, Expand);
614 setOperationAction(ISD::FLOG, MVT::f64, Expand);
615 setOperationAction(ISD::FLOG2, MVT::f64, Expand);
616 setOperationAction(ISD::FLOG10, MVT::f64, Expand);
617 setOperationAction(ISD::FEXP, MVT::f64, Expand);
618 setOperationAction(ISD::FEXP2, MVT::f64, Expand);
619 setOperationAction(ISD::FCEIL, MVT::f64, Expand);
620 setOperationAction(ISD::FTRUNC, MVT::f64, Expand);
621 setOperationAction(ISD::FRINT, MVT::f64, Expand);
622 setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
623 setOperationAction(ISD::FFLOOR, MVT::f64, Expand);
624 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
625 setOperationAction(ISD::FP_EXTEND, MVT::f64, Custom);
628 computeRegisterProperties();
630 // ARM does not have floating-point extending loads.
631 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
634 // ... or truncating stores
635 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
639 // ARM does not have i1 sign extending load.
640 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
642 // ARM supports all 4 flavors of integer indexed load / store.
643 if (!Subtarget->isThumb1Only()) {
644 for (unsigned im = (unsigned)ISD::PRE_INC;
645 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
646 setIndexedLoadAction(im, MVT::i1, Legal);
647 setIndexedLoadAction(im, MVT::i8, Legal);
648 setIndexedLoadAction(im, MVT::i16, Legal);
649 setIndexedLoadAction(im, MVT::i32, Legal);
650 setIndexedStoreAction(im, MVT::i1, Legal);
651 setIndexedStoreAction(im, MVT::i8, Legal);
652 setIndexedStoreAction(im, MVT::i16, Legal);
653 setIndexedStoreAction(im, MVT::i32, Legal);
657 setOperationAction(ISD::SADDO, MVT::i32, Custom);
658 setOperationAction(ISD::UADDO, MVT::i32, Custom);
659 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
660 setOperationAction(ISD::USUBO, MVT::i32, Custom);
662 // i64 operation support.
663 setOperationAction(ISD::MUL, MVT::i64, Expand);
664 setOperationAction(ISD::MULHU, MVT::i32, Expand);
665 if (Subtarget->isThumb1Only()) {
666 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
667 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
669 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
670 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
671 setOperationAction(ISD::MULHS, MVT::i32, Expand);
673 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
674 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
675 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
676 setOperationAction(ISD::SRL, MVT::i64, Custom);
677 setOperationAction(ISD::SRA, MVT::i64, Custom);
679 if (!Subtarget->isThumb1Only()) {
680 // FIXME: We should do this for Thumb1 as well.
681 setOperationAction(ISD::ADDC, MVT::i32, Custom);
682 setOperationAction(ISD::ADDE, MVT::i32, Custom);
683 setOperationAction(ISD::SUBC, MVT::i32, Custom);
684 setOperationAction(ISD::SUBE, MVT::i32, Custom);
687 // ARM does not have ROTL.
688 setOperationAction(ISD::ROTL, MVT::i32, Expand);
689 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
690 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
691 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
692 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
694 // These just redirect to CTTZ and CTLZ on ARM.
695 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
696 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
698 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
700 // Only ARMv6 has BSWAP.
701 if (!Subtarget->hasV6Ops())
702 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
704 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
705 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
706 // These are expanded into libcalls if the cpu doesn't have HW divider.
707 setOperationAction(ISD::SDIV, MVT::i32, Expand);
708 setOperationAction(ISD::UDIV, MVT::i32, Expand);
711 // FIXME: Also set divmod for SREM on EABI
712 setOperationAction(ISD::SREM, MVT::i32, Expand);
713 setOperationAction(ISD::UREM, MVT::i32, Expand);
714 // Register based DivRem for AEABI (RTABI 4.2)
715 if (Subtarget->isTargetAEABI()) {
716 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
717 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
718 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
719 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
720 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
721 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
722 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
723 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
725 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
726 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
727 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
728 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
729 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
730 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
731 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
732 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
734 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
735 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
737 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
738 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
741 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
742 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
743 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
744 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
745 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
747 setOperationAction(ISD::TRAP, MVT::Other, Legal);
749 // Use the default implementation.
750 setOperationAction(ISD::VASTART, MVT::Other, Custom);
751 setOperationAction(ISD::VAARG, MVT::Other, Expand);
752 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
753 setOperationAction(ISD::VAEND, MVT::Other, Expand);
754 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
755 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
757 if (!Subtarget->isTargetMachO()) {
758 // Non-MachO platforms may return values in these registers via the
759 // personality function.
760 setExceptionPointerRegister(ARM::R0);
761 setExceptionSelectorRegister(ARM::R1);
764 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
765 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
767 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
769 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
770 // the default expansion. If we are targeting a single threaded system,
771 // then set them all for expand so we can lower them later into their
773 if (TM.Options.ThreadModel == ThreadModel::Single)
774 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
775 else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777 // to ldrex/strex loops already.
778 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
780 // On v8, we have particularly efficient implementations of atomic fences
781 // if they can be combined with nearby atomic loads and stores.
782 if (!Subtarget->hasV8Ops()) {
783 // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
784 setInsertFencesForAtomic(true);
787 // If there's anything we can use as a barrier, go through custom lowering
789 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
790 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
792 // Set them all for expansion, which will force libcalls.
793 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806 // Unordered/Monotonic case.
807 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
811 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
813 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814 if (!Subtarget->hasV6Ops()) {
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
818 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
820 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821 !Subtarget->isThumb1Only()) {
822 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823 // iff target supports vfp2.
824 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
828 // We want to custom lower some of our intrinsics.
829 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830 if (Subtarget->isTargetDarwin()) {
831 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
836 setOperationAction(ISD::SETCC, MVT::i32, Expand);
837 setOperationAction(ISD::SETCC, MVT::f32, Expand);
838 setOperationAction(ISD::SETCC, MVT::f64, Expand);
839 setOperationAction(ISD::SELECT, MVT::i32, Custom);
840 setOperationAction(ISD::SELECT, MVT::f32, Custom);
841 setOperationAction(ISD::SELECT, MVT::f64, Custom);
842 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
846 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
847 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
848 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
849 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
850 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
852 // We don't support sin/cos/fmod/copysign/pow
853 setOperationAction(ISD::FSIN, MVT::f64, Expand);
854 setOperationAction(ISD::FSIN, MVT::f32, Expand);
855 setOperationAction(ISD::FCOS, MVT::f32, Expand);
856 setOperationAction(ISD::FCOS, MVT::f64, Expand);
857 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
858 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
859 setOperationAction(ISD::FREM, MVT::f64, Expand);
860 setOperationAction(ISD::FREM, MVT::f32, Expand);
861 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862 !Subtarget->isThumb1Only()) {
863 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
866 setOperationAction(ISD::FPOW, MVT::f64, Expand);
867 setOperationAction(ISD::FPOW, MVT::f32, Expand);
869 if (!Subtarget->hasVFP4()) {
870 setOperationAction(ISD::FMA, MVT::f64, Expand);
871 setOperationAction(ISD::FMA, MVT::f32, Expand);
874 // Various VFP goodness
875 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877 if (Subtarget->hasVFP2()) {
878 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
884 // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
885 if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
886 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
887 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
890 // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
891 if (!Subtarget->hasFP16()) {
892 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
893 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
897 // Combine sin / cos into one node or libcall if possible.
898 if (Subtarget->hasSinCos()) {
899 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
900 setLibcallName(RTLIB::SINCOS_F64, "sincos");
901 if (Subtarget->getTargetTriple().isiOS()) {
902 // For iOS, we don't want to the normal expansion of a libcall to
903 // sincos. We want to issue a libcall to __sincos_stret.
904 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
905 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
909 // FP-ARMv8 implements a lot of rounding-like FP operations.
910 if (Subtarget->hasFPARMv8()) {
911 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
912 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
913 setOperationAction(ISD::FROUND, MVT::f32, Legal);
914 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
915 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
916 setOperationAction(ISD::FRINT, MVT::f32, Legal);
917 if (!Subtarget->isFPOnlySP()) {
918 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
919 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
920 setOperationAction(ISD::FROUND, MVT::f64, Legal);
921 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
922 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
923 setOperationAction(ISD::FRINT, MVT::f64, Legal);
926 // We have target-specific dag combine patterns for the following nodes:
927 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
928 setTargetDAGCombine(ISD::ADD);
929 setTargetDAGCombine(ISD::SUB);
930 setTargetDAGCombine(ISD::MUL);
931 setTargetDAGCombine(ISD::AND);
932 setTargetDAGCombine(ISD::OR);
933 setTargetDAGCombine(ISD::XOR);
935 if (Subtarget->hasV6Ops())
936 setTargetDAGCombine(ISD::SRL);
938 setStackPointerRegisterToSaveRestore(ARM::SP);
940 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
941 !Subtarget->hasVFP2())
942 setSchedulingPreference(Sched::RegPressure);
944 setSchedulingPreference(Sched::Hybrid);
946 //// temporary - rewrite interface to use type
947 MaxStoresPerMemset = 8;
948 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
949 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
950 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
951 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
952 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
954 // On ARM arguments smaller than 4 bytes are extended, so all arguments
955 // are at least 4 bytes aligned.
956 setMinStackArgumentAlignment(4);
958 // Prefer likely predicted branches to selects on out-of-order cores.
959 PredictableSelectIsExpensive = Subtarget->isLikeA9();
961 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
964 // FIXME: It might make sense to define the representative register class as the
965 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
966 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
967 // SPR's representative would be DPR_VFP2. This should work well if register
968 // pressure tracking were modified such that a register use would increment the
969 // pressure of the register class's representative and all of it's super
970 // classes' representatives transitively. We have not implemented this because
971 // of the difficulty prior to coalescing of modeling operand register classes
972 // due to the common occurrence of cross class copies and subregister insertions
974 std::pair<const TargetRegisterClass*, uint8_t>
975 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
976 const TargetRegisterClass *RRC = nullptr;
978 switch (VT.SimpleTy) {
980 return TargetLowering::findRepresentativeClass(VT);
981 // Use DPR as representative register class for all floating point
982 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
983 // the cost is 1 for both f32 and f64.
984 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
985 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
986 RRC = &ARM::DPRRegClass;
987 // When NEON is used for SP, only half of the register file is available
988 // because operations that define both SP and DP results will be constrained
989 // to the VFP2 class (D0-D15). We currently model this constraint prior to
990 // coalescing by double-counting the SP regs. See the FIXME above.
991 if (Subtarget->useNEONForSinglePrecisionFP())
994 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
995 case MVT::v4f32: case MVT::v2f64:
996 RRC = &ARM::DPRRegClass;
1000 RRC = &ARM::DPRRegClass;
1004 RRC = &ARM::DPRRegClass;
1008 return std::make_pair(RRC, Cost);
1011 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1013 default: return nullptr;
1014 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1015 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1016 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1017 case ARMISD::CALL: return "ARMISD::CALL";
1018 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1019 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1020 case ARMISD::tCALL: return "ARMISD::tCALL";
1021 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1022 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1023 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1024 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1025 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1026 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1027 case ARMISD::CMP: return "ARMISD::CMP";
1028 case ARMISD::CMN: return "ARMISD::CMN";
1029 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1030 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1031 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1032 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1033 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1035 case ARMISD::CMOV: return "ARMISD::CMOV";
1037 case ARMISD::RBIT: return "ARMISD::RBIT";
1039 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1040 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1041 case ARMISD::SITOF: return "ARMISD::SITOF";
1042 case ARMISD::UITOF: return "ARMISD::UITOF";
1044 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1045 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1046 case ARMISD::RRX: return "ARMISD::RRX";
1048 case ARMISD::ADDC: return "ARMISD::ADDC";
1049 case ARMISD::ADDE: return "ARMISD::ADDE";
1050 case ARMISD::SUBC: return "ARMISD::SUBC";
1051 case ARMISD::SUBE: return "ARMISD::SUBE";
1053 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1054 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1056 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1057 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1059 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1061 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1063 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1065 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1067 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1069 case ARMISD::WIN__CHKSTK: return "ARMISD:::WIN__CHKSTK";
1071 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1072 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1073 case ARMISD::VCGE: return "ARMISD::VCGE";
1074 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1075 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1076 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1077 case ARMISD::VCGT: return "ARMISD::VCGT";
1078 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1079 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1080 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1081 case ARMISD::VTST: return "ARMISD::VTST";
1083 case ARMISD::VSHL: return "ARMISD::VSHL";
1084 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1085 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1086 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1087 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1088 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1089 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1090 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1091 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1092 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1093 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1094 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1095 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1096 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1097 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1098 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1099 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1100 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1101 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1102 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1103 case ARMISD::VDUP: return "ARMISD::VDUP";
1104 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1105 case ARMISD::VEXT: return "ARMISD::VEXT";
1106 case ARMISD::VREV64: return "ARMISD::VREV64";
1107 case ARMISD::VREV32: return "ARMISD::VREV32";
1108 case ARMISD::VREV16: return "ARMISD::VREV16";
1109 case ARMISD::VZIP: return "ARMISD::VZIP";
1110 case ARMISD::VUZP: return "ARMISD::VUZP";
1111 case ARMISD::VTRN: return "ARMISD::VTRN";
1112 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1113 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1114 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1115 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1116 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1117 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1118 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1119 case ARMISD::FMAX: return "ARMISD::FMAX";
1120 case ARMISD::FMIN: return "ARMISD::FMIN";
1121 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1122 case ARMISD::VMINNM: return "ARMISD::VMIN";
1123 case ARMISD::BFI: return "ARMISD::BFI";
1124 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1125 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1126 case ARMISD::VBSL: return "ARMISD::VBSL";
1127 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1128 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1129 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1130 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1131 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1132 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1133 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1134 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1135 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1136 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1137 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1138 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1139 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1140 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1141 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1142 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1143 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1144 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1145 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1146 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1150 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1151 if (!VT.isVector()) return getPointerTy();
1152 return VT.changeVectorElementTypeToInteger();
1155 /// getRegClassFor - Return the register class that should be used for the
1156 /// specified value type.
1157 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1158 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1159 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1160 // load / store 4 to 8 consecutive D registers.
1161 if (Subtarget->hasNEON()) {
1162 if (VT == MVT::v4i64)
1163 return &ARM::QQPRRegClass;
1164 if (VT == MVT::v8i64)
1165 return &ARM::QQQQPRRegClass;
1167 return TargetLowering::getRegClassFor(VT);
1170 // Create a fast isel object.
1172 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1173 const TargetLibraryInfo *libInfo) const {
1174 return ARM::createFastISel(funcInfo, libInfo);
1177 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1178 /// be used for loads / stores from the global.
1179 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1180 return (Subtarget->isThumb1Only() ? 127 : 4095);
1183 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1184 unsigned NumVals = N->getNumValues();
1186 return Sched::RegPressure;
1188 for (unsigned i = 0; i != NumVals; ++i) {
1189 EVT VT = N->getValueType(i);
1190 if (VT == MVT::Glue || VT == MVT::Other)
1192 if (VT.isFloatingPoint() || VT.isVector())
1196 if (!N->isMachineOpcode())
1197 return Sched::RegPressure;
1199 // Load are scheduled for latency even if there instruction itinerary
1200 // is not available.
1201 const TargetInstrInfo *TII =
1202 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1203 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1205 if (MCID.getNumDefs() == 0)
1206 return Sched::RegPressure;
1207 if (!Itins->isEmpty() &&
1208 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1211 return Sched::RegPressure;
1214 //===----------------------------------------------------------------------===//
1216 //===----------------------------------------------------------------------===//
1218 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1219 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1221 default: llvm_unreachable("Unknown condition code!");
1222 case ISD::SETNE: return ARMCC::NE;
1223 case ISD::SETEQ: return ARMCC::EQ;
1224 case ISD::SETGT: return ARMCC::GT;
1225 case ISD::SETGE: return ARMCC::GE;
1226 case ISD::SETLT: return ARMCC::LT;
1227 case ISD::SETLE: return ARMCC::LE;
1228 case ISD::SETUGT: return ARMCC::HI;
1229 case ISD::SETUGE: return ARMCC::HS;
1230 case ISD::SETULT: return ARMCC::LO;
1231 case ISD::SETULE: return ARMCC::LS;
1235 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1236 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1237 ARMCC::CondCodes &CondCode2) {
1238 CondCode2 = ARMCC::AL;
1240 default: llvm_unreachable("Unknown FP condition!");
1242 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1244 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1246 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1247 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1248 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1249 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1250 case ISD::SETO: CondCode = ARMCC::VC; break;
1251 case ISD::SETUO: CondCode = ARMCC::VS; break;
1252 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1253 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1254 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1256 case ISD::SETULT: CondCode = ARMCC::LT; break;
1258 case ISD::SETULE: CondCode = ARMCC::LE; break;
1260 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1264 //===----------------------------------------------------------------------===//
1265 // Calling Convention Implementation
1266 //===----------------------------------------------------------------------===//
1268 #include "ARMGenCallingConv.inc"
1270 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1271 /// account presence of floating point hardware and calling convention
1272 /// limitations, such as support for variadic functions.
1274 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1275 bool isVarArg) const {
1278 llvm_unreachable("Unsupported calling convention");
1279 case CallingConv::ARM_AAPCS:
1280 case CallingConv::ARM_APCS:
1281 case CallingConv::GHC:
1283 case CallingConv::ARM_AAPCS_VFP:
1284 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1285 case CallingConv::C:
1286 if (!Subtarget->isAAPCS_ABI())
1287 return CallingConv::ARM_APCS;
1288 else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1289 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1291 return CallingConv::ARM_AAPCS_VFP;
1293 return CallingConv::ARM_AAPCS;
1294 case CallingConv::Fast:
1295 if (!Subtarget->isAAPCS_ABI()) {
1296 if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1297 return CallingConv::Fast;
1298 return CallingConv::ARM_APCS;
1299 } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1300 return CallingConv::ARM_AAPCS_VFP;
1302 return CallingConv::ARM_AAPCS;
1306 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1307 /// CallingConvention.
1308 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1310 bool isVarArg) const {
1311 switch (getEffectiveCallingConv(CC, isVarArg)) {
1313 llvm_unreachable("Unsupported calling convention");
1314 case CallingConv::ARM_APCS:
1315 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1316 case CallingConv::ARM_AAPCS:
1317 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1318 case CallingConv::ARM_AAPCS_VFP:
1319 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1320 case CallingConv::Fast:
1321 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1322 case CallingConv::GHC:
1323 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1327 /// LowerCallResult - Lower the result values of a call into the
1328 /// appropriate copies out of appropriate physical registers.
1330 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1331 CallingConv::ID CallConv, bool isVarArg,
1332 const SmallVectorImpl<ISD::InputArg> &Ins,
1333 SDLoc dl, SelectionDAG &DAG,
1334 SmallVectorImpl<SDValue> &InVals,
1335 bool isThisReturn, SDValue ThisVal) const {
1337 // Assign locations to each value returned by this call.
1338 SmallVector<CCValAssign, 16> RVLocs;
1339 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1340 *DAG.getContext(), Call);
1341 CCInfo.AnalyzeCallResult(Ins,
1342 CCAssignFnForNode(CallConv, /* Return*/ true,
1345 // Copy all of the result registers out of their specified physreg.
1346 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1347 CCValAssign VA = RVLocs[i];
1349 // Pass 'this' value directly from the argument to return value, to avoid
1350 // reg unit interference
1351 if (i == 0 && isThisReturn) {
1352 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1353 "unexpected return calling convention register assignment");
1354 InVals.push_back(ThisVal);
1359 if (VA.needsCustom()) {
1360 // Handle f64 or half of a v2f64.
1361 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1363 Chain = Lo.getValue(1);
1364 InFlag = Lo.getValue(2);
1365 VA = RVLocs[++i]; // skip ahead to next loc
1366 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1368 Chain = Hi.getValue(1);
1369 InFlag = Hi.getValue(2);
1370 if (!Subtarget->isLittle())
1372 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1374 if (VA.getLocVT() == MVT::v2f64) {
1375 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1376 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1377 DAG.getConstant(0, MVT::i32));
1379 VA = RVLocs[++i]; // skip ahead to next loc
1380 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1381 Chain = Lo.getValue(1);
1382 InFlag = Lo.getValue(2);
1383 VA = RVLocs[++i]; // skip ahead to next loc
1384 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1385 Chain = Hi.getValue(1);
1386 InFlag = Hi.getValue(2);
1387 if (!Subtarget->isLittle())
1389 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1390 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1391 DAG.getConstant(1, MVT::i32));
1394 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1396 Chain = Val.getValue(1);
1397 InFlag = Val.getValue(2);
1400 switch (VA.getLocInfo()) {
1401 default: llvm_unreachable("Unknown loc info!");
1402 case CCValAssign::Full: break;
1403 case CCValAssign::BCvt:
1404 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1408 InVals.push_back(Val);
1414 /// LowerMemOpCallTo - Store the argument to the stack.
1416 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1417 SDValue StackPtr, SDValue Arg,
1418 SDLoc dl, SelectionDAG &DAG,
1419 const CCValAssign &VA,
1420 ISD::ArgFlagsTy Flags) const {
1421 unsigned LocMemOffset = VA.getLocMemOffset();
1422 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1423 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1424 return DAG.getStore(Chain, dl, Arg, PtrOff,
1425 MachinePointerInfo::getStack(LocMemOffset),
1429 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1430 SDValue Chain, SDValue &Arg,
1431 RegsToPassVector &RegsToPass,
1432 CCValAssign &VA, CCValAssign &NextVA,
1434 SmallVectorImpl<SDValue> &MemOpChains,
1435 ISD::ArgFlagsTy Flags) const {
1437 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1438 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1439 unsigned id = Subtarget->isLittle() ? 0 : 1;
1440 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1442 if (NextVA.isRegLoc())
1443 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1445 assert(NextVA.isMemLoc());
1446 if (!StackPtr.getNode())
1447 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1449 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1455 /// LowerCall - Lowering a call into a callseq_start <-
1456 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1459 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1460 SmallVectorImpl<SDValue> &InVals) const {
1461 SelectionDAG &DAG = CLI.DAG;
1463 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1464 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1465 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1466 SDValue Chain = CLI.Chain;
1467 SDValue Callee = CLI.Callee;
1468 bool &isTailCall = CLI.IsTailCall;
1469 CallingConv::ID CallConv = CLI.CallConv;
1470 bool doesNotRet = CLI.DoesNotReturn;
1471 bool isVarArg = CLI.IsVarArg;
1473 MachineFunction &MF = DAG.getMachineFunction();
1474 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1475 bool isThisReturn = false;
1476 bool isSibCall = false;
1478 // Disable tail calls if they're not supported.
1479 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1483 // Check if it's really possible to do a tail call.
1484 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1485 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1486 Outs, OutVals, Ins, DAG);
1487 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1488 report_fatal_error("failed to perform tail call elimination on a call "
1489 "site marked musttail");
1490 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1491 // detected sibcalls.
1498 // Analyze operands of the call, assigning locations to each operand.
1499 SmallVector<CCValAssign, 16> ArgLocs;
1500 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1501 *DAG.getContext(), Call);
1502 CCInfo.AnalyzeCallOperands(Outs,
1503 CCAssignFnForNode(CallConv, /* Return*/ false,
1506 // Get a count of how many bytes are to be pushed on the stack.
1507 unsigned NumBytes = CCInfo.getNextStackOffset();
1509 // For tail calls, memory operands are available in our caller's stack.
1513 // Adjust the stack pointer for the new arguments...
1514 // These operations are automatically eliminated by the prolog/epilog pass
1516 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1519 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1521 RegsToPassVector RegsToPass;
1522 SmallVector<SDValue, 8> MemOpChains;
1524 // Walk the register/memloc assignments, inserting copies/loads. In the case
1525 // of tail call optimization, arguments are handled later.
1526 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1528 ++i, ++realArgIdx) {
1529 CCValAssign &VA = ArgLocs[i];
1530 SDValue Arg = OutVals[realArgIdx];
1531 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1532 bool isByVal = Flags.isByVal();
1534 // Promote the value if needed.
1535 switch (VA.getLocInfo()) {
1536 default: llvm_unreachable("Unknown loc info!");
1537 case CCValAssign::Full: break;
1538 case CCValAssign::SExt:
1539 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1541 case CCValAssign::ZExt:
1542 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1544 case CCValAssign::AExt:
1545 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1547 case CCValAssign::BCvt:
1548 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1552 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1553 if (VA.needsCustom()) {
1554 if (VA.getLocVT() == MVT::v2f64) {
1555 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1556 DAG.getConstant(0, MVT::i32));
1557 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1558 DAG.getConstant(1, MVT::i32));
1560 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1561 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1563 VA = ArgLocs[++i]; // skip ahead to next loc
1564 if (VA.isRegLoc()) {
1565 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1566 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1568 assert(VA.isMemLoc());
1570 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1571 dl, DAG, VA, Flags));
1574 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1575 StackPtr, MemOpChains, Flags);
1577 } else if (VA.isRegLoc()) {
1578 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1579 assert(VA.getLocVT() == MVT::i32 &&
1580 "unexpected calling convention register assignment");
1581 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1582 "unexpected use of 'returned'");
1583 isThisReturn = true;
1585 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1586 } else if (isByVal) {
1587 assert(VA.isMemLoc());
1588 unsigned offset = 0;
1590 // True if this byval aggregate will be split between registers
1592 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1593 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1595 if (CurByValIdx < ByValArgsCount) {
1597 unsigned RegBegin, RegEnd;
1598 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1600 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1602 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1603 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1604 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1605 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1606 MachinePointerInfo(),
1607 false, false, false,
1608 DAG.InferPtrAlignment(AddArg));
1609 MemOpChains.push_back(Load.getValue(1));
1610 RegsToPass.push_back(std::make_pair(j, Load));
1613 // If parameter size outsides register area, "offset" value
1614 // helps us to calculate stack slot for remained part properly.
1615 offset = RegEnd - RegBegin;
1617 CCInfo.nextInRegsParam();
1620 if (Flags.getByValSize() > 4*offset) {
1621 unsigned LocMemOffset = VA.getLocMemOffset();
1622 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1623 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1625 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1626 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1627 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1629 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1631 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1632 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1633 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1636 } else if (!isSibCall) {
1637 assert(VA.isMemLoc());
1639 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1640 dl, DAG, VA, Flags));
1644 if (!MemOpChains.empty())
1645 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1647 // Build a sequence of copy-to-reg nodes chained together with token chain
1648 // and flag operands which copy the outgoing args into the appropriate regs.
1650 // Tail call byval lowering might overwrite argument registers so in case of
1651 // tail call optimization the copies to registers are lowered later.
1653 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1654 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1655 RegsToPass[i].second, InFlag);
1656 InFlag = Chain.getValue(1);
1659 // For tail calls lower the arguments to the 'real' stack slot.
1661 // Force all the incoming stack arguments to be loaded from the stack
1662 // before any new outgoing arguments are stored to the stack, because the
1663 // outgoing stack slots may alias the incoming argument stack slots, and
1664 // the alias isn't otherwise explicit. This is slightly more conservative
1665 // than necessary, because it means that each store effectively depends
1666 // on every argument instead of just those arguments it would clobber.
1668 // Do not flag preceding copytoreg stuff together with the following stuff.
1670 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1671 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1672 RegsToPass[i].second, InFlag);
1673 InFlag = Chain.getValue(1);
1678 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1679 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1680 // node so that legalize doesn't hack it.
1681 bool isDirect = false;
1682 bool isARMFunc = false;
1683 bool isLocalARMFunc = false;
1684 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1686 if (EnableARMLongCalls) {
1687 assert((Subtarget->isTargetWindows() ||
1688 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1689 "long-calls with non-static relocation model!");
1690 // Handle a global address or an external symbol. If it's not one of
1691 // those, the target's already in a register, so we don't need to do
1693 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1694 const GlobalValue *GV = G->getGlobal();
1695 // Create a constant pool entry for the callee address
1696 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1697 ARMConstantPoolValue *CPV =
1698 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1700 // Get the address of the callee into a register
1701 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1702 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1703 Callee = DAG.getLoad(getPointerTy(), dl,
1704 DAG.getEntryNode(), CPAddr,
1705 MachinePointerInfo::getConstantPool(),
1706 false, false, false, 0);
1707 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1708 const char *Sym = S->getSymbol();
1710 // Create a constant pool entry for the callee address
1711 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1712 ARMConstantPoolValue *CPV =
1713 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1714 ARMPCLabelIndex, 0);
1715 // Get the address of the callee into a register
1716 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1717 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1718 Callee = DAG.getLoad(getPointerTy(), dl,
1719 DAG.getEntryNode(), CPAddr,
1720 MachinePointerInfo::getConstantPool(),
1721 false, false, false, 0);
1723 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1724 const GlobalValue *GV = G->getGlobal();
1726 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1727 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1728 getTargetMachine().getRelocationModel() != Reloc::Static;
1729 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1730 // ARM call to a local ARM function is predicable.
1731 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1732 // tBX takes a register source operand.
1733 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1734 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1735 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1736 DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1737 0, ARMII::MO_NONLAZY));
1738 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1739 MachinePointerInfo::getGOT(), false, false, true, 0);
1740 } else if (Subtarget->isTargetCOFF()) {
1741 assert(Subtarget->isTargetWindows() &&
1742 "Windows is the only supported COFF target");
1743 unsigned TargetFlags = GV->hasDLLImportStorageClass()
1744 ? ARMII::MO_DLLIMPORT
1745 : ARMII::MO_NO_FLAG;
1746 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1748 if (GV->hasDLLImportStorageClass())
1749 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1750 DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1751 Callee), MachinePointerInfo::getGOT(),
1752 false, false, false, 0);
1754 // On ELF targets for PIC code, direct calls should go through the PLT
1755 unsigned OpFlags = 0;
1756 if (Subtarget->isTargetELF() &&
1757 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1758 OpFlags = ARMII::MO_PLT;
1759 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1761 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1763 bool isStub = Subtarget->isTargetMachO() &&
1764 getTargetMachine().getRelocationModel() != Reloc::Static;
1765 isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1766 // tBX takes a register source operand.
1767 const char *Sym = S->getSymbol();
1768 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1769 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1770 ARMConstantPoolValue *CPV =
1771 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1772 ARMPCLabelIndex, 4);
1773 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1774 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1775 Callee = DAG.getLoad(getPointerTy(), dl,
1776 DAG.getEntryNode(), CPAddr,
1777 MachinePointerInfo::getConstantPool(),
1778 false, false, false, 0);
1779 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1780 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1781 getPointerTy(), Callee, PICLabel);
1783 unsigned OpFlags = 0;
1784 // On ELF targets for PIC code, direct calls should go through the PLT
1785 if (Subtarget->isTargetELF() &&
1786 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1787 OpFlags = ARMII::MO_PLT;
1788 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1792 // FIXME: handle tail calls differently.
1794 bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1795 AttributeSet::FunctionIndex, Attribute::MinSize);
1796 if (Subtarget->isThumb()) {
1797 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1798 CallOpc = ARMISD::CALL_NOLINK;
1800 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1802 if (!isDirect && !Subtarget->hasV5TOps())
1803 CallOpc = ARMISD::CALL_NOLINK;
1804 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1805 // Emit regular call when code size is the priority
1807 // "mov lr, pc; b _foo" to avoid confusing the RSP
1808 CallOpc = ARMISD::CALL_NOLINK;
1810 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1813 std::vector<SDValue> Ops;
1814 Ops.push_back(Chain);
1815 Ops.push_back(Callee);
1817 // Add argument registers to the end of the list so that they are known live
1819 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1820 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1821 RegsToPass[i].second.getValueType()));
1823 // Add a register mask operand representing the call-preserved registers.
1825 const uint32_t *Mask;
1826 const TargetRegisterInfo *TRI =
1827 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1828 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1830 // For 'this' returns, use the R0-preserving mask if applicable
1831 Mask = ARI->getThisReturnPreservedMask(CallConv);
1833 // Set isThisReturn to false if the calling convention is not one that
1834 // allows 'returned' to be modeled in this way, so LowerCallResult does
1835 // not try to pass 'this' straight through
1836 isThisReturn = false;
1837 Mask = ARI->getCallPreservedMask(CallConv);
1840 Mask = ARI->getCallPreservedMask(CallConv);
1842 assert(Mask && "Missing call preserved mask for calling convention");
1843 Ops.push_back(DAG.getRegisterMask(Mask));
1846 if (InFlag.getNode())
1847 Ops.push_back(InFlag);
1849 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1851 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1853 // Returns a chain and a flag for retval copy to use.
1854 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1855 InFlag = Chain.getValue(1);
1857 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1858 DAG.getIntPtrConstant(0, true), InFlag, dl);
1860 InFlag = Chain.getValue(1);
1862 // Handle result values, copying them out of physregs into vregs that we
1864 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1865 InVals, isThisReturn,
1866 isThisReturn ? OutVals[0] : SDValue());
1869 /// HandleByVal - Every parameter *after* a byval parameter is passed
1870 /// on the stack. Remember the next parameter register to allocate,
1871 /// and then confiscate the rest of the parameter registers to insure
1874 ARMTargetLowering::HandleByVal(
1875 CCState *State, unsigned &size, unsigned Align) const {
1876 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1877 assert((State->getCallOrPrologue() == Prologue ||
1878 State->getCallOrPrologue() == Call) &&
1879 "unhandled ParmContext");
1881 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1882 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1883 unsigned AlignInRegs = Align / 4;
1884 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1885 for (unsigned i = 0; i < Waste; ++i)
1886 reg = State->AllocateReg(GPRArgRegs, 4);
1889 unsigned excess = 4 * (ARM::R4 - reg);
1891 // Special case when NSAA != SP and parameter size greater than size of
1892 // all remained GPR regs. In that case we can't split parameter, we must
1893 // send it to stack. We also must set NCRN to R4, so waste all
1894 // remained registers.
1895 const unsigned NSAAOffset = State->getNextStackOffset();
1896 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1897 while (State->AllocateReg(GPRArgRegs, 4))
1902 // First register for byval parameter is the first register that wasn't
1903 // allocated before this method call, so it would be "reg".
1904 // If parameter is small enough to be saved in range [reg, r4), then
1905 // the end (first after last) register would be reg + param-size-in-regs,
1906 // else parameter would be splitted between registers and stack,
1907 // end register would be r4 in this case.
1908 unsigned ByValRegBegin = reg;
1909 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1910 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1911 // Note, first register is allocated in the beginning of function already,
1912 // allocate remained amount of registers we need.
1913 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1914 State->AllocateReg(GPRArgRegs, 4);
1915 // A byval parameter that is split between registers and memory needs its
1916 // size truncated here.
1917 // In the case where the entire structure fits in registers, we set the
1918 // size in memory to zero.
1927 /// MatchingStackOffset - Return true if the given stack call argument is
1928 /// already available in the same position (relatively) of the caller's
1929 /// incoming argument stack.
1931 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1932 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1933 const TargetInstrInfo *TII) {
1934 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1936 if (Arg.getOpcode() == ISD::CopyFromReg) {
1937 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1938 if (!TargetRegisterInfo::isVirtualRegister(VR))
1940 MachineInstr *Def = MRI->getVRegDef(VR);
1943 if (!Flags.isByVal()) {
1944 if (!TII->isLoadFromStackSlot(Def, FI))
1949 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1950 if (Flags.isByVal())
1951 // ByVal argument is passed in as a pointer but it's now being
1952 // dereferenced. e.g.
1953 // define @foo(%struct.X* %A) {
1954 // tail call @bar(%struct.X* byval %A)
1957 SDValue Ptr = Ld->getBasePtr();
1958 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1961 FI = FINode->getIndex();
1965 assert(FI != INT_MAX);
1966 if (!MFI->isFixedObjectIndex(FI))
1968 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1971 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1972 /// for tail call optimization. Targets which want to do tail call
1973 /// optimization should implement this function.
1975 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1976 CallingConv::ID CalleeCC,
1978 bool isCalleeStructRet,
1979 bool isCallerStructRet,
1980 const SmallVectorImpl<ISD::OutputArg> &Outs,
1981 const SmallVectorImpl<SDValue> &OutVals,
1982 const SmallVectorImpl<ISD::InputArg> &Ins,
1983 SelectionDAG& DAG) const {
1984 const Function *CallerF = DAG.getMachineFunction().getFunction();
1985 CallingConv::ID CallerCC = CallerF->getCallingConv();
1986 bool CCMatch = CallerCC == CalleeCC;
1988 // Look for obvious safe cases to perform tail call optimization that do not
1989 // require ABI changes. This is what gcc calls sibcall.
1991 // Do not sibcall optimize vararg calls unless the call site is not passing
1993 if (isVarArg && !Outs.empty())
1996 // Exception-handling functions need a special set of instructions to indicate
1997 // a return to the hardware. Tail-calling another function would probably
1999 if (CallerF->hasFnAttribute("interrupt"))
2002 // Also avoid sibcall optimization if either caller or callee uses struct
2003 // return semantics.
2004 if (isCalleeStructRet || isCallerStructRet)
2007 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2008 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2009 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2010 // support in the assembler and linker to be used. This would need to be
2011 // fixed to fully support tail calls in Thumb1.
2013 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2014 // LR. This means if we need to reload LR, it takes an extra instructions,
2015 // which outweighs the value of the tail call; but here we don't know yet
2016 // whether LR is going to be used. Probably the right approach is to
2017 // generate the tail call here and turn it back into CALL/RET in
2018 // emitEpilogue if LR is used.
2020 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2021 // but we need to make sure there are enough registers; the only valid
2022 // registers are the 4 used for parameters. We don't currently do this
2024 if (Subtarget->isThumb1Only())
2027 // Externally-defined functions with weak linkage should not be
2028 // tail-called on ARM when the OS does not support dynamic
2029 // pre-emption of symbols, as the AAELF spec requires normal calls
2030 // to undefined weak functions to be replaced with a NOP or jump to the
2031 // next instruction. The behaviour of branch instructions in this
2032 // situation (as used for tail calls) is implementation-defined, so we
2033 // cannot rely on the linker replacing the tail call with a return.
2034 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2035 const GlobalValue *GV = G->getGlobal();
2036 if (GV->hasExternalWeakLinkage())
2040 // If the calling conventions do not match, then we'd better make sure the
2041 // results are returned in the same way as what the caller expects.
2043 SmallVector<CCValAssign, 16> RVLocs1;
2044 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2045 *DAG.getContext(), Call);
2046 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2048 SmallVector<CCValAssign, 16> RVLocs2;
2049 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2050 *DAG.getContext(), Call);
2051 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2053 if (RVLocs1.size() != RVLocs2.size())
2055 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2056 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2058 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2060 if (RVLocs1[i].isRegLoc()) {
2061 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2064 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2070 // If Caller's vararg or byval argument has been split between registers and
2071 // stack, do not perform tail call, since part of the argument is in caller's
2073 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2074 getInfo<ARMFunctionInfo>();
2075 if (AFI_Caller->getArgRegsSaveSize())
2078 // If the callee takes no arguments then go on to check the results of the
2080 if (!Outs.empty()) {
2081 // Check if stack adjustment is needed. For now, do not do this if any
2082 // argument is passed on the stack.
2083 SmallVector<CCValAssign, 16> ArgLocs;
2084 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2085 *DAG.getContext(), Call);
2086 CCInfo.AnalyzeCallOperands(Outs,
2087 CCAssignFnForNode(CalleeCC, false, isVarArg));
2088 if (CCInfo.getNextStackOffset()) {
2089 MachineFunction &MF = DAG.getMachineFunction();
2091 // Check if the arguments are already laid out in the right way as
2092 // the caller's fixed stack objects.
2093 MachineFrameInfo *MFI = MF.getFrameInfo();
2094 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2095 const TargetInstrInfo *TII =
2096 getTargetMachine().getSubtargetImpl()->getInstrInfo();
2097 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2099 ++i, ++realArgIdx) {
2100 CCValAssign &VA = ArgLocs[i];
2101 EVT RegVT = VA.getLocVT();
2102 SDValue Arg = OutVals[realArgIdx];
2103 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2104 if (VA.getLocInfo() == CCValAssign::Indirect)
2106 if (VA.needsCustom()) {
2107 // f64 and vector types are split into multiple registers or
2108 // register/stack-slot combinations. The types will not match
2109 // the registers; give up on memory f64 refs until we figure
2110 // out what to do about this.
2113 if (!ArgLocs[++i].isRegLoc())
2115 if (RegVT == MVT::v2f64) {
2116 if (!ArgLocs[++i].isRegLoc())
2118 if (!ArgLocs[++i].isRegLoc())
2121 } else if (!VA.isRegLoc()) {
2122 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2134 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2135 MachineFunction &MF, bool isVarArg,
2136 const SmallVectorImpl<ISD::OutputArg> &Outs,
2137 LLVMContext &Context) const {
2138 SmallVector<CCValAssign, 16> RVLocs;
2139 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2140 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2144 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2145 SDLoc DL, SelectionDAG &DAG) {
2146 const MachineFunction &MF = DAG.getMachineFunction();
2147 const Function *F = MF.getFunction();
2149 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2151 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2152 // version of the "preferred return address". These offsets affect the return
2153 // instruction if this is a return from PL1 without hypervisor extensions.
2154 // IRQ/FIQ: +4 "subs pc, lr, #4"
2155 // SWI: 0 "subs pc, lr, #0"
2156 // ABORT: +4 "subs pc, lr, #4"
2157 // UNDEF: +4/+2 "subs pc, lr, #0"
2158 // UNDEF varies depending on where the exception came from ARM or Thumb
2159 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2162 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2165 else if (IntKind == "SWI" || IntKind == "UNDEF")
2168 report_fatal_error("Unsupported interrupt attribute. If present, value "
2169 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2171 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2173 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2177 ARMTargetLowering::LowerReturn(SDValue Chain,
2178 CallingConv::ID CallConv, bool isVarArg,
2179 const SmallVectorImpl<ISD::OutputArg> &Outs,
2180 const SmallVectorImpl<SDValue> &OutVals,
2181 SDLoc dl, SelectionDAG &DAG) const {
2183 // CCValAssign - represent the assignment of the return value to a location.
2184 SmallVector<CCValAssign, 16> RVLocs;
2186 // CCState - Info about the registers and stack slots.
2187 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2188 *DAG.getContext(), Call);
2190 // Analyze outgoing return values.
2191 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2195 SmallVector<SDValue, 4> RetOps;
2196 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2197 bool isLittleEndian = Subtarget->isLittle();
2199 MachineFunction &MF = DAG.getMachineFunction();
2200 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2201 AFI->setReturnRegsCount(RVLocs.size());
2203 // Copy the result values into the output registers.
2204 for (unsigned i = 0, realRVLocIdx = 0;
2206 ++i, ++realRVLocIdx) {
2207 CCValAssign &VA = RVLocs[i];
2208 assert(VA.isRegLoc() && "Can only return in registers!");
2210 SDValue Arg = OutVals[realRVLocIdx];
2212 switch (VA.getLocInfo()) {
2213 default: llvm_unreachable("Unknown loc info!");
2214 case CCValAssign::Full: break;
2215 case CCValAssign::BCvt:
2216 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2220 if (VA.needsCustom()) {
2221 if (VA.getLocVT() == MVT::v2f64) {
2222 // Extract the first half and return it in two registers.
2223 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2224 DAG.getConstant(0, MVT::i32));
2225 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2226 DAG.getVTList(MVT::i32, MVT::i32), Half);
2228 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2229 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2231 Flag = Chain.getValue(1);
2232 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2233 VA = RVLocs[++i]; // skip ahead to next loc
2234 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2235 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2237 Flag = Chain.getValue(1);
2238 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2239 VA = RVLocs[++i]; // skip ahead to next loc
2241 // Extract the 2nd half and fall through to handle it as an f64 value.
2242 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2243 DAG.getConstant(1, MVT::i32));
2245 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2247 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2248 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2249 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2250 fmrrd.getValue(isLittleEndian ? 0 : 1),
2252 Flag = Chain.getValue(1);
2253 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2254 VA = RVLocs[++i]; // skip ahead to next loc
2255 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2256 fmrrd.getValue(isLittleEndian ? 1 : 0),
2259 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2261 // Guarantee that all emitted copies are
2262 // stuck together, avoiding something bad.
2263 Flag = Chain.getValue(1);
2264 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2267 // Update chain and glue.
2270 RetOps.push_back(Flag);
2272 // CPUs which aren't M-class use a special sequence to return from
2273 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2274 // though we use "subs pc, lr, #N").
2276 // M-class CPUs actually use a normal return sequence with a special
2277 // (hardware-provided) value in LR, so the normal code path works.
2278 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2279 !Subtarget->isMClass()) {
2280 if (Subtarget->isThumb1Only())
2281 report_fatal_error("interrupt attribute is not supported in Thumb1");
2282 return LowerInterruptReturn(RetOps, dl, DAG);
2285 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2288 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2289 if (N->getNumValues() != 1)
2291 if (!N->hasNUsesOfValue(1, 0))
2294 SDValue TCChain = Chain;
2295 SDNode *Copy = *N->use_begin();
2296 if (Copy->getOpcode() == ISD::CopyToReg) {
2297 // If the copy has a glue operand, we conservatively assume it isn't safe to
2298 // perform a tail call.
2299 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2301 TCChain = Copy->getOperand(0);
2302 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2303 SDNode *VMov = Copy;
2304 // f64 returned in a pair of GPRs.
2305 SmallPtrSet<SDNode*, 2> Copies;
2306 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2308 if (UI->getOpcode() != ISD::CopyToReg)
2312 if (Copies.size() > 2)
2315 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2317 SDValue UseChain = UI->getOperand(0);
2318 if (Copies.count(UseChain.getNode()))
2322 // We are at the top of this chain.
2323 // If the copy has a glue operand, we conservatively assume it
2324 // isn't safe to perform a tail call.
2325 if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2331 } else if (Copy->getOpcode() == ISD::BITCAST) {
2332 // f32 returned in a single GPR.
2333 if (!Copy->hasOneUse())
2335 Copy = *Copy->use_begin();
2336 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2338 // If the copy has a glue operand, we conservatively assume it isn't safe to
2339 // perform a tail call.
2340 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2342 TCChain = Copy->getOperand(0);
2347 bool HasRet = false;
2348 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2350 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2351 UI->getOpcode() != ARMISD::INTRET_FLAG)
2363 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2364 if (!Subtarget->supportsTailCall())
2367 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2370 return !Subtarget->isThumb1Only();
2373 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2374 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2375 // one of the above mentioned nodes. It has to be wrapped because otherwise
2376 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2377 // be used to form addressing mode. These wrapped nodes will be selected
2379 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2380 EVT PtrVT = Op.getValueType();
2381 // FIXME there is no actual debug info here
2383 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2385 if (CP->isMachineConstantPoolEntry())
2386 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2387 CP->getAlignment());
2389 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2390 CP->getAlignment());
2391 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2394 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2395 return MachineJumpTableInfo::EK_Inline;
2398 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2399 SelectionDAG &DAG) const {
2400 MachineFunction &MF = DAG.getMachineFunction();
2401 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2402 unsigned ARMPCLabelIndex = 0;
2404 EVT PtrVT = getPointerTy();
2405 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2406 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2408 if (RelocM == Reloc::Static) {
2409 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2411 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2412 ARMPCLabelIndex = AFI->createPICLabelUId();
2413 ARMConstantPoolValue *CPV =
2414 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2415 ARMCP::CPBlockAddress, PCAdj);
2416 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2418 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2419 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2420 MachinePointerInfo::getConstantPool(),
2421 false, false, false, 0);
2422 if (RelocM == Reloc::Static)
2424 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2425 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2428 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2430 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2431 SelectionDAG &DAG) const {
2433 EVT PtrVT = getPointerTy();
2434 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2435 MachineFunction &MF = DAG.getMachineFunction();
2436 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2437 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2438 ARMConstantPoolValue *CPV =
2439 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2440 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2441 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2442 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2443 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2444 MachinePointerInfo::getConstantPool(),
2445 false, false, false, 0);
2446 SDValue Chain = Argument.getValue(1);
2448 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2449 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2451 // call __tls_get_addr.
2454 Entry.Node = Argument;
2455 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2456 Args.push_back(Entry);
2458 // FIXME: is there useful debug info available here?
2459 TargetLowering::CallLoweringInfo CLI(DAG);
2460 CLI.setDebugLoc(dl).setChain(Chain)
2461 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2462 DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2465 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2466 return CallResult.first;
2469 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2470 // "local exec" model.
2472 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2474 TLSModel::Model model) const {
2475 const GlobalValue *GV = GA->getGlobal();
2478 SDValue Chain = DAG.getEntryNode();
2479 EVT PtrVT = getPointerTy();
2480 // Get the Thread Pointer
2481 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2483 if (model == TLSModel::InitialExec) {
2484 MachineFunction &MF = DAG.getMachineFunction();
2485 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2486 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2487 // Initial exec model.
2488 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2489 ARMConstantPoolValue *CPV =
2490 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2491 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2493 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2494 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2495 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2496 MachinePointerInfo::getConstantPool(),
2497 false, false, false, 0);
2498 Chain = Offset.getValue(1);
2500 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2501 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2503 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2504 MachinePointerInfo::getConstantPool(),
2505 false, false, false, 0);
2508 assert(model == TLSModel::LocalExec);
2509 ARMConstantPoolValue *CPV =
2510 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2511 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2512 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2513 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2514 MachinePointerInfo::getConstantPool(),
2515 false, false, false, 0);
2518 // The address of the thread local variable is the add of the thread
2519 // pointer with the offset of the variable.
2520 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2524 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2525 // TODO: implement the "local dynamic" model
2526 assert(Subtarget->isTargetELF() &&
2527 "TLS not implemented for non-ELF targets");
2528 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2530 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2533 case TLSModel::GeneralDynamic:
2534 case TLSModel::LocalDynamic:
2535 return LowerToTLSGeneralDynamicModel(GA, DAG);
2536 case TLSModel::InitialExec:
2537 case TLSModel::LocalExec:
2538 return LowerToTLSExecModels(GA, DAG, model);
2540 llvm_unreachable("bogus TLS model");
2543 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 EVT PtrVT = getPointerTy();
2547 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2548 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2549 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2550 ARMConstantPoolValue *CPV =
2551 ARMConstantPoolConstant::Create(GV,
2552 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2553 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2554 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2555 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2557 MachinePointerInfo::getConstantPool(),
2558 false, false, false, 0);
2559 SDValue Chain = Result.getValue(1);
2560 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2561 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2563 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2564 MachinePointerInfo::getGOT(),
2565 false, false, false, 0);
2569 // If we have T2 ops, we can materialize the address directly via movt/movw
2570 // pair. This is always cheaper.
2571 if (Subtarget->useMovt(DAG.getMachineFunction())) {
2573 // FIXME: Once remat is capable of dealing with instructions with register
2574 // operands, expand this into two nodes.
2575 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2576 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2578 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2579 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2580 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2581 MachinePointerInfo::getConstantPool(),
2582 false, false, false, 0);
2586 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2587 SelectionDAG &DAG) const {
2588 EVT PtrVT = getPointerTy();
2590 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2591 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2593 if (Subtarget->useMovt(DAG.getMachineFunction()))
2596 // FIXME: Once remat is capable of dealing with instructions with register
2597 // operands, expand this into multiple nodes
2599 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2601 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2602 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2604 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2605 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2606 MachinePointerInfo::getGOT(), false, false, false, 0);
2610 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2611 SelectionDAG &DAG) const {
2612 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2613 assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2614 "Windows on ARM expects to use movw/movt");
2616 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2617 const ARMII::TOF TargetFlags =
2618 (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2619 EVT PtrVT = getPointerTy();
2625 // FIXME: Once remat is capable of dealing with instructions with register
2626 // operands, expand this into two nodes.
2627 Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2628 DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2630 if (GV->hasDLLImportStorageClass())
2631 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2632 MachinePointerInfo::getGOT(), false, false, false, 0);
2636 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2637 SelectionDAG &DAG) const {
2638 assert(Subtarget->isTargetELF() &&
2639 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2640 MachineFunction &MF = DAG.getMachineFunction();
2641 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2642 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2643 EVT PtrVT = getPointerTy();
2645 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2646 ARMConstantPoolValue *CPV =
2647 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2648 ARMPCLabelIndex, PCAdj);
2649 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2650 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2651 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2652 MachinePointerInfo::getConstantPool(),
2653 false, false, false, 0);
2654 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2655 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2659 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2661 SDValue Val = DAG.getConstant(0, MVT::i32);
2662 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2663 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2664 Op.getOperand(1), Val);
2668 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2670 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2671 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2675 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2676 const ARMSubtarget *Subtarget) const {
2677 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2680 default: return SDValue(); // Don't custom lower most intrinsics.
2681 case Intrinsic::arm_rbit: {
2682 assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2683 "RBIT intrinsic must have i32 type!");
2684 return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2686 case Intrinsic::arm_thread_pointer: {
2687 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2688 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2690 case Intrinsic::eh_sjlj_lsda: {
2691 MachineFunction &MF = DAG.getMachineFunction();
2692 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2693 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2694 EVT PtrVT = getPointerTy();
2695 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2697 unsigned PCAdj = (RelocM != Reloc::PIC_)
2698 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2699 ARMConstantPoolValue *CPV =
2700 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2701 ARMCP::CPLSDA, PCAdj);
2702 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2703 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2705 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2706 MachinePointerInfo::getConstantPool(),
2707 false, false, false, 0);
2709 if (RelocM == Reloc::PIC_) {
2710 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2711 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2715 case Intrinsic::arm_neon_vmulls:
2716 case Intrinsic::arm_neon_vmullu: {
2717 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2718 ? ARMISD::VMULLs : ARMISD::VMULLu;
2719 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2720 Op.getOperand(1), Op.getOperand(2));
2725 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2726 const ARMSubtarget *Subtarget) {
2727 // FIXME: handle "fence singlethread" more efficiently.
2729 if (!Subtarget->hasDataBarrier()) {
2730 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2731 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2733 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2734 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2735 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2736 DAG.getConstant(0, MVT::i32));
2739 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2740 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2741 ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2742 if (Subtarget->isMClass()) {
2743 // Only a full system barrier exists in the M-class architectures.
2744 Domain = ARM_MB::SY;
2745 } else if (Subtarget->isSwift() && Ord == Release) {
2746 // Swift happens to implement ISHST barriers in a way that's compatible with
2747 // Release semantics but weaker than ISH so we'd be fools not to use
2748 // it. Beware: other processors probably don't!
2749 Domain = ARM_MB::ISHST;
2752 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2753 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2754 DAG.getConstant(Domain, MVT::i32));
2757 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2758 const ARMSubtarget *Subtarget) {
2759 // ARM pre v5TE and Thumb1 does not have preload instructions.
2760 if (!(Subtarget->isThumb2() ||
2761 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2762 // Just preserve the chain.
2763 return Op.getOperand(0);
2766 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2768 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2769 // ARMv7 with MP extension has PLDW.
2770 return Op.getOperand(0);
2772 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2773 if (Subtarget->isThumb()) {
2775 isRead = ~isRead & 1;
2776 isData = ~isData & 1;
2779 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2780 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2781 DAG.getConstant(isData, MVT::i32));
2784 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2785 MachineFunction &MF = DAG.getMachineFunction();
2786 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2788 // vastart just stores the address of the VarArgsFrameIndex slot into the
2789 // memory location argument.
2791 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2792 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2793 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2794 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2795 MachinePointerInfo(SV), false, false, 0);
2799 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2800 SDValue &Root, SelectionDAG &DAG,
2802 MachineFunction &MF = DAG.getMachineFunction();
2803 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2805 const TargetRegisterClass *RC;
2806 if (AFI->isThumb1OnlyFunction())
2807 RC = &ARM::tGPRRegClass;
2809 RC = &ARM::GPRRegClass;
2811 // Transform the arguments stored in physical registers into virtual ones.
2812 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2813 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2816 if (NextVA.isMemLoc()) {
2817 MachineFrameInfo *MFI = MF.getFrameInfo();
2818 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2820 // Create load node to retrieve arguments from the stack.
2821 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2822 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2823 MachinePointerInfo::getFixedStack(FI),
2824 false, false, false, 0);
2826 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2827 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2829 if (!Subtarget->isLittle())
2830 std::swap (ArgValue, ArgValue2);
2831 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2835 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2836 unsigned InRegsParamRecordIdx,
2838 unsigned &ArgRegsSize,
2839 unsigned &ArgRegsSaveSize)
2842 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2843 unsigned RBegin, REnd;
2844 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2845 NumGPRs = REnd - RBegin;
2847 unsigned int firstUnalloced;
2848 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2849 sizeof(GPRArgRegs) /
2850 sizeof(GPRArgRegs[0]));
2851 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2854 unsigned Align = MF.getTarget()
2856 ->getFrameLowering()
2857 ->getStackAlignment();
2858 ArgRegsSize = NumGPRs * 4;
2860 // If parameter is split between stack and GPRs...
2861 if (NumGPRs && Align > 4 &&
2862 (ArgRegsSize < ArgSize ||
2863 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2864 // Add padding for part of param recovered from GPRs. For example,
2865 // if Align == 8, its last byte must be at address K*8 - 1.
2866 // We need to do it, since remained (stack) part of parameter has
2867 // stack alignment, and we need to "attach" "GPRs head" without gaps
2870 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2871 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2873 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2875 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2876 ArgRegsSaveSize = ArgRegsSize + Padding;
2878 // We don't need to extend regs save size for byval parameters if they
2879 // are passed via GPRs only.
2880 ArgRegsSaveSize = ArgRegsSize;
2883 // The remaining GPRs hold either the beginning of variable-argument
2884 // data, or the beginning of an aggregate passed by value (usually
2885 // byval). Either way, we allocate stack slots adjacent to the data
2886 // provided by our caller, and store the unallocated registers there.
2887 // If this is a variadic function, the va_list pointer will begin with
2888 // these values; otherwise, this reassembles a (byval) structure that
2889 // was split between registers and memory.
2890 // Return: The frame index registers were stored into.
2892 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2893 SDLoc dl, SDValue &Chain,
2894 const Value *OrigArg,
2895 unsigned InRegsParamRecordIdx,
2896 unsigned OffsetFromOrigArg,
2900 unsigned ByValStoreOffset,
2901 unsigned TotalArgRegsSaveSize) const {
2903 // Currently, two use-cases possible:
2904 // Case #1. Non-var-args function, and we meet first byval parameter.
2905 // Setup first unallocated register as first byval register;
2906 // eat all remained registers
2907 // (these two actions are performed by HandleByVal method).
2908 // Then, here, we initialize stack frame with
2909 // "store-reg" instructions.
2910 // Case #2. Var-args function, that doesn't contain byval parameters.
2911 // The same: eat all remained unallocated registers,
2912 // initialize stack frame.
2914 MachineFunction &MF = DAG.getMachineFunction();
2915 MachineFrameInfo *MFI = MF.getFrameInfo();
2916 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2917 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2918 unsigned RBegin, REnd;
2919 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2920 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2921 firstRegToSaveIndex = RBegin - ARM::R0;
2922 lastRegToSaveIndex = REnd - ARM::R0;
2924 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2925 (GPRArgRegs, array_lengthof(GPRArgRegs));
2926 lastRegToSaveIndex = 4;
2929 unsigned ArgRegsSize, ArgRegsSaveSize;
2930 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2931 ArgRegsSize, ArgRegsSaveSize);
2933 // Store any by-val regs to their spots on the stack so that they may be
2934 // loaded by deferencing the result of formal parameter pointer or va_next.
2935 // Note: once stack area for byval/varargs registers
2936 // was initialized, it can't be initialized again.
2937 if (ArgRegsSaveSize) {
2938 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2941 assert(AFI->getStoredByValParamsPadding() == 0 &&
2942 "The only parameter may be padded.");
2943 AFI->setStoredByValParamsPadding(Padding);
2946 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2949 (int64_t)TotalArgRegsSaveSize,
2951 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2953 MFI->CreateFixedObject(Padding,
2954 ArgOffset + ByValStoreOffset -
2955 (int64_t)ArgRegsSaveSize,
2959 SmallVector<SDValue, 4> MemOps;
2960 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2961 ++firstRegToSaveIndex, ++i) {
2962 const TargetRegisterClass *RC;
2963 if (AFI->isThumb1OnlyFunction())
2964 RC = &ARM::tGPRRegClass;
2966 RC = &ARM::GPRRegClass;
2968 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2969 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2971 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2972 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2974 MemOps.push_back(Store);
2975 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2976 DAG.getConstant(4, getPointerTy()));
2979 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2981 if (!MemOps.empty())
2982 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2986 // We cannot allocate a zero-byte object for the first variadic argument,
2987 // so just make up a size.
2990 // This will point to the next argument passed via stack.
2991 return MFI->CreateFixedObject(
2992 ArgSize, ArgOffset, !ForceMutable);
2996 // Setup stack frame, the va_list pointer will start from.
2998 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2999 SDLoc dl, SDValue &Chain,
3001 unsigned TotalArgRegsSaveSize,
3002 bool ForceMutable) const {
3003 MachineFunction &MF = DAG.getMachineFunction();
3004 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3006 // Try to store any remaining integer argument regs
3007 // to their spots on the stack so that they may be loaded by deferencing
3008 // the result of va_next.
3009 // If there is no regs to be stored, just point address after last
3010 // argument passed via stack.
3012 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3013 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
3014 0, TotalArgRegsSaveSize);
3016 AFI->setVarArgsFrameIndex(FrameIndex);
3020 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3021 CallingConv::ID CallConv, bool isVarArg,
3022 const SmallVectorImpl<ISD::InputArg>
3024 SDLoc dl, SelectionDAG &DAG,
3025 SmallVectorImpl<SDValue> &InVals)
3027 MachineFunction &MF = DAG.getMachineFunction();
3028 MachineFrameInfo *MFI = MF.getFrameInfo();
3030 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3032 // Assign locations to all of the incoming arguments.
3033 SmallVector<CCValAssign, 16> ArgLocs;
3034 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3035 *DAG.getContext(), Prologue);
3036 CCInfo.AnalyzeFormalArguments(Ins,
3037 CCAssignFnForNode(CallConv, /* Return*/ false,
3040 SmallVector<SDValue, 16> ArgValues;
3041 int lastInsIndex = -1;
3043 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3044 unsigned CurArgIdx = 0;
3046 // Initially ArgRegsSaveSize is zero.
3047 // Then we increase this value each time we meet byval parameter.
3048 // We also increase this value in case of varargs function.
3049 AFI->setArgRegsSaveSize(0);
3051 unsigned ByValStoreOffset = 0;
3052 unsigned TotalArgRegsSaveSize = 0;
3053 unsigned ArgRegsSaveSizeMaxAlign = 4;
3055 // Calculate the amount of stack space that we need to allocate to store
3056 // byval and variadic arguments that are passed in registers.
3057 // We need to know this before we allocate the first byval or variadic
3058 // argument, as they will be allocated a stack slot below the CFA (Canonical
3059 // Frame Address, the stack pointer at entry to the function).
3060 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3061 CCValAssign &VA = ArgLocs[i];
3062 if (VA.isMemLoc()) {
3063 int index = VA.getValNo();
3064 if (index != lastInsIndex) {
3065 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3066 if (Flags.isByVal()) {
3067 unsigned ExtraArgRegsSize;
3068 unsigned ExtraArgRegsSaveSize;
3069 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3070 Flags.getByValSize(),
3071 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3073 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3074 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3075 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3076 CCInfo.nextInRegsParam();
3078 lastInsIndex = index;
3082 CCInfo.rewindByValRegsInfo();
3084 if (isVarArg && MFI->hasVAStart()) {
3085 unsigned ExtraArgRegsSize;
3086 unsigned ExtraArgRegsSaveSize;
3087 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3088 ExtraArgRegsSize, ExtraArgRegsSaveSize);
3089 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3091 // If the arg regs save area contains N-byte aligned values, the
3092 // bottom of it must be at least N-byte aligned.
3093 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3094 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3096 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3097 CCValAssign &VA = ArgLocs[i];
3098 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3099 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3100 // Arguments stored in registers.
3101 if (VA.isRegLoc()) {
3102 EVT RegVT = VA.getLocVT();
3104 if (VA.needsCustom()) {
3105 // f64 and vector types are split up into multiple registers or
3106 // combinations of registers and stack slots.
3107 if (VA.getLocVT() == MVT::v2f64) {
3108 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3110 VA = ArgLocs[++i]; // skip ahead to next loc
3112 if (VA.isMemLoc()) {
3113 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3114 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3115 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3116 MachinePointerInfo::getFixedStack(FI),
3117 false, false, false, 0);
3119 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3122 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3123 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3124 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3125 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3126 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3128 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3131 const TargetRegisterClass *RC;
3133 if (RegVT == MVT::f32)
3134 RC = &ARM::SPRRegClass;
3135 else if (RegVT == MVT::f64)
3136 RC = &ARM::DPRRegClass;
3137 else if (RegVT == MVT::v2f64)
3138 RC = &ARM::QPRRegClass;
3139 else if (RegVT == MVT::i32)
3140 RC = AFI->isThumb1OnlyFunction() ?
3141 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3142 (const TargetRegisterClass*)&ARM::GPRRegClass;
3144 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3146 // Transform the arguments in physical registers into virtual ones.
3147 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3148 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3151 // If this is an 8 or 16-bit value, it is really passed promoted
3152 // to 32 bits. Insert an assert[sz]ext to capture this, then
3153 // truncate to the right size.
3154 switch (VA.getLocInfo()) {
3155 default: llvm_unreachable("Unknown loc info!");
3156 case CCValAssign::Full: break;
3157 case CCValAssign::BCvt:
3158 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3160 case CCValAssign::SExt:
3161 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3162 DAG.getValueType(VA.getValVT()));
3163 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3165 case CCValAssign::ZExt:
3166 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3167 DAG.getValueType(VA.getValVT()));
3168 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3172 InVals.push_back(ArgValue);
3174 } else { // VA.isRegLoc()
3177 assert(VA.isMemLoc());
3178 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3180 int index = ArgLocs[i].getValNo();
3182 // Some Ins[] entries become multiple ArgLoc[] entries.
3183 // Process them only once.
3184 if (index != lastInsIndex)
3186 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3187 // FIXME: For now, all byval parameter objects are marked mutable.
3188 // This can be changed with more analysis.
3189 // In case of tail call optimization mark all arguments mutable.
3190 // Since they could be overwritten by lowering of arguments in case of
3192 if (Flags.isByVal()) {
3193 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3195 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3196 int FrameIndex = StoreByValRegs(
3197 CCInfo, DAG, dl, Chain, CurOrigArg,
3199 Ins[VA.getValNo()].PartOffset,
3200 VA.getLocMemOffset(),
3201 Flags.getByValSize(),
3202 true /*force mutable frames*/,
3204 TotalArgRegsSaveSize);
3205 ByValStoreOffset += Flags.getByValSize();
3206 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3207 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3208 CCInfo.nextInRegsParam();
3210 unsigned FIOffset = VA.getLocMemOffset();
3211 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3214 // Create load nodes to retrieve arguments from the stack.
3215 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3216 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3217 MachinePointerInfo::getFixedStack(FI),
3218 false, false, false, 0));
3220 lastInsIndex = index;
3226 if (isVarArg && MFI->hasVAStart())
3227 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3228 CCInfo.getNextStackOffset(),
3229 TotalArgRegsSaveSize);
3231 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3236 /// isFloatingPointZero - Return true if this is +0.0.
3237 static bool isFloatingPointZero(SDValue Op) {
3238 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3239 return CFP->getValueAPF().isPosZero();
3240 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3241 // Maybe this has already been legalized into the constant pool?
3242 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3243 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3244 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3245 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3246 return CFP->getValueAPF().isPosZero();
3248 } else if (Op->getOpcode() == ISD::BITCAST &&
3249 Op->getValueType(0) == MVT::f64) {
3250 // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3251 // created by LowerConstantFP().
3252 SDValue BitcastOp = Op->getOperand(0);
3253 if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3254 SDValue MoveOp = BitcastOp->getOperand(0);
3255 if (MoveOp->getOpcode() == ISD::TargetConstant &&
3256 cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3264 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3265 /// the given operands.
3267 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3268 SDValue &ARMcc, SelectionDAG &DAG,
3270 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3271 unsigned C = RHSC->getZExtValue();
3272 if (!isLegalICmpImmediate(C)) {
3273 // Constant does not fit, try adjusting it by one?
3278 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3279 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3280 RHS = DAG.getConstant(C-1, MVT::i32);
3285 if (C != 0 && isLegalICmpImmediate(C-1)) {
3286 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3287 RHS = DAG.getConstant(C-1, MVT::i32);
3292 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3293 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3294 RHS = DAG.getConstant(C+1, MVT::i32);
3299 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3300 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3301 RHS = DAG.getConstant(C+1, MVT::i32);
3308 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3309 ARMISD::NodeType CompareType;
3312 CompareType = ARMISD::CMP;
3317 CompareType = ARMISD::CMPZ;
3320 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3321 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3324 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3326 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3328 assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3330 if (!isFloatingPointZero(RHS))
3331 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3333 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3334 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3337 /// duplicateCmp - Glue values can have only one use, so this function
3338 /// duplicates a comparison node.
3340 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3341 unsigned Opc = Cmp.getOpcode();
3343 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3344 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3346 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3347 Cmp = Cmp.getOperand(0);
3348 Opc = Cmp.getOpcode();
3349 if (Opc == ARMISD::CMPFP)
3350 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3352 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3353 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3355 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3358 std::pair<SDValue, SDValue>
3359 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3360 SDValue &ARMcc) const {
3361 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3363 SDValue Value, OverflowCmp;
3364 SDValue LHS = Op.getOperand(0);
3365 SDValue RHS = Op.getOperand(1);
3368 // FIXME: We are currently always generating CMPs because we don't support
3369 // generating CMN through the backend. This is not as good as the natural
3370 // CMP case because it causes a register dependency and cannot be folded
3373 switch (Op.getOpcode()) {
3375 llvm_unreachable("Unknown overflow instruction!");
3377 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3378 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3379 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3382 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3383 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3384 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3387 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3388 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3389 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3392 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3393 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3394 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3398 return std::make_pair(Value, OverflowCmp);
3403 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3404 // Let legalize expand this if it isn't a legal type yet.
3405 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3408 SDValue Value, OverflowCmp;
3410 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3411 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3412 // We use 0 and 1 as false and true values.
3413 SDValue TVal = DAG.getConstant(1, MVT::i32);
3414 SDValue FVal = DAG.getConstant(0, MVT::i32);
3415 EVT VT = Op.getValueType();
3417 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3418 ARMcc, CCR, OverflowCmp);
3420 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3421 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3425 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3426 SDValue Cond = Op.getOperand(0);
3427 SDValue SelectTrue = Op.getOperand(1);
3428 SDValue SelectFalse = Op.getOperand(2);
3430 unsigned Opc = Cond.getOpcode();
3432 if (Cond.getResNo() == 1 &&
3433 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3434 Opc == ISD::USUBO)) {
3435 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3438 SDValue Value, OverflowCmp;
3440 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3441 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3442 EVT VT = Op.getValueType();
3444 return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3450 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3451 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3453 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3454 const ConstantSDNode *CMOVTrue =
3455 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3456 const ConstantSDNode *CMOVFalse =
3457 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3459 if (CMOVTrue && CMOVFalse) {
3460 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3461 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3465 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3467 False = SelectFalse;
3468 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3473 if (True.getNode() && False.getNode()) {
3474 EVT VT = Op.getValueType();
3475 SDValue ARMcc = Cond.getOperand(2);
3476 SDValue CCR = Cond.getOperand(3);
3477 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3478 assert(True.getValueType() == VT);
3479 return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3484 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3485 // undefined bits before doing a full-word comparison with zero.
3486 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3487 DAG.getConstant(1, Cond.getValueType()));
3489 return DAG.getSelectCC(dl, Cond,
3490 DAG.getConstant(0, Cond.getValueType()),
3491 SelectTrue, SelectFalse, ISD::SETNE);
3494 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3495 if (CC == ISD::SETNE)
3497 return ISD::getSetCCInverse(CC, true);
3500 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3501 bool &swpCmpOps, bool &swpVselOps) {
3502 // Start by selecting the GE condition code for opcodes that return true for
3504 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3506 CondCode = ARMCC::GE;
3508 // and GT for opcodes that return false for 'equality'.
3509 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3511 CondCode = ARMCC::GT;
3513 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3514 // to swap the compare operands.
3515 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3519 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3520 // If we have an unordered opcode, we need to swap the operands to the VSEL
3521 // instruction (effectively negating the condition).
3523 // This also has the effect of swapping which one of 'less' or 'greater'
3524 // returns true, so we also swap the compare operands. It also switches
3525 // whether we return true for 'equality', so we compensate by picking the
3526 // opposite condition code to our original choice.
3527 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3528 CC == ISD::SETUGT) {
3529 swpCmpOps = !swpCmpOps;
3530 swpVselOps = !swpVselOps;
3531 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3534 // 'ordered' is 'anything but unordered', so use the VS condition code and
3535 // swap the VSEL operands.
3536 if (CC == ISD::SETO) {
3537 CondCode = ARMCC::VS;
3541 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3542 // code and swap the VSEL operands.
3543 if (CC == ISD::SETUNE) {
3544 CondCode = ARMCC::EQ;
3549 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3550 SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3551 SDValue Cmp, SelectionDAG &DAG) const {
3552 if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3553 FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3554 DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3555 TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3556 DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3558 SDValue TrueLow = TrueVal.getValue(0);
3559 SDValue TrueHigh = TrueVal.getValue(1);
3560 SDValue FalseLow = FalseVal.getValue(0);
3561 SDValue FalseHigh = FalseVal.getValue(1);
3563 SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3565 SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3566 ARMcc, CCR, duplicateCmp(Cmp, DAG));
3568 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3570 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3575 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3576 EVT VT = Op.getValueType();
3577 SDValue LHS = Op.getOperand(0);
3578 SDValue RHS = Op.getOperand(1);
3579 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3580 SDValue TrueVal = Op.getOperand(2);
3581 SDValue FalseVal = Op.getOperand(3);
3584 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3585 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3588 // If softenSetCCOperands only returned one value, we should compare it to
3590 if (!RHS.getNode()) {
3591 RHS = DAG.getConstant(0, LHS.getValueType());
3596 if (LHS.getValueType() == MVT::i32) {
3597 // Try to generate VSEL on ARMv8.
3598 // The VSEL instruction can't use all the usual ARM condition
3599 // codes: it only has two bits to select the condition code, so it's
3600 // constrained to use only GE, GT, VS and EQ.
3602 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3603 // swap the operands of the previous compare instruction (effectively
3604 // inverting the compare condition, swapping 'less' and 'greater') and
3605 // sometimes need to swap the operands to the VSEL (which inverts the
3606 // condition in the sense of firing whenever the previous condition didn't)
3607 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3608 TrueVal.getValueType() == MVT::f64)) {
3609 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3610 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3611 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3612 CC = getInverseCCForVSEL(CC);
3613 std::swap(TrueVal, FalseVal);
3618 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3619 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3620 return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3623 ARMCC::CondCodes CondCode, CondCode2;
3624 FPCCToARMCC(CC, CondCode, CondCode2);
3626 // Try to generate VSEL on ARMv8.
3627 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3628 TrueVal.getValueType() == MVT::f64)) {
3629 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3630 // same operands, as follows:
3631 // c = fcmp [ogt, olt, ugt, ult] a, b
3633 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3634 // handled differently than the original code sequence.
3635 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3637 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3638 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3639 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3640 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3643 bool swpCmpOps = false;
3644 bool swpVselOps = false;
3645 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3647 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3648 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3650 std::swap(LHS, RHS);
3652 std::swap(TrueVal, FalseVal);
3656 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3657 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3658 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3659 SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3660 if (CondCode2 != ARMCC::AL) {
3661 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3662 // FIXME: Needs another CMP because flag can have but one use.
3663 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3664 Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3669 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3670 /// to morph to an integer compare sequence.
3671 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3672 const ARMSubtarget *Subtarget) {
3673 SDNode *N = Op.getNode();
3674 if (!N->hasOneUse())
3675 // Otherwise it requires moving the value from fp to integer registers.
3677 if (!N->getNumValues())
3679 EVT VT = Op.getValueType();
3680 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3681 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3682 // vmrs are very slow, e.g. cortex-a8.
3685 if (isFloatingPointZero(Op)) {
3689 return ISD::isNormalLoad(N);
3692 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3693 if (isFloatingPointZero(Op))
3694 return DAG.getConstant(0, MVT::i32);
3696 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3697 return DAG.getLoad(MVT::i32, SDLoc(Op),
3698 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3699 Ld->isVolatile(), Ld->isNonTemporal(),
3700 Ld->isInvariant(), Ld->getAlignment());
3702 llvm_unreachable("Unknown VFP cmp argument!");
3705 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3706 SDValue &RetVal1, SDValue &RetVal2) {
3707 if (isFloatingPointZero(Op)) {
3708 RetVal1 = DAG.getConstant(0, MVT::i32);
3709 RetVal2 = DAG.getConstant(0, MVT::i32);
3713 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3714 SDValue Ptr = Ld->getBasePtr();
3715 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3716 Ld->getChain(), Ptr,
3717 Ld->getPointerInfo(),
3718 Ld->isVolatile(), Ld->isNonTemporal(),
3719 Ld->isInvariant(), Ld->getAlignment());
3721 EVT PtrType = Ptr.getValueType();
3722 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3723 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3724 PtrType, Ptr, DAG.getConstant(4, PtrType));
3725 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3726 Ld->getChain(), NewPtr,
3727 Ld->getPointerInfo().getWithOffset(4),
3728 Ld->isVolatile(), Ld->isNonTemporal(),
3729 Ld->isInvariant(), NewAlign);
3733 llvm_unreachable("Unknown VFP cmp argument!");
3736 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3737 /// f32 and even f64 comparisons to integer ones.
3739 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3740 SDValue Chain = Op.getOperand(0);
3741 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3742 SDValue LHS = Op.getOperand(2);
3743 SDValue RHS = Op.getOperand(3);
3744 SDValue Dest = Op.getOperand(4);
3747 bool LHSSeenZero = false;
3748 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3749 bool RHSSeenZero = false;
3750 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3751 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3752 // If unsafe fp math optimization is enabled and there are no other uses of
3753 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3754 // to an integer comparison.
3755 if (CC == ISD::SETOEQ)
3757 else if (CC == ISD::SETUNE)
3760 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3762 if (LHS.getValueType() == MVT::f32) {
3763 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3764 bitcastf32Toi32(LHS, DAG), Mask);
3765 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3766 bitcastf32Toi32(RHS, DAG), Mask);
3767 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3768 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3769 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3770 Chain, Dest, ARMcc, CCR, Cmp);
3775 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3776 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3777 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3778 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3779 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3780 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3781 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3782 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3783 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3789 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3790 SDValue Chain = Op.getOperand(0);
3791 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3792 SDValue LHS = Op.getOperand(2);
3793 SDValue RHS = Op.getOperand(3);
3794 SDValue Dest = Op.getOperand(4);
3797 if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3798 DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3801 // If softenSetCCOperands only returned one value, we should compare it to
3803 if (!RHS.getNode()) {
3804 RHS = DAG.getConstant(0, LHS.getValueType());
3809 if (LHS.getValueType() == MVT::i32) {
3811 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3812 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3813 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3814 Chain, Dest, ARMcc, CCR, Cmp);
3817 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3819 if (getTargetMachine().Options.UnsafeFPMath &&
3820 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3821 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3822 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3823 if (Result.getNode())
3827 ARMCC::CondCodes CondCode, CondCode2;
3828 FPCCToARMCC(CC, CondCode, CondCode2);
3830 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3831 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3832 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3833 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3834 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3835 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3836 if (CondCode2 != ARMCC::AL) {
3837 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3838 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3839 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3844 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3845 SDValue Chain = Op.getOperand(0);
3846 SDValue Table = Op.getOperand(1);
3847 SDValue Index = Op.getOperand(2);
3850 EVT PTy = getPointerTy();
3851 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3852 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3853 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3854 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3855 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3856 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3857 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3858 if (Subtarget->isThumb2()) {
3859 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3860 // which does another jump to the destination. This also makes it easier
3861 // to translate it to TBB / TBH later.
3862 // FIXME: This might not work if the function is extremely large.
3863 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3864 Addr, Op.getOperand(2), JTI, UId);
3866 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3867 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3868 MachinePointerInfo::getJumpTable(),
3869 false, false, false, 0);
3870 Chain = Addr.getValue(1);
3871 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3872 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3874 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3875 MachinePointerInfo::getJumpTable(),
3876 false, false, false, 0);
3877 Chain = Addr.getValue(1);
3878 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3882 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3883 EVT VT = Op.getValueType();
3886 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3887 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3889 return DAG.UnrollVectorOp(Op.getNode());
3892 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3893 "Invalid type for custom lowering!");
3894 if (VT != MVT::v4i16)
3895 return DAG.UnrollVectorOp(Op.getNode());
3897 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3898 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3901 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3902 EVT VT = Op.getValueType();
3904 return LowerVectorFP_TO_INT(Op, DAG);
3906 if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3908 if (Op.getOpcode() == ISD::FP_TO_SINT)
3909 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3912 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3914 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3915 /*isSigned*/ false, SDLoc(Op)).first;
3921 switch (Op.getOpcode()) {
3922 default: llvm_unreachable("Invalid opcode!");
3923 case ISD::FP_TO_SINT:
3924 Opc = ARMISD::FTOSI;
3926 case ISD::FP_TO_UINT:
3927 Opc = ARMISD::FTOUI;
3930 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3931 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3934 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3935 EVT VT = Op.getValueType();
3938 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3939 if (VT.getVectorElementType() == MVT::f32)
3941 return DAG.UnrollVectorOp(Op.getNode());
3944 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3945 "Invalid type for custom lowering!");
3946 if (VT != MVT::v4f32)
3947 return DAG.UnrollVectorOp(Op.getNode());
3951 switch (Op.getOpcode()) {
3952 default: llvm_unreachable("Invalid opcode!");
3953 case ISD::SINT_TO_FP:
3954 CastOpc = ISD::SIGN_EXTEND;
3955 Opc = ISD::SINT_TO_FP;
3957 case ISD::UINT_TO_FP:
3958 CastOpc = ISD::ZERO_EXTEND;
3959 Opc = ISD::UINT_TO_FP;
3963 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3964 return DAG.getNode(Opc, dl, VT, Op);
3967 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3968 EVT VT = Op.getValueType();
3970 return LowerVectorINT_TO_FP(Op, DAG);
3972 if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3974 if (Op.getOpcode() == ISD::SINT_TO_FP)
3975 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3978 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3980 return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3981 /*isSigned*/ false, SDLoc(Op)).first;
3987 switch (Op.getOpcode()) {
3988 default: llvm_unreachable("Invalid opcode!");
3989 case ISD::SINT_TO_FP:
3990 Opc = ARMISD::SITOF;
3992 case ISD::UINT_TO_FP:
3993 Opc = ARMISD::UITOF;
3997 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3998 return DAG.getNode(Opc, dl, VT, Op);
4001 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4002 // Implement fcopysign with a fabs and a conditional fneg.
4003 SDValue Tmp0 = Op.getOperand(0);
4004 SDValue Tmp1 = Op.getOperand(1);
4006 EVT VT = Op.getValueType();
4007 EVT SrcVT = Tmp1.getValueType();
4008 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4009 Tmp0.getOpcode() == ARMISD::VMOVDRR;
4010 bool UseNEON = !InGPR && Subtarget->hasNEON();
4013 // Use VBSL to copy the sign bit.
4014 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4015 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4016 DAG.getTargetConstant(EncodedVal, MVT::i32));
4017 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4019 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4020 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4021 DAG.getConstant(32, MVT::i32));
4022 else /*if (VT == MVT::f32)*/
4023 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4024 if (SrcVT == MVT::f32) {
4025 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4027 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4028 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4029 DAG.getConstant(32, MVT::i32));
4030 } else if (VT == MVT::f32)
4031 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4032 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4033 DAG.getConstant(32, MVT::i32));
4034 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4035 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4037 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4039 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4040 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4041 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4043 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4044 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4045 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4046 if (VT == MVT::f32) {
4047 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4048 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4049 DAG.getConstant(0, MVT::i32));
4051 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4057 // Bitcast operand 1 to i32.
4058 if (SrcVT == MVT::f64)
4059 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4061 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4063 // Or in the signbit with integer operations.
4064 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4065 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4066 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4067 if (VT == MVT::f32) {
4068 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4069 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4070 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4071 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4074 // f64: Or the high part with signbit and then combine two parts.
4075 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4077 SDValue Lo = Tmp0.getValue(0);
4078 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4079 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4080 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4083 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4084 MachineFunction &MF = DAG.getMachineFunction();
4085 MachineFrameInfo *MFI = MF.getFrameInfo();
4086 MFI->setReturnAddressIsTaken(true);
4088 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4091 EVT VT = Op.getValueType();
4093 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4095 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4096 SDValue Offset = DAG.getConstant(4, MVT::i32);
4097 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4098 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4099 MachinePointerInfo(), false, false, false, 0);
4102 // Return LR, which contains the return address. Mark it an implicit live-in.
4103 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4104 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4107 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4108 const ARMBaseRegisterInfo &ARI =
4109 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4110 MachineFunction &MF = DAG.getMachineFunction();
4111 MachineFrameInfo *MFI = MF.getFrameInfo();
4112 MFI->setFrameAddressIsTaken(true);
4114 EVT VT = Op.getValueType();
4115 SDLoc dl(Op); // FIXME probably not meaningful
4116 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4117 unsigned FrameReg = ARI.getFrameRegister(MF);
4118 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4120 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4121 MachinePointerInfo(),
4122 false, false, false, 0);
4126 // FIXME? Maybe this could be a TableGen attribute on some registers and
4127 // this table could be generated automatically from RegInfo.
4128 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4130 unsigned Reg = StringSwitch<unsigned>(RegName)
4131 .Case("sp", ARM::SP)
4135 report_fatal_error("Invalid register name global variable");
4138 /// ExpandBITCAST - If the target supports VFP, this function is called to
4139 /// expand a bit convert where either the source or destination type is i64 to
4140 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
4141 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4142 /// vectors), since the legalizer won't know what to do with that.
4143 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4144 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4146 SDValue Op = N->getOperand(0);
4148 // This function is only supposed to be called for i64 types, either as the
4149 // source or destination of the bit convert.
4150 EVT SrcVT = Op.getValueType();
4151 EVT DstVT = N->getValueType(0);
4152 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4153 "ExpandBITCAST called for non-i64 type");
4155 // Turn i64->f64 into VMOVDRR.
4156 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4157 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4158 DAG.getConstant(0, MVT::i32));
4159 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4160 DAG.getConstant(1, MVT::i32));
4161 return DAG.getNode(ISD::BITCAST, dl, DstVT,
4162 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4165 // Turn f64->i64 into VMOVRRD.
4166 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4168 if (TLI.isBigEndian() && SrcVT.isVector() &&
4169 SrcVT.getVectorNumElements() > 1)
4170 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4171 DAG.getVTList(MVT::i32, MVT::i32),
4172 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4174 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4175 DAG.getVTList(MVT::i32, MVT::i32), Op);
4176 // Merge the pieces into a single i64 value.
4177 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4183 /// getZeroVector - Returns a vector of specified type with all zero elements.
4184 /// Zero vectors are used to represent vector negation and in those cases
4185 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4186 /// not support i64 elements, so sometimes the zero vectors will need to be
4187 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4189 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4190 assert(VT.isVector() && "Expected a vector type");
4191 // The canonical modified immediate encoding of a zero vector is....0!
4192 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4193 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4194 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4195 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4198 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4199 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4200 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4201 SelectionDAG &DAG) const {
4202 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4203 EVT VT = Op.getValueType();
4204 unsigned VTBits = VT.getSizeInBits();
4206 SDValue ShOpLo = Op.getOperand(0);
4207 SDValue ShOpHi = Op.getOperand(1);
4208 SDValue ShAmt = Op.getOperand(2);
4210 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4212 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4214 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4215 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4216 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4217 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4218 DAG.getConstant(VTBits, MVT::i32));
4219 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4220 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4221 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4223 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4224 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4226 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4227 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4230 SDValue Ops[2] = { Lo, Hi };
4231 return DAG.getMergeValues(Ops, dl);
4234 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4235 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4236 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4237 SelectionDAG &DAG) const {
4238 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4239 EVT VT = Op.getValueType();
4240 unsigned VTBits = VT.getSizeInBits();
4242 SDValue ShOpLo = Op.getOperand(0);
4243 SDValue ShOpHi = Op.getOperand(1);
4244 SDValue ShAmt = Op.getOperand(2);
4247 assert(Op.getOpcode() == ISD::SHL_PARTS);
4248 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4249 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4250 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4251 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4252 DAG.getConstant(VTBits, MVT::i32));
4253 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4254 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4256 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4257 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4258 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4260 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4261 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4264 SDValue Ops[2] = { Lo, Hi };
4265 return DAG.getMergeValues(Ops, dl);
4268 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4269 SelectionDAG &DAG) const {
4270 // The rounding mode is in bits 23:22 of the FPSCR.
4271 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4272 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4273 // so that the shift + and get folded into a bitfield extract.
4275 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4276 DAG.getConstant(Intrinsic::arm_get_fpscr,
4278 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4279 DAG.getConstant(1U << 22, MVT::i32));
4280 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4281 DAG.getConstant(22, MVT::i32));
4282 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4283 DAG.getConstant(3, MVT::i32));
4286 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4287 const ARMSubtarget *ST) {
4288 EVT VT = N->getValueType(0);
4291 if (!ST->hasV6T2Ops())
4294 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4295 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4298 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4299 /// for each 16-bit element from operand, repeated. The basic idea is to
4300 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4302 /// Trace for v4i16:
4303 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4304 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4305 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4306 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4307 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4308 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4309 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4310 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4311 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4312 EVT VT = N->getValueType(0);
4315 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4316 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4317 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4318 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4319 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4320 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4323 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4324 /// bit-count for each 16-bit element from the operand. We need slightly
4325 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4326 /// 64/128-bit registers.
4328 /// Trace for v4i16:
4329 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4330 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4331 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4332 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4333 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4334 EVT VT = N->getValueType(0);
4337 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4338 if (VT.is64BitVector()) {
4339 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4340 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4341 DAG.getIntPtrConstant(0));
4343 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4344 BitCounts, DAG.getIntPtrConstant(0));
4345 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4349 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4350 /// bit-count for each 32-bit element from the operand. The idea here is
4351 /// to split the vector into 16-bit elements, leverage the 16-bit count
4352 /// routine, and then combine the results.
4354 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4355 /// input = [v0 v1 ] (vi: 32-bit elements)
4356 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4357 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4358 /// vrev: N0 = [k1 k0 k3 k2 ]
4360 /// N1 =+[k1 k0 k3 k2 ]
4362 /// N2 =+[k1 k3 k0 k2 ]
4364 /// Extended =+[k1 k3 k0 k2 ]
4366 /// Extracted=+[k1 k3 ]
4368 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4369 EVT VT = N->getValueType(0);
4372 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4374 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4375 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4376 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4377 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4378 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4380 if (VT.is64BitVector()) {
4381 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4382 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4383 DAG.getIntPtrConstant(0));
4385 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4386 DAG.getIntPtrConstant(0));
4387 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4391 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4392 const ARMSubtarget *ST) {
4393 EVT VT = N->getValueType(0);
4395 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4396 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4397 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4398 "Unexpected type for custom ctpop lowering");
4400 if (VT.getVectorElementType() == MVT::i32)
4401 return lowerCTPOP32BitElements(N, DAG);
4403 return lowerCTPOP16BitElements(N, DAG);
4406 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4407 const ARMSubtarget *ST) {
4408 EVT VT = N->getValueType(0);
4414 // Lower vector shifts on NEON to use VSHL.
4415 assert(ST->hasNEON() && "unexpected vector shift");
4417 // Left shifts translate directly to the vshiftu intrinsic.
4418 if (N->getOpcode() == ISD::SHL)
4419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4420 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4421 N->getOperand(0), N->getOperand(1));
4423 assert((N->getOpcode() == ISD::SRA ||
4424 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4426 // NEON uses the same intrinsics for both left and right shifts. For
4427 // right shifts, the shift amounts are negative, so negate the vector of
4429 EVT ShiftVT = N->getOperand(1).getValueType();
4430 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4431 getZeroVector(ShiftVT, DAG, dl),
4433 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4434 Intrinsic::arm_neon_vshifts :
4435 Intrinsic::arm_neon_vshiftu);
4436 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4437 DAG.getConstant(vshiftInt, MVT::i32),
4438 N->getOperand(0), NegatedCount);
4441 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4442 const ARMSubtarget *ST) {
4443 EVT VT = N->getValueType(0);
4446 // We can get here for a node like i32 = ISD::SHL i32, i64
4450 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4451 "Unknown shift to lower!");
4453 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4454 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4455 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4458 // If we are in thumb mode, we don't have RRX.
4459 if (ST->isThumb1Only()) return SDValue();
4461 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4462 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4463 DAG.getConstant(0, MVT::i32));
4464 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4465 DAG.getConstant(1, MVT::i32));
4467 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4468 // captures the result into a carry flag.
4469 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4470 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4472 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4473 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4475 // Merge the pieces into a single i64 value.
4476 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4479 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4480 SDValue TmpOp0, TmpOp1;
4481 bool Invert = false;
4485 SDValue Op0 = Op.getOperand(0);
4486 SDValue Op1 = Op.getOperand(1);
4487 SDValue CC = Op.getOperand(2);
4488 EVT VT = Op.getValueType();
4489 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4492 if (Op1.getValueType().isFloatingPoint()) {
4493 switch (SetCCOpcode) {
4494 default: llvm_unreachable("Illegal FP comparison");
4496 case ISD::SETNE: Invert = true; // Fallthrough
4498 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4500 case ISD::SETLT: Swap = true; // Fallthrough
4502 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4504 case ISD::SETLE: Swap = true; // Fallthrough
4506 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4507 case ISD::SETUGE: Swap = true; // Fallthrough
4508 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4509 case ISD::SETUGT: Swap = true; // Fallthrough
4510 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4511 case ISD::SETUEQ: Invert = true; // Fallthrough
4513 // Expand this to (OLT | OGT).
4517 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4518 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4520 case ISD::SETUO: Invert = true; // Fallthrough
4522 // Expand this to (OLT | OGE).
4526 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4527 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4531 // Integer comparisons.
4532 switch (SetCCOpcode) {
4533 default: llvm_unreachable("Illegal integer comparison");
4534 case ISD::SETNE: Invert = true;
4535 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4536 case ISD::SETLT: Swap = true;
4537 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4538 case ISD::SETLE: Swap = true;
4539 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4540 case ISD::SETULT: Swap = true;
4541 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4542 case ISD::SETULE: Swap = true;
4543 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4546 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4547 if (Opc == ARMISD::VCEQ) {
4550 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4552 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4555 // Ignore bitconvert.
4556 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4557 AndOp = AndOp.getOperand(0);
4559 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4561 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4562 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4569 std::swap(Op0, Op1);
4571 // If one of the operands is a constant vector zero, attempt to fold the
4572 // comparison to a specialized compare-against-zero form.
4574 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4576 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4577 if (Opc == ARMISD::VCGE)
4578 Opc = ARMISD::VCLEZ;
4579 else if (Opc == ARMISD::VCGT)
4580 Opc = ARMISD::VCLTZ;
4585 if (SingleOp.getNode()) {
4588 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4590 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4592 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4594 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4596 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4598 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4601 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4605 Result = DAG.getNOT(dl, Result, VT);
4610 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4611 /// valid vector constant for a NEON instruction with a "modified immediate"
4612 /// operand (e.g., VMOV). If so, return the encoded value.
4613 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4614 unsigned SplatBitSize, SelectionDAG &DAG,
4615 EVT &VT, bool is128Bits, NEONModImmType type) {
4616 unsigned OpCmode, Imm;
4618 // SplatBitSize is set to the smallest size that splats the vector, so a
4619 // zero vector will always have SplatBitSize == 8. However, NEON modified
4620 // immediate instructions others than VMOV do not support the 8-bit encoding
4621 // of a zero vector, and the default encoding of zero is supposed to be the
4626 switch (SplatBitSize) {
4628 if (type != VMOVModImm)
4630 // Any 1-byte value is OK. Op=0, Cmode=1110.
4631 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4634 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4638 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4639 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4640 if ((SplatBits & ~0xff) == 0) {
4641 // Value = 0x00nn: Op=x, Cmode=100x.
4646 if ((SplatBits & ~0xff00) == 0) {
4647 // Value = 0xnn00: Op=x, Cmode=101x.
4649 Imm = SplatBits >> 8;
4655 // NEON's 32-bit VMOV supports splat values where:
4656 // * only one byte is nonzero, or
4657 // * the least significant byte is 0xff and the second byte is nonzero, or
4658 // * the least significant 2 bytes are 0xff and the third is nonzero.
4659 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4660 if ((SplatBits & ~0xff) == 0) {
4661 // Value = 0x000000nn: Op=x, Cmode=000x.
4666 if ((SplatBits & ~0xff00) == 0) {
4667 // Value = 0x0000nn00: Op=x, Cmode=001x.
4669 Imm = SplatBits >> 8;
4672 if ((SplatBits & ~0xff0000) == 0) {
4673 // Value = 0x00nn0000: Op=x, Cmode=010x.
4675 Imm = SplatBits >> 16;
4678 if ((SplatBits & ~0xff000000) == 0) {
4679 // Value = 0xnn000000: Op=x, Cmode=011x.
4681 Imm = SplatBits >> 24;
4685 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4686 if (type == OtherModImm) return SDValue();
4688 if ((SplatBits & ~0xffff) == 0 &&
4689 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4690 // Value = 0x0000nnff: Op=x, Cmode=1100.
4692 Imm = SplatBits >> 8;
4696 if ((SplatBits & ~0xffffff) == 0 &&
4697 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4698 // Value = 0x00nnffff: Op=x, Cmode=1101.
4700 Imm = SplatBits >> 16;
4704 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4705 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4706 // VMOV.I32. A (very) minor optimization would be to replicate the value
4707 // and fall through here to test for a valid 64-bit splat. But, then the
4708 // caller would also need to check and handle the change in size.
4712 if (type != VMOVModImm)
4714 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4715 uint64_t BitMask = 0xff;
4717 unsigned ImmMask = 1;
4719 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4720 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4723 } else if ((SplatBits & BitMask) != 0) {
4730 if (DAG.getTargetLoweringInfo().isBigEndian())
4731 // swap higher and lower 32 bit word
4732 Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4734 // Op=1, Cmode=1110.
4736 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4741 llvm_unreachable("unexpected size for isNEONModifiedImm");
4744 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4745 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4748 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4749 const ARMSubtarget *ST) const {
4753 bool IsDouble = Op.getValueType() == MVT::f64;
4754 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4756 // Use the default (constant pool) lowering for double constants when we have
4758 if (IsDouble && Subtarget->isFPOnlySP())
4761 // Try splatting with a VMOV.f32...
4762 APFloat FPVal = CFP->getValueAPF();
4763 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4766 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4767 // We have code in place to select a valid ConstantFP already, no need to
4772 // It's a float and we are trying to use NEON operations where
4773 // possible. Lower it to a splat followed by an extract.
4775 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4776 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4778 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4779 DAG.getConstant(0, MVT::i32));
4782 // The rest of our options are NEON only, make sure that's allowed before
4784 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4788 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4790 // It wouldn't really be worth bothering for doubles except for one very
4791 // important value, which does happen to match: 0.0. So make sure we don't do
4793 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4796 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4797 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4799 if (NewVal != SDValue()) {
4801 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4804 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4806 // It's a float: cast and extract a vector element.
4807 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4809 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4810 DAG.getConstant(0, MVT::i32));
4813 // Finally, try a VMVN.i32
4814 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4816 if (NewVal != SDValue()) {
4818 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4821 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4823 // It's a float: cast and extract a vector element.
4824 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4826 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4827 DAG.getConstant(0, MVT::i32));
4833 // check if an VEXT instruction can handle the shuffle mask when the
4834 // vector sources of the shuffle are the same.
4835 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4836 unsigned NumElts = VT.getVectorNumElements();
4838 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4844 // If this is a VEXT shuffle, the immediate value is the index of the first
4845 // element. The other shuffle indices must be the successive elements after
4847 unsigned ExpectedElt = Imm;
4848 for (unsigned i = 1; i < NumElts; ++i) {
4849 // Increment the expected index. If it wraps around, just follow it
4850 // back to index zero and keep going.
4852 if (ExpectedElt == NumElts)
4855 if (M[i] < 0) continue; // ignore UNDEF indices
4856 if (ExpectedElt != static_cast<unsigned>(M[i]))
4864 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4865 bool &ReverseVEXT, unsigned &Imm) {
4866 unsigned NumElts = VT.getVectorNumElements();
4867 ReverseVEXT = false;
4869 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4875 // If this is a VEXT shuffle, the immediate value is the index of the first
4876 // element. The other shuffle indices must be the successive elements after
4878 unsigned ExpectedElt = Imm;
4879 for (unsigned i = 1; i < NumElts; ++i) {
4880 // Increment the expected index. If it wraps around, it may still be
4881 // a VEXT but the source vectors must be swapped.
4883 if (ExpectedElt == NumElts * 2) {
4888 if (M[i] < 0) continue; // ignore UNDEF indices
4889 if (ExpectedElt != static_cast<unsigned>(M[i]))
4893 // Adjust the index value if the source operands will be swapped.
4900 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4901 /// instruction with the specified blocksize. (The order of the elements
4902 /// within each block of the vector is reversed.)
4903 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4904 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4905 "Only possible block sizes for VREV are: 16, 32, 64");
4907 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4911 unsigned NumElts = VT.getVectorNumElements();
4912 unsigned BlockElts = M[0] + 1;
4913 // If the first shuffle index is UNDEF, be optimistic.
4915 BlockElts = BlockSize / EltSz;
4917 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4920 for (unsigned i = 0; i < NumElts; ++i) {
4921 if (M[i] < 0) continue; // ignore UNDEF indices
4922 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4929 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4930 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4931 // range, then 0 is placed into the resulting vector. So pretty much any mask
4932 // of 8 elements can work here.
4933 return VT == MVT::v8i8 && M.size() == 8;
4936 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4937 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4941 unsigned NumElts = VT.getVectorNumElements();
4942 WhichResult = (M[0] == 0 ? 0 : 1);
4943 for (unsigned i = 0; i < NumElts; i += 2) {
4944 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4945 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4951 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4952 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4953 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4954 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4955 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4959 unsigned NumElts = VT.getVectorNumElements();
4960 WhichResult = (M[0] == 0 ? 0 : 1);
4961 for (unsigned i = 0; i < NumElts; i += 2) {
4962 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4963 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4969 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4970 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4974 unsigned NumElts = VT.getVectorNumElements();
4975 WhichResult = (M[0] == 0 ? 0 : 1);
4976 for (unsigned i = 0; i != NumElts; ++i) {
4977 if (M[i] < 0) continue; // ignore UNDEF indices
4978 if ((unsigned) M[i] != 2 * i + WhichResult)
4982 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4983 if (VT.is64BitVector() && EltSz == 32)
4989 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4990 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4991 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4992 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4993 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4997 unsigned Half = VT.getVectorNumElements() / 2;
4998 WhichResult = (M[0] == 0 ? 0 : 1);
4999 for (unsigned j = 0; j != 2; ++j) {
5000 unsigned Idx = WhichResult;
5001 for (unsigned i = 0; i != Half; ++i) {
5002 int MIdx = M[i + j * Half];
5003 if (MIdx >= 0 && (unsigned) MIdx != Idx)
5009 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5010 if (VT.is64BitVector() && EltSz == 32)
5016 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5017 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5021 unsigned NumElts = VT.getVectorNumElements();
5022 WhichResult = (M[0] == 0 ? 0 : 1);
5023 unsigned Idx = WhichResult * NumElts / 2;
5024 for (unsigned i = 0; i != NumElts; i += 2) {
5025 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5026 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5031 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5032 if (VT.is64BitVector() && EltSz == 32)
5038 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5039 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5040 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5041 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5042 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5046 unsigned NumElts = VT.getVectorNumElements();
5047 WhichResult = (M[0] == 0 ? 0 : 1);
5048 unsigned Idx = WhichResult * NumElts / 2;
5049 for (unsigned i = 0; i != NumElts; i += 2) {
5050 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5051 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5056 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5057 if (VT.is64BitVector() && EltSz == 32)
5063 /// \return true if this is a reverse operation on an vector.
5064 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5065 unsigned NumElts = VT.getVectorNumElements();
5066 // Make sure the mask has the right size.
5067 if (NumElts != M.size())
5070 // Look for <15, ..., 3, -1, 1, 0>.
5071 for (unsigned i = 0; i != NumElts; ++i)
5072 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5078 // If N is an integer constant that can be moved into a register in one
5079 // instruction, return an SDValue of such a constant (will become a MOV
5080 // instruction). Otherwise return null.
5081 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5082 const ARMSubtarget *ST, SDLoc dl) {
5084 if (!isa<ConstantSDNode>(N))
5086 Val = cast<ConstantSDNode>(N)->getZExtValue();
5088 if (ST->isThumb1Only()) {
5089 if (Val <= 255 || ~Val <= 255)
5090 return DAG.getConstant(Val, MVT::i32);
5092 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5093 return DAG.getConstant(Val, MVT::i32);
5098 // If this is a case we can't handle, return null and let the default
5099 // expansion code take care of it.
5100 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5101 const ARMSubtarget *ST) const {
5102 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5104 EVT VT = Op.getValueType();
5106 APInt SplatBits, SplatUndef;
5107 unsigned SplatBitSize;
5109 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5110 if (SplatBitSize <= 64) {
5111 // Check if an immediate VMOV works.
5113 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5114 SplatUndef.getZExtValue(), SplatBitSize,
5115 DAG, VmovVT, VT.is128BitVector(),
5117 if (Val.getNode()) {
5118 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5119 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5122 // Try an immediate VMVN.
5123 uint64_t NegatedImm = (~SplatBits).getZExtValue();
5124 Val = isNEONModifiedImm(NegatedImm,
5125 SplatUndef.getZExtValue(), SplatBitSize,
5126 DAG, VmovVT, VT.is128BitVector(),
5128 if (Val.getNode()) {
5129 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5130 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5133 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5134 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5135 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5137 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5138 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5144 // Scan through the operands to see if only one value is used.
5146 // As an optimisation, even if more than one value is used it may be more
5147 // profitable to splat with one value then change some lanes.
5149 // Heuristically we decide to do this if the vector has a "dominant" value,
5150 // defined as splatted to more than half of the lanes.
5151 unsigned NumElts = VT.getVectorNumElements();
5152 bool isOnlyLowElement = true;
5153 bool usesOnlyOneValue = true;
5154 bool hasDominantValue = false;
5155 bool isConstant = true;
5157 // Map of the number of times a particular SDValue appears in the
5159 DenseMap<SDValue, unsigned> ValueCounts;
5161 for (unsigned i = 0; i < NumElts; ++i) {
5162 SDValue V = Op.getOperand(i);
5163 if (V.getOpcode() == ISD::UNDEF)
5166 isOnlyLowElement = false;
5167 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5170 ValueCounts.insert(std::make_pair(V, 0));
5171 unsigned &Count = ValueCounts[V];
5173 // Is this value dominant? (takes up more than half of the lanes)
5174 if (++Count > (NumElts / 2)) {
5175 hasDominantValue = true;
5179 if (ValueCounts.size() != 1)
5180 usesOnlyOneValue = false;
5181 if (!Value.getNode() && ValueCounts.size() > 0)
5182 Value = ValueCounts.begin()->first;
5184 if (ValueCounts.size() == 0)
5185 return DAG.getUNDEF(VT);
5187 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5188 // Keep going if we are hitting this case.
5189 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5190 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5192 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5194 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5195 // i32 and try again.
5196 if (hasDominantValue && EltSize <= 32) {
5200 // If we are VDUPing a value that comes directly from a vector, that will
5201 // cause an unnecessary move to and from a GPR, where instead we could
5202 // just use VDUPLANE. We can only do this if the lane being extracted
5203 // is at a constant index, as the VDUP from lane instructions only have
5204 // constant-index forms.
5205 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5206 isa<ConstantSDNode>(Value->getOperand(1))) {
5207 // We need to create a new undef vector to use for the VDUPLANE if the
5208 // size of the vector from which we get the value is different than the
5209 // size of the vector that we need to create. We will insert the element
5210 // such that the register coalescer will remove unnecessary copies.
5211 if (VT != Value->getOperand(0).getValueType()) {
5212 ConstantSDNode *constIndex;
5213 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5214 assert(constIndex && "The index is not a constant!");
5215 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5216 VT.getVectorNumElements();
5217 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5218 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5219 Value, DAG.getConstant(index, MVT::i32)),
5220 DAG.getConstant(index, MVT::i32));
5222 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5223 Value->getOperand(0), Value->getOperand(1));
5225 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5227 if (!usesOnlyOneValue) {
5228 // The dominant value was splatted as 'N', but we now have to insert
5229 // all differing elements.
5230 for (unsigned I = 0; I < NumElts; ++I) {
5231 if (Op.getOperand(I) == Value)
5233 SmallVector<SDValue, 3> Ops;
5235 Ops.push_back(Op.getOperand(I));
5236 Ops.push_back(DAG.getConstant(I, MVT::i32));
5237 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5242 if (VT.getVectorElementType().isFloatingPoint()) {
5243 SmallVector<SDValue, 8> Ops;
5244 for (unsigned i = 0; i < NumElts; ++i)
5245 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5247 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5248 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5249 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5251 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5253 if (usesOnlyOneValue) {
5254 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5255 if (isConstant && Val.getNode())
5256 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5260 // If all elements are constants and the case above didn't get hit, fall back
5261 // to the default expansion, which will generate a load from the constant
5266 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5268 SDValue shuffle = ReconstructShuffle(Op, DAG);
5269 if (shuffle != SDValue())
5273 // Vectors with 32- or 64-bit elements can be built by directly assigning
5274 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5275 // will be legalized.
5276 if (EltSize >= 32) {
5277 // Do the expansion with floating-point types, since that is what the VFP
5278 // registers are defined to use, and since i64 is not legal.
5279 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5280 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5281 SmallVector<SDValue, 8> Ops;
5282 for (unsigned i = 0; i < NumElts; ++i)
5283 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5284 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5285 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5288 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5289 // know the default expansion would otherwise fall back on something even
5290 // worse. For a vector with one or two non-undef values, that's
5291 // scalar_to_vector for the elements followed by a shuffle (provided the
5292 // shuffle is valid for the target) and materialization element by element
5293 // on the stack followed by a load for everything else.
5294 if (!isConstant && !usesOnlyOneValue) {
5295 SDValue Vec = DAG.getUNDEF(VT);
5296 for (unsigned i = 0 ; i < NumElts; ++i) {
5297 SDValue V = Op.getOperand(i);
5298 if (V.getOpcode() == ISD::UNDEF)
5300 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5301 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5309 // Gather data to see if the operation can be modelled as a
5310 // shuffle in combination with VEXTs.
5311 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5312 SelectionDAG &DAG) const {
5314 EVT VT = Op.getValueType();
5315 unsigned NumElts = VT.getVectorNumElements();
5317 SmallVector<SDValue, 2> SourceVecs;
5318 SmallVector<unsigned, 2> MinElts;
5319 SmallVector<unsigned, 2> MaxElts;
5321 for (unsigned i = 0; i < NumElts; ++i) {
5322 SDValue V = Op.getOperand(i);
5323 if (V.getOpcode() == ISD::UNDEF)
5325 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5326 // A shuffle can only come from building a vector from various
5327 // elements of other vectors.
5329 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5330 VT.getVectorElementType()) {
5331 // This code doesn't know how to handle shuffles where the vector
5332 // element types do not match (this happens because type legalization
5333 // promotes the return type of EXTRACT_VECTOR_ELT).
5334 // FIXME: It might be appropriate to extend this code to handle
5335 // mismatched types.
5339 // Record this extraction against the appropriate vector if possible...
5340 SDValue SourceVec = V.getOperand(0);
5341 // If the element number isn't a constant, we can't effectively
5342 // analyze what's going on.
5343 if (!isa<ConstantSDNode>(V.getOperand(1)))
5345 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5346 bool FoundSource = false;
5347 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5348 if (SourceVecs[j] == SourceVec) {
5349 if (MinElts[j] > EltNo)
5351 if (MaxElts[j] < EltNo)
5358 // Or record a new source if not...
5360 SourceVecs.push_back(SourceVec);
5361 MinElts.push_back(EltNo);
5362 MaxElts.push_back(EltNo);
5366 // Currently only do something sane when at most two source vectors
5368 if (SourceVecs.size() > 2)
5371 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5372 int VEXTOffsets[2] = {0, 0};
5374 // This loop extracts the usage patterns of the source vectors
5375 // and prepares appropriate SDValues for a shuffle if possible.
5376 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5377 if (SourceVecs[i].getValueType() == VT) {
5378 // No VEXT necessary
5379 ShuffleSrcs[i] = SourceVecs[i];
5382 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5383 // It probably isn't worth padding out a smaller vector just to
5384 // break it down again in a shuffle.
5388 // Since only 64-bit and 128-bit vectors are legal on ARM and
5389 // we've eliminated the other cases...
5390 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5391 "unexpected vector sizes in ReconstructShuffle");
5393 if (MaxElts[i] - MinElts[i] >= NumElts) {
5394 // Span too large for a VEXT to cope
5398 if (MinElts[i] >= NumElts) {
5399 // The extraction can just take the second half
5400 VEXTOffsets[i] = NumElts;
5401 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5403 DAG.getIntPtrConstant(NumElts));
5404 } else if (MaxElts[i] < NumElts) {
5405 // The extraction can just take the first half
5407 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5409 DAG.getIntPtrConstant(0));
5411 // An actual VEXT is needed
5412 VEXTOffsets[i] = MinElts[i];
5413 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5415 DAG.getIntPtrConstant(0));
5416 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5418 DAG.getIntPtrConstant(NumElts));
5419 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5420 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5424 SmallVector<int, 8> Mask;
5426 for (unsigned i = 0; i < NumElts; ++i) {
5427 SDValue Entry = Op.getOperand(i);
5428 if (Entry.getOpcode() == ISD::UNDEF) {
5433 SDValue ExtractVec = Entry.getOperand(0);
5434 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5435 .getOperand(1))->getSExtValue();
5436 if (ExtractVec == SourceVecs[0]) {
5437 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5439 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5443 // Final check before we try to produce nonsense...
5444 if (isShuffleMaskLegal(Mask, VT))
5445 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5451 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5452 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5453 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5454 /// are assumed to be legal.
5456 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5458 if (VT.getVectorNumElements() == 4 &&
5459 (VT.is128BitVector() || VT.is64BitVector())) {
5460 unsigned PFIndexes[4];
5461 for (unsigned i = 0; i != 4; ++i) {
5465 PFIndexes[i] = M[i];
5468 // Compute the index in the perfect shuffle table.
5469 unsigned PFTableIndex =
5470 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5471 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5472 unsigned Cost = (PFEntry >> 30);
5479 unsigned Imm, WhichResult;
5481 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5482 return (EltSize >= 32 ||
5483 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5484 isVREVMask(M, VT, 64) ||
5485 isVREVMask(M, VT, 32) ||
5486 isVREVMask(M, VT, 16) ||
5487 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5488 isVTBLMask(M, VT) ||
5489 isVTRNMask(M, VT, WhichResult) ||
5490 isVUZPMask(M, VT, WhichResult) ||
5491 isVZIPMask(M, VT, WhichResult) ||
5492 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5493 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5494 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5495 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5498 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5499 /// the specified operations to build the shuffle.
5500 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5501 SDValue RHS, SelectionDAG &DAG,
5503 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5504 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5505 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5508 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5517 OP_VUZPL, // VUZP, left result
5518 OP_VUZPR, // VUZP, right result
5519 OP_VZIPL, // VZIP, left result
5520 OP_VZIPR, // VZIP, right result
5521 OP_VTRNL, // VTRN, left result
5522 OP_VTRNR // VTRN, right result
5525 if (OpNum == OP_COPY) {
5526 if (LHSID == (1*9+2)*9+3) return LHS;
5527 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5531 SDValue OpLHS, OpRHS;
5532 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5533 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5534 EVT VT = OpLHS.getValueType();
5537 default: llvm_unreachable("Unknown shuffle opcode!");
5539 // VREV divides the vector in half and swaps within the half.
5540 if (VT.getVectorElementType() == MVT::i32 ||
5541 VT.getVectorElementType() == MVT::f32)
5542 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5543 // vrev <4 x i16> -> VREV32
5544 if (VT.getVectorElementType() == MVT::i16)
5545 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5546 // vrev <4 x i8> -> VREV16
5547 assert(VT.getVectorElementType() == MVT::i8);
5548 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5553 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5554 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5558 return DAG.getNode(ARMISD::VEXT, dl, VT,
5560 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5563 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5564 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5567 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5568 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5571 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5572 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5576 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5577 ArrayRef<int> ShuffleMask,
5578 SelectionDAG &DAG) {
5579 // Check to see if we can use the VTBL instruction.
5580 SDValue V1 = Op.getOperand(0);
5581 SDValue V2 = Op.getOperand(1);
5584 SmallVector<SDValue, 8> VTBLMask;
5585 for (ArrayRef<int>::iterator
5586 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5587 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5589 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5590 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5591 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5593 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5594 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5597 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5598 SelectionDAG &DAG) {
5600 SDValue OpLHS = Op.getOperand(0);
5601 EVT VT = OpLHS.getValueType();
5603 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5604 "Expect an v8i16/v16i8 type");
5605 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5606 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5607 // extract the first 8 bytes into the top double word and the last 8 bytes
5608 // into the bottom double word. The v8i16 case is similar.
5609 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5610 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5611 DAG.getConstant(ExtractNum, MVT::i32));
5614 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5615 SDValue V1 = Op.getOperand(0);
5616 SDValue V2 = Op.getOperand(1);
5618 EVT VT = Op.getValueType();
5619 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5621 // Convert shuffles that are directly supported on NEON to target-specific
5622 // DAG nodes, instead of keeping them as shuffles and matching them again
5623 // during code selection. This is more efficient and avoids the possibility
5624 // of inconsistencies between legalization and selection.
5625 // FIXME: floating-point vectors should be canonicalized to integer vectors
5626 // of the same time so that they get CSEd properly.
5627 ArrayRef<int> ShuffleMask = SVN->getMask();
5629 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5630 if (EltSize <= 32) {
5631 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5632 int Lane = SVN->getSplatIndex();
5633 // If this is undef splat, generate it via "just" vdup, if possible.
5634 if (Lane == -1) Lane = 0;
5636 // Test if V1 is a SCALAR_TO_VECTOR.
5637 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5638 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5640 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5641 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5643 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5644 !isa<ConstantSDNode>(V1.getOperand(0))) {
5645 bool IsScalarToVector = true;
5646 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5647 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5648 IsScalarToVector = false;
5651 if (IsScalarToVector)
5652 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5654 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5655 DAG.getConstant(Lane, MVT::i32));
5660 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5663 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5664 DAG.getConstant(Imm, MVT::i32));
5667 if (isVREVMask(ShuffleMask, VT, 64))
5668 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5669 if (isVREVMask(ShuffleMask, VT, 32))
5670 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5671 if (isVREVMask(ShuffleMask, VT, 16))
5672 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5674 if (V2->getOpcode() == ISD::UNDEF &&
5675 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5676 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5677 DAG.getConstant(Imm, MVT::i32));
5680 // Check for Neon shuffles that modify both input vectors in place.
5681 // If both results are used, i.e., if there are two shuffles with the same
5682 // source operands and with masks corresponding to both results of one of
5683 // these operations, DAG memoization will ensure that a single node is
5684 // used for both shuffles.
5685 unsigned WhichResult;
5686 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5687 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5688 V1, V2).getValue(WhichResult);
5689 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5690 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5691 V1, V2).getValue(WhichResult);
5692 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5693 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5694 V1, V2).getValue(WhichResult);
5696 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5697 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5698 V1, V1).getValue(WhichResult);
5699 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5700 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5701 V1, V1).getValue(WhichResult);
5702 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5703 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5704 V1, V1).getValue(WhichResult);
5707 // If the shuffle is not directly supported and it has 4 elements, use
5708 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5709 unsigned NumElts = VT.getVectorNumElements();
5711 unsigned PFIndexes[4];
5712 for (unsigned i = 0; i != 4; ++i) {
5713 if (ShuffleMask[i] < 0)
5716 PFIndexes[i] = ShuffleMask[i];
5719 // Compute the index in the perfect shuffle table.
5720 unsigned PFTableIndex =
5721 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5722 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5723 unsigned Cost = (PFEntry >> 30);
5726 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5729 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5730 if (EltSize >= 32) {
5731 // Do the expansion with floating-point types, since that is what the VFP
5732 // registers are defined to use, and since i64 is not legal.
5733 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5734 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5735 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5736 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5737 SmallVector<SDValue, 8> Ops;
5738 for (unsigned i = 0; i < NumElts; ++i) {
5739 if (ShuffleMask[i] < 0)
5740 Ops.push_back(DAG.getUNDEF(EltVT));
5742 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5743 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5744 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5747 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5748 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5751 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5752 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5754 if (VT == MVT::v8i8) {
5755 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5756 if (NewOp.getNode())
5763 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5764 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5765 SDValue Lane = Op.getOperand(2);
5766 if (!isa<ConstantSDNode>(Lane))
5772 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5773 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5774 SDValue Lane = Op.getOperand(1);
5775 if (!isa<ConstantSDNode>(Lane))
5778 SDValue Vec = Op.getOperand(0);
5779 if (Op.getValueType() == MVT::i32 &&
5780 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5782 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5788 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5789 // The only time a CONCAT_VECTORS operation can have legal types is when
5790 // two 64-bit vectors are concatenated to a 128-bit vector.
5791 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5792 "unexpected CONCAT_VECTORS");
5794 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5795 SDValue Op0 = Op.getOperand(0);
5796 SDValue Op1 = Op.getOperand(1);
5797 if (Op0.getOpcode() != ISD::UNDEF)
5798 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5799 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5800 DAG.getIntPtrConstant(0));
5801 if (Op1.getOpcode() != ISD::UNDEF)
5802 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5803 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5804 DAG.getIntPtrConstant(1));
5805 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5808 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5809 /// element has been zero/sign-extended, depending on the isSigned parameter,
5810 /// from an integer type half its size.
5811 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5813 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5814 EVT VT = N->getValueType(0);
5815 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5816 SDNode *BVN = N->getOperand(0).getNode();
5817 if (BVN->getValueType(0) != MVT::v4i32 ||
5818 BVN->getOpcode() != ISD::BUILD_VECTOR)
5820 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5821 unsigned HiElt = 1 - LoElt;
5822 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5823 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5824 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5825 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5826 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5829 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5830 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5833 if (Hi0->isNullValue() && Hi1->isNullValue())
5839 if (N->getOpcode() != ISD::BUILD_VECTOR)
5842 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5843 SDNode *Elt = N->getOperand(i).getNode();
5844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5845 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5846 unsigned HalfSize = EltSize / 2;
5848 if (!isIntN(HalfSize, C->getSExtValue()))
5851 if (!isUIntN(HalfSize, C->getZExtValue()))
5862 /// isSignExtended - Check if a node is a vector value that is sign-extended
5863 /// or a constant BUILD_VECTOR with sign-extended elements.
5864 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5865 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5867 if (isExtendedBUILD_VECTOR(N, DAG, true))
5872 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5873 /// or a constant BUILD_VECTOR with zero-extended elements.
5874 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5875 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5877 if (isExtendedBUILD_VECTOR(N, DAG, false))
5882 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5883 if (OrigVT.getSizeInBits() >= 64)
5886 assert(OrigVT.isSimple() && "Expecting a simple value type");
5888 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5889 switch (OrigSimpleTy) {
5890 default: llvm_unreachable("Unexpected Vector Type");
5899 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5900 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5901 /// We insert the required extension here to get the vector to fill a D register.
5902 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5905 unsigned ExtOpcode) {
5906 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5907 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5908 // 64-bits we need to insert a new extension so that it will be 64-bits.
5909 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5910 if (OrigTy.getSizeInBits() >= 64)
5913 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5914 EVT NewVT = getExtensionTo64Bits(OrigTy);
5916 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5919 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5920 /// does not do any sign/zero extension. If the original vector is less
5921 /// than 64 bits, an appropriate extension will be added after the load to
5922 /// reach a total size of 64 bits. We have to add the extension separately
5923 /// because ARM does not have a sign/zero extending load for vectors.
5924 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5925 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5927 // The load already has the right type.
5928 if (ExtendedTy == LD->getMemoryVT())
5929 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5930 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5931 LD->isNonTemporal(), LD->isInvariant(),
5932 LD->getAlignment());
5934 // We need to create a zextload/sextload. We cannot just create a load
5935 // followed by a zext/zext node because LowerMUL is also run during normal
5936 // operation legalization where we can't create illegal types.
5937 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5938 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5939 LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5940 LD->isNonTemporal(), LD->getAlignment());
5943 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5944 /// extending load, or BUILD_VECTOR with extended elements, return the
5945 /// unextended value. The unextended vector should be 64 bits so that it can
5946 /// be used as an operand to a VMULL instruction. If the original vector size
5947 /// before extension is less than 64 bits we add a an extension to resize
5948 /// the vector to 64 bits.
5949 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5950 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5951 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5952 N->getOperand(0)->getValueType(0),
5956 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5957 return SkipLoadExtensionForVMULL(LD, DAG);
5959 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5960 // have been legalized as a BITCAST from v4i32.
5961 if (N->getOpcode() == ISD::BITCAST) {
5962 SDNode *BVN = N->getOperand(0).getNode();
5963 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5964 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5965 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5966 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5967 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5969 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5970 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5971 EVT VT = N->getValueType(0);
5972 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5973 unsigned NumElts = VT.getVectorNumElements();
5974 MVT TruncVT = MVT::getIntegerVT(EltSize);
5975 SmallVector<SDValue, 8> Ops;
5976 for (unsigned i = 0; i != NumElts; ++i) {
5977 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5978 const APInt &CInt = C->getAPIntValue();
5979 // Element types smaller than 32 bits are not legal, so use i32 elements.
5980 // The values are implicitly truncated so sext vs. zext doesn't matter.
5981 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5983 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5984 MVT::getVectorVT(TruncVT, NumElts), Ops);
5987 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5988 unsigned Opcode = N->getOpcode();
5989 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5990 SDNode *N0 = N->getOperand(0).getNode();
5991 SDNode *N1 = N->getOperand(1).getNode();
5992 return N0->hasOneUse() && N1->hasOneUse() &&
5993 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5998 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5999 unsigned Opcode = N->getOpcode();
6000 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6001 SDNode *N0 = N->getOperand(0).getNode();
6002 SDNode *N1 = N->getOperand(1).getNode();
6003 return N0->hasOneUse() && N1->hasOneUse() &&
6004 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6009 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6010 // Multiplications are only custom-lowered for 128-bit vectors so that
6011 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
6012 EVT VT = Op.getValueType();
6013 assert(VT.is128BitVector() && VT.isInteger() &&
6014 "unexpected type for custom-lowering ISD::MUL");
6015 SDNode *N0 = Op.getOperand(0).getNode();
6016 SDNode *N1 = Op.getOperand(1).getNode();
6017 unsigned NewOpc = 0;
6019 bool isN0SExt = isSignExtended(N0, DAG);
6020 bool isN1SExt = isSignExtended(N1, DAG);
6021 if (isN0SExt && isN1SExt)
6022 NewOpc = ARMISD::VMULLs;
6024 bool isN0ZExt = isZeroExtended(N0, DAG);
6025 bool isN1ZExt = isZeroExtended(N1, DAG);
6026 if (isN0ZExt && isN1ZExt)
6027 NewOpc = ARMISD::VMULLu;
6028 else if (isN1SExt || isN1ZExt) {
6029 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6030 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6031 if (isN1SExt && isAddSubSExt(N0, DAG)) {
6032 NewOpc = ARMISD::VMULLs;
6034 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6035 NewOpc = ARMISD::VMULLu;
6037 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6039 NewOpc = ARMISD::VMULLu;
6045 if (VT == MVT::v2i64)
6046 // Fall through to expand this. It is not legal.
6049 // Other vector multiplications are legal.
6054 // Legalize to a VMULL instruction.
6057 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6059 Op0 = SkipExtensionForVMULL(N0, DAG);
6060 assert(Op0.getValueType().is64BitVector() &&
6061 Op1.getValueType().is64BitVector() &&
6062 "unexpected types for extended operands to VMULL");
6063 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6066 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6067 // isel lowering to take advantage of no-stall back to back vmul + vmla.
6074 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6075 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6076 EVT Op1VT = Op1.getValueType();
6077 return DAG.getNode(N0->getOpcode(), DL, VT,
6078 DAG.getNode(NewOpc, DL, VT,
6079 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6080 DAG.getNode(NewOpc, DL, VT,
6081 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6085 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6087 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6088 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6089 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6090 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6091 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6092 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6093 // Get reciprocal estimate.
6094 // float4 recip = vrecpeq_f32(yf);
6095 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6096 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6097 // Because char has a smaller range than uchar, we can actually get away
6098 // without any newton steps. This requires that we use a weird bias
6099 // of 0xb000, however (again, this has been exhaustively tested).
6100 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6101 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6102 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6103 Y = DAG.getConstant(0xb000, MVT::i32);
6104 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6105 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6106 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6107 // Convert back to short.
6108 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6109 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6114 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6116 // Convert to float.
6117 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6118 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6119 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6120 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6121 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6122 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6124 // Use reciprocal estimate and one refinement step.
6125 // float4 recip = vrecpeq_f32(yf);
6126 // recip *= vrecpsq_f32(yf, recip);
6127 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6128 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6129 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6130 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6132 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6133 // Because short has a smaller range than ushort, we can actually get away
6134 // with only a single newton step. This requires that we use a weird bias
6135 // of 89, however (again, this has been exhaustively tested).
6136 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6137 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6138 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6139 N1 = DAG.getConstant(0x89, MVT::i32);
6140 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6141 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6142 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6143 // Convert back to integer and return.
6144 // return vmovn_s32(vcvt_s32_f32(result));
6145 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6146 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6150 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6151 EVT VT = Op.getValueType();
6152 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6153 "unexpected type for custom-lowering ISD::SDIV");
6156 SDValue N0 = Op.getOperand(0);
6157 SDValue N1 = Op.getOperand(1);
6160 if (VT == MVT::v8i8) {
6161 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6162 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6164 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6165 DAG.getIntPtrConstant(4));
6166 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6167 DAG.getIntPtrConstant(4));
6168 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6169 DAG.getIntPtrConstant(0));
6170 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6171 DAG.getIntPtrConstant(0));
6173 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6174 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6176 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6177 N0 = LowerCONCAT_VECTORS(N0, DAG);
6179 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6182 return LowerSDIV_v4i16(N0, N1, dl, DAG);
6185 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6186 EVT VT = Op.getValueType();
6187 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6188 "unexpected type for custom-lowering ISD::UDIV");
6191 SDValue N0 = Op.getOperand(0);
6192 SDValue N1 = Op.getOperand(1);
6195 if (VT == MVT::v8i8) {
6196 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6197 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6199 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6200 DAG.getIntPtrConstant(4));
6201 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6202 DAG.getIntPtrConstant(4));
6203 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6204 DAG.getIntPtrConstant(0));
6205 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6206 DAG.getIntPtrConstant(0));
6208 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6209 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6211 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6212 N0 = LowerCONCAT_VECTORS(N0, DAG);
6214 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6215 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6220 // v4i16 sdiv ... Convert to float.
6221 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6222 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6223 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6224 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6225 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6226 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6228 // Use reciprocal estimate and two refinement steps.
6229 // float4 recip = vrecpeq_f32(yf);
6230 // recip *= vrecpsq_f32(yf, recip);
6231 // recip *= vrecpsq_f32(yf, recip);
6232 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6233 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6234 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6235 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6237 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6238 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6239 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6241 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6242 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6243 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6244 // and that it will never cause us to return an answer too large).
6245 // float4 result = as_float4(as_int4(xf*recip) + 2);
6246 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6247 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6248 N1 = DAG.getConstant(2, MVT::i32);
6249 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6250 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6251 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6252 // Convert back to integer and return.
6253 // return vmovn_u32(vcvt_s32_f32(result));
6254 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6255 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6259 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6260 EVT VT = Op.getNode()->getValueType(0);
6261 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6264 bool ExtraOp = false;
6265 switch (Op.getOpcode()) {
6266 default: llvm_unreachable("Invalid code");
6267 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6268 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6269 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6270 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6274 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6276 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6277 Op.getOperand(1), Op.getOperand(2));
6280 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6281 assert(Subtarget->isTargetDarwin());
6283 // For iOS, we want to call an alternative entry point: __sincos_stret,
6284 // return values are passed via sret.
6286 SDValue Arg = Op.getOperand(0);
6287 EVT ArgVT = Arg.getValueType();
6288 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6290 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6293 // Pair of floats / doubles used to pass the result.
6294 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6296 // Create stack object for sret.
6297 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6298 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6299 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6300 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6306 Entry.Ty = RetTy->getPointerTo();
6307 Entry.isSExt = false;
6308 Entry.isZExt = false;
6309 Entry.isSRet = true;
6310 Args.push_back(Entry);
6314 Entry.isSExt = false;
6315 Entry.isZExt = false;
6316 Args.push_back(Entry);
6318 const char *LibcallName = (ArgVT == MVT::f64)
6319 ? "__sincos_stret" : "__sincosf_stret";
6320 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6322 TargetLowering::CallLoweringInfo CLI(DAG);
6323 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6324 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6326 .setDiscardResult();
6328 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6330 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6331 MachinePointerInfo(), false, false, false, 0);
6333 // Address of cos field.
6334 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6335 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6336 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6337 MachinePointerInfo(), false, false, false, 0);
6339 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6340 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6341 LoadSin.getValue(0), LoadCos.getValue(0));
6344 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6345 // Monotonic load/store is legal for all targets
6346 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6349 // Acquire/Release load/store is not legal for targets without a
6350 // dmb or equivalent available.
6354 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6355 SmallVectorImpl<SDValue> &Results,
6357 const ARMSubtarget *Subtarget) {
6359 SDValue Cycles32, OutChain;
6361 if (Subtarget->hasPerfMon()) {
6362 // Under Power Management extensions, the cycle-count is:
6363 // mrc p15, #0, <Rt>, c9, c13, #0
6364 SDValue Ops[] = { N->getOperand(0), // Chain
6365 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6366 DAG.getConstant(15, MVT::i32),
6367 DAG.getConstant(0, MVT::i32),
6368 DAG.getConstant(9, MVT::i32),
6369 DAG.getConstant(13, MVT::i32),
6370 DAG.getConstant(0, MVT::i32)
6373 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6374 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6375 OutChain = Cycles32.getValue(1);
6377 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6378 // there are older ARM CPUs that have implementation-specific ways of
6379 // obtaining this information (FIXME!).
6380 Cycles32 = DAG.getConstant(0, MVT::i32);
6381 OutChain = DAG.getEntryNode();
6385 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6386 Cycles32, DAG.getConstant(0, MVT::i32));
6387 Results.push_back(Cycles64);
6388 Results.push_back(OutChain);
6391 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6392 switch (Op.getOpcode()) {
6393 default: llvm_unreachable("Don't know how to custom lower this!");
6394 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6395 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6396 case ISD::GlobalAddress:
6397 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6398 default: llvm_unreachable("unknown object format");
6400 return LowerGlobalAddressWindows(Op, DAG);
6402 return LowerGlobalAddressELF(Op, DAG);
6404 return LowerGlobalAddressDarwin(Op, DAG);
6406 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6407 case ISD::SELECT: return LowerSELECT(Op, DAG);
6408 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6409 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6410 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6411 case ISD::VASTART: return LowerVASTART(Op, DAG);
6412 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6413 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6414 case ISD::SINT_TO_FP:
6415 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6416 case ISD::FP_TO_SINT:
6417 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6418 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6419 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6420 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6421 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6422 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6423 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6424 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6426 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6429 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6430 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6431 case ISD::SRL_PARTS:
6432 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6433 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6434 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6435 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6436 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6437 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6438 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6439 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6440 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6441 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6442 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6443 case ISD::MUL: return LowerMUL(Op, DAG);
6444 case ISD::SDIV: return LowerSDIV(Op, DAG);
6445 case ISD::UDIV: return LowerUDIV(Op, DAG);
6449 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6454 return LowerXALUO(Op, DAG);
6455 case ISD::ATOMIC_LOAD:
6456 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6457 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6459 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6460 case ISD::DYNAMIC_STACKALLOC:
6461 if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6462 return LowerDYNAMIC_STACKALLOC(Op, DAG);
6463 llvm_unreachable("Don't know how to custom lower this!");
6464 case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6465 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6469 /// ReplaceNodeResults - Replace the results of node with an illegal result
6470 /// type with new values built out of custom code.
6471 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6472 SmallVectorImpl<SDValue>&Results,
6473 SelectionDAG &DAG) const {
6475 switch (N->getOpcode()) {
6477 llvm_unreachable("Don't know how to custom expand this!");
6479 Res = ExpandBITCAST(N, DAG);
6483 Res = Expand64BitShift(N, DAG, Subtarget);
6485 case ISD::READCYCLECOUNTER:
6486 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6490 Results.push_back(Res);
6493 //===----------------------------------------------------------------------===//
6494 // ARM Scheduler Hooks
6495 //===----------------------------------------------------------------------===//
6497 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6498 /// registers the function context.
6499 void ARMTargetLowering::
6500 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6501 MachineBasicBlock *DispatchBB, int FI) const {
6502 const TargetInstrInfo *TII =
6503 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6504 DebugLoc dl = MI->getDebugLoc();
6505 MachineFunction *MF = MBB->getParent();
6506 MachineRegisterInfo *MRI = &MF->getRegInfo();
6507 MachineConstantPool *MCP = MF->getConstantPool();
6508 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6509 const Function *F = MF->getFunction();
6511 bool isThumb = Subtarget->isThumb();
6512 bool isThumb2 = Subtarget->isThumb2();
6514 unsigned PCLabelId = AFI->createPICLabelUId();
6515 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6516 ARMConstantPoolValue *CPV =
6517 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6518 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6520 const TargetRegisterClass *TRC = isThumb ?
6521 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6522 (const TargetRegisterClass*)&ARM::GPRRegClass;
6524 // Grab constant pool and fixed stack memory operands.
6525 MachineMemOperand *CPMMO =
6526 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6527 MachineMemOperand::MOLoad, 4, 4);
6529 MachineMemOperand *FIMMOSt =
6530 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6531 MachineMemOperand::MOStore, 4, 4);
6533 // Load the address of the dispatch MBB into the jump buffer.
6535 // Incoming value: jbuf
6536 // ldr.n r5, LCPI1_1
6539 // str r5, [$jbuf, #+4] ; &jbuf[1]
6540 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6541 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6542 .addConstantPoolIndex(CPI)
6543 .addMemOperand(CPMMO));
6544 // Set the low bit because of thumb mode.
6545 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6547 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6548 .addReg(NewVReg1, RegState::Kill)
6550 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6551 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6552 .addReg(NewVReg2, RegState::Kill)
6554 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6555 .addReg(NewVReg3, RegState::Kill)
6557 .addImm(36) // &jbuf[1] :: pc
6558 .addMemOperand(FIMMOSt));
6559 } else if (isThumb) {
6560 // Incoming value: jbuf
6561 // ldr.n r1, LCPI1_4
6565 // add r2, $jbuf, #+4 ; &jbuf[1]
6567 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6568 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6569 .addConstantPoolIndex(CPI)
6570 .addMemOperand(CPMMO));
6571 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6572 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6573 .addReg(NewVReg1, RegState::Kill)
6575 // Set the low bit because of thumb mode.
6576 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6577 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6578 .addReg(ARM::CPSR, RegState::Define)
6580 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6581 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6582 .addReg(ARM::CPSR, RegState::Define)
6583 .addReg(NewVReg2, RegState::Kill)
6584 .addReg(NewVReg3, RegState::Kill));
6585 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6586 BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6588 .addImm(36); // &jbuf[1] :: pc
6589 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6590 .addReg(NewVReg4, RegState::Kill)
6591 .addReg(NewVReg5, RegState::Kill)
6593 .addMemOperand(FIMMOSt));
6595 // Incoming value: jbuf
6598 // str r1, [$jbuf, #+4] ; &jbuf[1]
6599 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6600 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6601 .addConstantPoolIndex(CPI)
6603 .addMemOperand(CPMMO));
6604 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6605 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6606 .addReg(NewVReg1, RegState::Kill)
6607 .addImm(PCLabelId));
6608 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6609 .addReg(NewVReg2, RegState::Kill)
6611 .addImm(36) // &jbuf[1] :: pc
6612 .addMemOperand(FIMMOSt));
6616 MachineBasicBlock *ARMTargetLowering::
6617 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6618 const TargetInstrInfo *TII =
6619 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6620 DebugLoc dl = MI->getDebugLoc();
6621 MachineFunction *MF = MBB->getParent();
6622 MachineRegisterInfo *MRI = &MF->getRegInfo();
6623 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6624 MachineFrameInfo *MFI = MF->getFrameInfo();
6625 int FI = MFI->getFunctionContextIndex();
6627 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6628 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6629 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6631 // Get a mapping of the call site numbers to all of the landing pads they're
6633 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6634 unsigned MaxCSNum = 0;
6635 MachineModuleInfo &MMI = MF->getMMI();
6636 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6638 if (!BB->isLandingPad()) continue;
6640 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6642 for (MachineBasicBlock::iterator
6643 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6644 if (!II->isEHLabel()) continue;
6646 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6647 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6649 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6650 for (SmallVectorImpl<unsigned>::iterator
6651 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6652 CSI != CSE; ++CSI) {
6653 CallSiteNumToLPad[*CSI].push_back(BB);
6654 MaxCSNum = std::max(MaxCSNum, *CSI);
6660 // Get an ordered list of the machine basic blocks for the jump table.
6661 std::vector<MachineBasicBlock*> LPadList;
6662 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6663 LPadList.reserve(CallSiteNumToLPad.size());
6664 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6665 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6666 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6667 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6668 LPadList.push_back(*II);
6669 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6673 assert(!LPadList.empty() &&
6674 "No landing pad destinations for the dispatch jump table!");
6676 // Create the jump table and associated information.
6677 MachineJumpTableInfo *JTI =
6678 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6679 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6680 unsigned UId = AFI->createJumpTableUId();
6681 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6683 // Create the MBBs for the dispatch code.
6685 // Shove the dispatch's address into the return slot in the function context.
6686 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6687 DispatchBB->setIsLandingPad();
6689 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6690 unsigned trap_opcode;
6691 if (Subtarget->isThumb())
6692 trap_opcode = ARM::tTRAP;
6694 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6696 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6697 DispatchBB->addSuccessor(TrapBB);
6699 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6700 DispatchBB->addSuccessor(DispContBB);
6703 MF->insert(MF->end(), DispatchBB);
6704 MF->insert(MF->end(), DispContBB);
6705 MF->insert(MF->end(), TrapBB);
6707 // Insert code into the entry block that creates and registers the function
6709 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6711 MachineMemOperand *FIMMOLd =
6712 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6713 MachineMemOperand::MOLoad |
6714 MachineMemOperand::MOVolatile, 4, 4);
6716 MachineInstrBuilder MIB;
6717 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6719 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6720 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6722 // Add a register mask with no preserved registers. This results in all
6723 // registers being marked as clobbered.
6724 MIB.addRegMask(RI.getNoPreservedMask());
6726 unsigned NumLPads = LPadList.size();
6727 if (Subtarget->isThumb2()) {
6728 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6729 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6732 .addMemOperand(FIMMOLd));
6734 if (NumLPads < 256) {
6735 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6737 .addImm(LPadList.size()));
6739 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6740 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6741 .addImm(NumLPads & 0xFFFF));
6743 unsigned VReg2 = VReg1;
6744 if ((NumLPads & 0xFFFF0000) != 0) {
6745 VReg2 = MRI->createVirtualRegister(TRC);
6746 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6748 .addImm(NumLPads >> 16));
6751 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6756 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6761 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6762 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6763 .addJumpTableIndex(MJTI)
6766 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6769 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6770 .addReg(NewVReg3, RegState::Kill)
6772 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6774 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6775 .addReg(NewVReg4, RegState::Kill)
6777 .addJumpTableIndex(MJTI)
6779 } else if (Subtarget->isThumb()) {
6780 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6781 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6784 .addMemOperand(FIMMOLd));
6786 if (NumLPads < 256) {
6787 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6791 MachineConstantPool *ConstantPool = MF->getConstantPool();
6792 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6793 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6795 // MachineConstantPool wants an explicit alignment.
6796 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6798 Align = getDataLayout()->getTypeAllocSize(C->getType());
6799 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6801 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6802 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6803 .addReg(VReg1, RegState::Define)
6804 .addConstantPoolIndex(Idx));
6805 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6810 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6815 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6816 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6817 .addReg(ARM::CPSR, RegState::Define)
6821 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6822 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6823 .addJumpTableIndex(MJTI)
6826 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6827 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6828 .addReg(ARM::CPSR, RegState::Define)
6829 .addReg(NewVReg2, RegState::Kill)
6832 MachineMemOperand *JTMMOLd =
6833 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6834 MachineMemOperand::MOLoad, 4, 4);
6836 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6837 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6838 .addReg(NewVReg4, RegState::Kill)
6840 .addMemOperand(JTMMOLd));
6842 unsigned NewVReg6 = NewVReg5;
6843 if (RelocM == Reloc::PIC_) {
6844 NewVReg6 = MRI->createVirtualRegister(TRC);
6845 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6846 .addReg(ARM::CPSR, RegState::Define)
6847 .addReg(NewVReg5, RegState::Kill)
6851 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6852 .addReg(NewVReg6, RegState::Kill)
6853 .addJumpTableIndex(MJTI)
6856 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6857 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6860 .addMemOperand(FIMMOLd));
6862 if (NumLPads < 256) {
6863 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6866 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6867 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6868 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6869 .addImm(NumLPads & 0xFFFF));
6871 unsigned VReg2 = VReg1;
6872 if ((NumLPads & 0xFFFF0000) != 0) {
6873 VReg2 = MRI->createVirtualRegister(TRC);
6874 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6876 .addImm(NumLPads >> 16));
6879 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6883 MachineConstantPool *ConstantPool = MF->getConstantPool();
6884 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6885 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6887 // MachineConstantPool wants an explicit alignment.
6888 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6890 Align = getDataLayout()->getTypeAllocSize(C->getType());
6891 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6893 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6894 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6895 .addReg(VReg1, RegState::Define)
6896 .addConstantPoolIndex(Idx)
6898 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6900 .addReg(VReg1, RegState::Kill));
6903 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6908 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6910 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6912 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6913 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6914 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6915 .addJumpTableIndex(MJTI)
6918 MachineMemOperand *JTMMOLd =
6919 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6920 MachineMemOperand::MOLoad, 4, 4);
6921 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6923 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6924 .addReg(NewVReg3, RegState::Kill)
6927 .addMemOperand(JTMMOLd));
6929 if (RelocM == Reloc::PIC_) {
6930 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6931 .addReg(NewVReg5, RegState::Kill)
6933 .addJumpTableIndex(MJTI)
6936 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6937 .addReg(NewVReg5, RegState::Kill)
6938 .addJumpTableIndex(MJTI)
6943 // Add the jump table entries as successors to the MBB.
6944 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6945 for (std::vector<MachineBasicBlock*>::iterator
6946 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6947 MachineBasicBlock *CurMBB = *I;
6948 if (SeenMBBs.insert(CurMBB))
6949 DispContBB->addSuccessor(CurMBB);
6952 // N.B. the order the invoke BBs are processed in doesn't matter here.
6953 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6954 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6955 for (MachineBasicBlock *BB : InvokeBBs) {
6957 // Remove the landing pad successor from the invoke block and replace it
6958 // with the new dispatch block.
6959 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6961 while (!Successors.empty()) {
6962 MachineBasicBlock *SMBB = Successors.pop_back_val();
6963 if (SMBB->isLandingPad()) {
6964 BB->removeSuccessor(SMBB);
6965 MBBLPads.push_back(SMBB);
6969 BB->addSuccessor(DispatchBB);
6971 // Find the invoke call and mark all of the callee-saved registers as
6972 // 'implicit defined' so that they're spilled. This prevents code from
6973 // moving instructions to before the EH block, where they will never be
6975 for (MachineBasicBlock::reverse_iterator
6976 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6977 if (!II->isCall()) continue;
6979 DenseMap<unsigned, bool> DefRegs;
6980 for (MachineInstr::mop_iterator
6981 OI = II->operands_begin(), OE = II->operands_end();
6983 if (!OI->isReg()) continue;
6984 DefRegs[OI->getReg()] = true;
6987 MachineInstrBuilder MIB(*MF, &*II);
6989 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6990 unsigned Reg = SavedRegs[i];
6991 if (Subtarget->isThumb2() &&
6992 !ARM::tGPRRegClass.contains(Reg) &&
6993 !ARM::hGPRRegClass.contains(Reg))
6995 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6997 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7000 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7007 // Mark all former landing pads as non-landing pads. The dispatch is the only
7009 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7010 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7011 (*I)->setIsLandingPad(false);
7013 // The instruction is gone now.
7014 MI->eraseFromParent();
7020 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7021 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7022 E = MBB->succ_end(); I != E; ++I)
7025 llvm_unreachable("Expecting a BB with two successors!");
7028 /// Return the load opcode for a given load size. If load size >= 8,
7029 /// neon opcode will be returned.
7030 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7032 return LdSize == 16 ? ARM::VLD1q32wb_fixed
7033 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7035 return LdSize == 4 ? ARM::tLDRi
7036 : LdSize == 2 ? ARM::tLDRHi
7037 : LdSize == 1 ? ARM::tLDRBi : 0;
7039 return LdSize == 4 ? ARM::t2LDR_POST
7040 : LdSize == 2 ? ARM::t2LDRH_POST
7041 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7042 return LdSize == 4 ? ARM::LDR_POST_IMM
7043 : LdSize == 2 ? ARM::LDRH_POST
7044 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7047 /// Return the store opcode for a given store size. If store size >= 8,
7048 /// neon opcode will be returned.
7049 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7051 return StSize == 16 ? ARM::VST1q32wb_fixed
7052 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7054 return StSize == 4 ? ARM::tSTRi
7055 : StSize == 2 ? ARM::tSTRHi
7056 : StSize == 1 ? ARM::tSTRBi : 0;
7058 return StSize == 4 ? ARM::t2STR_POST
7059 : StSize == 2 ? ARM::t2STRH_POST
7060 : StSize == 1 ? ARM::t2STRB_POST : 0;
7061 return StSize == 4 ? ARM::STR_POST_IMM
7062 : StSize == 2 ? ARM::STRH_POST
7063 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7066 /// Emit a post-increment load operation with given size. The instructions
7067 /// will be added to BB at Pos.
7068 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7069 const TargetInstrInfo *TII, DebugLoc dl,
7070 unsigned LdSize, unsigned Data, unsigned AddrIn,
7071 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7072 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7073 assert(LdOpc != 0 && "Should have a load opcode");
7075 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7076 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7078 } else if (IsThumb1) {
7079 // load + update AddrIn
7080 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7081 .addReg(AddrIn).addImm(0));
7082 MachineInstrBuilder MIB =
7083 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7084 MIB = AddDefaultT1CC(MIB);
7085 MIB.addReg(AddrIn).addImm(LdSize);
7086 AddDefaultPred(MIB);
7087 } else if (IsThumb2) {
7088 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7089 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7092 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7093 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7094 .addReg(0).addImm(LdSize));
7098 /// Emit a post-increment store operation with given size. The instructions
7099 /// will be added to BB at Pos.
7100 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7101 const TargetInstrInfo *TII, DebugLoc dl,
7102 unsigned StSize, unsigned Data, unsigned AddrIn,
7103 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7104 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7105 assert(StOpc != 0 && "Should have a store opcode");
7107 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7108 .addReg(AddrIn).addImm(0).addReg(Data));
7109 } else if (IsThumb1) {
7110 // store + update AddrIn
7111 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7112 .addReg(AddrIn).addImm(0));
7113 MachineInstrBuilder MIB =
7114 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7115 MIB = AddDefaultT1CC(MIB);
7116 MIB.addReg(AddrIn).addImm(StSize);
7117 AddDefaultPred(MIB);
7118 } else if (IsThumb2) {
7119 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7120 .addReg(Data).addReg(AddrIn).addImm(StSize));
7122 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7123 .addReg(Data).addReg(AddrIn).addReg(0)
7129 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7130 MachineBasicBlock *BB) const {
7131 // This pseudo instruction has 3 operands: dst, src, size
7132 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7133 // Otherwise, we will generate unrolled scalar copies.
7134 const TargetInstrInfo *TII =
7135 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7136 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7137 MachineFunction::iterator It = BB;
7140 unsigned dest = MI->getOperand(0).getReg();
7141 unsigned src = MI->getOperand(1).getReg();
7142 unsigned SizeVal = MI->getOperand(2).getImm();
7143 unsigned Align = MI->getOperand(3).getImm();
7144 DebugLoc dl = MI->getDebugLoc();
7146 MachineFunction *MF = BB->getParent();
7147 MachineRegisterInfo &MRI = MF->getRegInfo();
7148 unsigned UnitSize = 0;
7149 const TargetRegisterClass *TRC = nullptr;
7150 const TargetRegisterClass *VecTRC = nullptr;
7152 bool IsThumb1 = Subtarget->isThumb1Only();
7153 bool IsThumb2 = Subtarget->isThumb2();
7157 } else if (Align & 2) {
7160 // Check whether we can use NEON instructions.
7161 if (!MF->getFunction()->getAttributes().
7162 hasAttribute(AttributeSet::FunctionIndex,
7163 Attribute::NoImplicitFloat) &&
7164 Subtarget->hasNEON()) {
7165 if ((Align % 16 == 0) && SizeVal >= 16)
7167 else if ((Align % 8 == 0) && SizeVal >= 8)
7170 // Can't use NEON instructions.
7175 // Select the correct opcode and register class for unit size load/store
7176 bool IsNeon = UnitSize >= 8;
7177 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7178 : (const TargetRegisterClass *)&ARM::GPRRegClass;
7180 VecTRC = UnitSize == 16
7181 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7183 ? (const TargetRegisterClass *)&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 = MRI.createVirtualRegister(isThumb2 ?
7633 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7634 (const TargetRegisterClass*)&ARM::GPRRegClass);
7636 // Transfer the remainder of BB and its successor edges to sinkMBB.
7637 SinkBB->splice(SinkBB->begin(), BB,
7638 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7639 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7641 BB->addSuccessor(RSBBB);
7642 BB->addSuccessor(SinkBB);
7644 // fall through to SinkMBB
7645 RSBBB->addSuccessor(SinkBB);
7647 // insert a cmp at the end of BB
7648 AddDefaultPred(BuildMI(BB, dl,
7649 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7650 .addReg(ABSSrcReg).addImm(0));
7652 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7654 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7655 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7657 // insert rsbri in RSBBB
7658 // Note: BCC and rsbri will be converted into predicated rsbmi
7659 // by if-conversion pass
7660 BuildMI(*RSBBB, RSBBB->begin(), dl,
7661 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7662 .addReg(ABSSrcReg, RegState::Kill)
7663 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7665 // insert PHI in SinkBB,
7666 // reuse ABSDstReg to not change uses of ABS instruction
7667 BuildMI(*SinkBB, SinkBB->begin(), dl,
7668 TII->get(ARM::PHI), ABSDstReg)
7669 .addReg(NewRsbDstReg).addMBB(RSBBB)
7670 .addReg(ABSSrcReg).addMBB(BB);
7672 // remove ABS instruction
7673 MI->eraseFromParent();
7675 // return last added BB
7678 case ARM::COPY_STRUCT_BYVAL_I32:
7680 return EmitStructByval(MI, BB);
7681 case ARM::WIN__CHKSTK:
7682 return EmitLowered__chkstk(MI, BB);
7686 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7687 SDNode *Node) const {
7688 const MCInstrDesc *MCID = &MI->getDesc();
7689 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7690 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7691 // operand is still set to noreg. If needed, set the optional operand's
7692 // register to CPSR, and remove the redundant implicit def.
7694 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7696 // Rename pseudo opcodes.
7697 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7699 const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7700 getTargetMachine().getSubtargetImpl()->getInstrInfo());
7701 MCID = &TII->get(NewOpc);
7703 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7704 "converted opcode should be the same except for cc_out");
7708 // Add the optional cc_out operand
7709 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7711 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7713 // Any ARM instruction that sets the 's' bit should specify an optional
7714 // "cc_out" operand in the last operand position.
7715 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7716 assert(!NewOpc && "Optional cc_out operand required");
7719 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7720 // since we already have an optional CPSR def.
7721 bool definesCPSR = false;
7722 bool deadCPSR = false;
7723 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7725 const MachineOperand &MO = MI->getOperand(i);
7726 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7730 MI->RemoveOperand(i);
7735 assert(!NewOpc && "Optional cc_out operand required");
7738 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7740 assert(!MI->getOperand(ccOutIdx).getReg() &&
7741 "expect uninitialized optional cc_out operand");
7745 // If this instruction was defined with an optional CPSR def and its dag node
7746 // had a live implicit CPSR def, then activate the optional CPSR def.
7747 MachineOperand &MO = MI->getOperand(ccOutIdx);
7748 MO.setReg(ARM::CPSR);
7752 //===----------------------------------------------------------------------===//
7753 // ARM Optimization Hooks
7754 //===----------------------------------------------------------------------===//
7756 // Helper function that checks if N is a null or all ones constant.
7757 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7758 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7761 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7764 // Return true if N is conditionally 0 or all ones.
7765 // Detects these expressions where cc is an i1 value:
7767 // (select cc 0, y) [AllOnes=0]
7768 // (select cc y, 0) [AllOnes=0]
7769 // (zext cc) [AllOnes=0]
7770 // (sext cc) [AllOnes=0/1]
7771 // (select cc -1, y) [AllOnes=1]
7772 // (select cc y, -1) [AllOnes=1]
7774 // Invert is set when N is the null/all ones constant when CC is false.
7775 // OtherOp is set to the alternative value of N.
7776 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7777 SDValue &CC, bool &Invert,
7779 SelectionDAG &DAG) {
7780 switch (N->getOpcode()) {
7781 default: return false;
7783 CC = N->getOperand(0);
7784 SDValue N1 = N->getOperand(1);
7785 SDValue N2 = N->getOperand(2);
7786 if (isZeroOrAllOnes(N1, AllOnes)) {
7791 if (isZeroOrAllOnes(N2, AllOnes)) {
7798 case ISD::ZERO_EXTEND:
7799 // (zext cc) can never be the all ones value.
7803 case ISD::SIGN_EXTEND: {
7804 EVT VT = N->getValueType(0);
7805 CC = N->getOperand(0);
7806 if (CC.getValueType() != MVT::i1)
7810 // When looking for an AllOnes constant, N is an sext, and the 'other'
7812 OtherOp = DAG.getConstant(0, VT);
7813 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7814 // When looking for a 0 constant, N can be zext or sext.
7815 OtherOp = DAG.getConstant(1, VT);
7817 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7823 // Combine a constant select operand into its use:
7825 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7826 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7827 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7828 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7829 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7831 // The transform is rejected if the select doesn't have a constant operand that
7832 // is null, or all ones when AllOnes is set.
7834 // Also recognize sext/zext from i1:
7836 // (add (zext cc), x) -> (select cc (add x, 1), x)
7837 // (add (sext cc), x) -> (select cc (add x, -1), x)
7839 // These transformations eventually create predicated instructions.
7841 // @param N The node to transform.
7842 // @param Slct The N operand that is a select.
7843 // @param OtherOp The other N operand (x above).
7844 // @param DCI Context.
7845 // @param AllOnes Require the select constant to be all ones instead of null.
7846 // @returns The new node, or SDValue() on failure.
7848 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7849 TargetLowering::DAGCombinerInfo &DCI,
7850 bool AllOnes = false) {
7851 SelectionDAG &DAG = DCI.DAG;
7852 EVT VT = N->getValueType(0);
7853 SDValue NonConstantVal;
7856 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7857 NonConstantVal, DAG))
7860 // Slct is now know to be the desired identity constant when CC is true.
7861 SDValue TrueVal = OtherOp;
7862 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7863 OtherOp, NonConstantVal);
7864 // Unless SwapSelectOps says CC should be false.
7866 std::swap(TrueVal, FalseVal);
7868 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7869 CCOp, TrueVal, FalseVal);
7872 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7874 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7875 TargetLowering::DAGCombinerInfo &DCI) {
7876 SDValue N0 = N->getOperand(0);
7877 SDValue N1 = N->getOperand(1);
7878 if (N0.getNode()->hasOneUse()) {
7879 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7880 if (Result.getNode())
7883 if (N1.getNode()->hasOneUse()) {
7884 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7885 if (Result.getNode())
7891 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7892 // (only after legalization).
7893 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7894 TargetLowering::DAGCombinerInfo &DCI,
7895 const ARMSubtarget *Subtarget) {
7897 // Only perform optimization if after legalize, and if NEON is available. We
7898 // also expected both operands to be BUILD_VECTORs.
7899 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7900 || N0.getOpcode() != ISD::BUILD_VECTOR
7901 || N1.getOpcode() != ISD::BUILD_VECTOR)
7904 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7905 EVT VT = N->getValueType(0);
7906 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7909 // Check that the vector operands are of the right form.
7910 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7911 // operands, where N is the size of the formed vector.
7912 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7913 // index such that we have a pair wise add pattern.
7915 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7916 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7918 SDValue Vec = N0->getOperand(0)->getOperand(0);
7919 SDNode *V = Vec.getNode();
7920 unsigned nextIndex = 0;
7922 // For each operands to the ADD which are BUILD_VECTORs,
7923 // check to see if each of their operands are an EXTRACT_VECTOR with
7924 // the same vector and appropriate index.
7925 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7926 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7927 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7929 SDValue ExtVec0 = N0->getOperand(i);
7930 SDValue ExtVec1 = N1->getOperand(i);
7932 // First operand is the vector, verify its the same.
7933 if (V != ExtVec0->getOperand(0).getNode() ||
7934 V != ExtVec1->getOperand(0).getNode())
7937 // Second is the constant, verify its correct.
7938 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7939 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7941 // For the constant, we want to see all the even or all the odd.
7942 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7943 || C1->getZExtValue() != nextIndex+1)
7952 // Create VPADDL node.
7953 SelectionDAG &DAG = DCI.DAG;
7954 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7956 // Build operand list.
7957 SmallVector<SDValue, 8> Ops;
7958 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7959 TLI.getPointerTy()));
7961 // Input is the vector.
7964 // Get widened type and narrowed type.
7966 unsigned numElem = VT.getVectorNumElements();
7968 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7969 switch (inputLaneType.getSimpleVT().SimpleTy) {
7970 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7971 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7972 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7974 llvm_unreachable("Invalid vector element type for padd optimization.");
7977 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7978 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7979 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7982 static SDValue findMUL_LOHI(SDValue V) {
7983 if (V->getOpcode() == ISD::UMUL_LOHI ||
7984 V->getOpcode() == ISD::SMUL_LOHI)
7989 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7990 TargetLowering::DAGCombinerInfo &DCI,
7991 const ARMSubtarget *Subtarget) {
7993 if (Subtarget->isThumb1Only()) return SDValue();
7995 // Only perform the checks after legalize when the pattern is available.
7996 if (DCI.isBeforeLegalize()) return SDValue();
7998 // Look for multiply add opportunities.
7999 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8000 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8001 // a glue link from the first add to the second add.
8002 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8003 // a S/UMLAL instruction.
8006 // \ / \ [no multiline comment]
8012 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8013 SDValue AddcOp0 = AddcNode->getOperand(0);
8014 SDValue AddcOp1 = AddcNode->getOperand(1);
8016 // Check if the two operands are from the same mul_lohi node.
8017 if (AddcOp0.getNode() == AddcOp1.getNode())
8020 assert(AddcNode->getNumValues() == 2 &&
8021 AddcNode->getValueType(0) == MVT::i32 &&
8022 "Expect ADDC with two result values. First: i32");
8024 // Check that we have a glued ADDC node.
8025 if (AddcNode->getValueType(1) != MVT::Glue)
8028 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8029 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8030 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8031 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8032 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8035 // Look for the glued ADDE.
8036 SDNode* AddeNode = AddcNode->getGluedUser();
8040 // Make sure it is really an ADDE.
8041 if (AddeNode->getOpcode() != ISD::ADDE)
8044 assert(AddeNode->getNumOperands() == 3 &&
8045 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8046 "ADDE node has the wrong inputs");
8048 // Check for the triangle shape.
8049 SDValue AddeOp0 = AddeNode->getOperand(0);
8050 SDValue AddeOp1 = AddeNode->getOperand(1);
8052 // Make sure that the ADDE operands are not coming from the same node.
8053 if (AddeOp0.getNode() == AddeOp1.getNode())
8056 // Find the MUL_LOHI node walking up ADDE's operands.
8057 bool IsLeftOperandMUL = false;
8058 SDValue MULOp = findMUL_LOHI(AddeOp0);
8059 if (MULOp == SDValue())
8060 MULOp = findMUL_LOHI(AddeOp1);
8062 IsLeftOperandMUL = true;
8063 if (MULOp == SDValue())
8066 // Figure out the right opcode.
8067 unsigned Opc = MULOp->getOpcode();
8068 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8070 // Figure out the high and low input values to the MLAL node.
8071 SDValue* HiMul = &MULOp;
8072 SDValue* HiAdd = nullptr;
8073 SDValue* LoMul = nullptr;
8074 SDValue* LowAdd = nullptr;
8076 if (IsLeftOperandMUL)
8082 if (AddcOp0->getOpcode() == Opc) {
8086 if (AddcOp1->getOpcode() == Opc) {
8094 if (LoMul->getNode() != HiMul->getNode())
8097 // Create the merged node.
8098 SelectionDAG &DAG = DCI.DAG;
8100 // Build operand list.
8101 SmallVector<SDValue, 8> Ops;
8102 Ops.push_back(LoMul->getOperand(0));
8103 Ops.push_back(LoMul->getOperand(1));
8104 Ops.push_back(*LowAdd);
8105 Ops.push_back(*HiAdd);
8107 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8108 DAG.getVTList(MVT::i32, MVT::i32), Ops);
8110 // Replace the ADDs' nodes uses by the MLA node's values.
8111 SDValue HiMLALResult(MLALNode.getNode(), 1);
8112 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8114 SDValue LoMLALResult(MLALNode.getNode(), 0);
8115 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8117 // Return original node to notify the driver to stop replacing.
8118 SDValue resNode(AddcNode, 0);
8122 /// PerformADDCCombine - Target-specific dag combine transform from
8123 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8124 static SDValue PerformADDCCombine(SDNode *N,
8125 TargetLowering::DAGCombinerInfo &DCI,
8126 const ARMSubtarget *Subtarget) {
8128 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8132 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8133 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8134 /// called with the default operands, and if that fails, with commuted
8136 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8137 TargetLowering::DAGCombinerInfo &DCI,
8138 const ARMSubtarget *Subtarget){
8140 // Attempt to create vpaddl for this add.
8141 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8142 if (Result.getNode())
8145 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8146 if (N0.getNode()->hasOneUse()) {
8147 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8148 if (Result.getNode()) return Result;
8153 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8155 static SDValue PerformADDCombine(SDNode *N,
8156 TargetLowering::DAGCombinerInfo &DCI,
8157 const ARMSubtarget *Subtarget) {
8158 SDValue N0 = N->getOperand(0);
8159 SDValue N1 = N->getOperand(1);
8161 // First try with the default operand order.
8162 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8163 if (Result.getNode())
8166 // If that didn't work, try again with the operands commuted.
8167 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8170 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8172 static SDValue PerformSUBCombine(SDNode *N,
8173 TargetLowering::DAGCombinerInfo &DCI) {
8174 SDValue N0 = N->getOperand(0);
8175 SDValue N1 = N->getOperand(1);
8177 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8178 if (N1.getNode()->hasOneUse()) {
8179 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8180 if (Result.getNode()) return Result;
8186 /// PerformVMULCombine
8187 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8188 /// special multiplier accumulator forwarding.
8194 // However, for (A + B) * (A + B),
8201 static SDValue PerformVMULCombine(SDNode *N,
8202 TargetLowering::DAGCombinerInfo &DCI,
8203 const ARMSubtarget *Subtarget) {
8204 if (!Subtarget->hasVMLxForwarding())
8207 SelectionDAG &DAG = DCI.DAG;
8208 SDValue N0 = N->getOperand(0);
8209 SDValue N1 = N->getOperand(1);
8210 unsigned Opcode = N0.getOpcode();
8211 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8212 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8213 Opcode = N1.getOpcode();
8214 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8215 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8223 EVT VT = N->getValueType(0);
8225 SDValue N00 = N0->getOperand(0);
8226 SDValue N01 = N0->getOperand(1);
8227 return DAG.getNode(Opcode, DL, VT,
8228 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8229 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8232 static SDValue PerformMULCombine(SDNode *N,
8233 TargetLowering::DAGCombinerInfo &DCI,
8234 const ARMSubtarget *Subtarget) {
8235 SelectionDAG &DAG = DCI.DAG;
8237 if (Subtarget->isThumb1Only())
8240 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8243 EVT VT = N->getValueType(0);
8244 if (VT.is64BitVector() || VT.is128BitVector())
8245 return PerformVMULCombine(N, DCI, Subtarget);
8249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8253 int64_t MulAmt = C->getSExtValue();
8254 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8256 ShiftAmt = ShiftAmt & (32 - 1);
8257 SDValue V = N->getOperand(0);
8261 MulAmt >>= ShiftAmt;
8264 if (isPowerOf2_32(MulAmt - 1)) {
8265 // (mul x, 2^N + 1) => (add (shl x, N), x)
8266 Res = DAG.getNode(ISD::ADD, DL, VT,
8268 DAG.getNode(ISD::SHL, DL, VT,
8270 DAG.getConstant(Log2_32(MulAmt - 1),
8272 } else if (isPowerOf2_32(MulAmt + 1)) {
8273 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8274 Res = DAG.getNode(ISD::SUB, DL, VT,
8275 DAG.getNode(ISD::SHL, DL, VT,
8277 DAG.getConstant(Log2_32(MulAmt + 1),
8283 uint64_t MulAmtAbs = -MulAmt;
8284 if (isPowerOf2_32(MulAmtAbs + 1)) {
8285 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8286 Res = DAG.getNode(ISD::SUB, DL, VT,
8288 DAG.getNode(ISD::SHL, DL, VT,
8290 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8292 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8293 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8294 Res = DAG.getNode(ISD::ADD, DL, VT,
8296 DAG.getNode(ISD::SHL, DL, VT,
8298 DAG.getConstant(Log2_32(MulAmtAbs-1),
8300 Res = DAG.getNode(ISD::SUB, DL, VT,
8301 DAG.getConstant(0, MVT::i32),Res);
8308 Res = DAG.getNode(ISD::SHL, DL, VT,
8309 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8311 // Do not add new nodes to DAG combiner worklist.
8312 DCI.CombineTo(N, Res, false);
8316 static SDValue PerformANDCombine(SDNode *N,
8317 TargetLowering::DAGCombinerInfo &DCI,
8318 const ARMSubtarget *Subtarget) {
8320 // Attempt to use immediate-form VBIC
8321 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8323 EVT VT = N->getValueType(0);
8324 SelectionDAG &DAG = DCI.DAG;
8326 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8329 APInt SplatBits, SplatUndef;
8330 unsigned SplatBitSize;
8333 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8334 if (SplatBitSize <= 64) {
8336 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8337 SplatUndef.getZExtValue(), SplatBitSize,
8338 DAG, VbicVT, VT.is128BitVector(),
8340 if (Val.getNode()) {
8342 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8343 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8344 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8349 if (!Subtarget->isThumb1Only()) {
8350 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8351 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8352 if (Result.getNode())
8359 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8360 static SDValue PerformORCombine(SDNode *N,
8361 TargetLowering::DAGCombinerInfo &DCI,
8362 const ARMSubtarget *Subtarget) {
8363 // Attempt to use immediate-form VORR
8364 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8366 EVT VT = N->getValueType(0);
8367 SelectionDAG &DAG = DCI.DAG;
8369 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8372 APInt SplatBits, SplatUndef;
8373 unsigned SplatBitSize;
8375 if (BVN && Subtarget->hasNEON() &&
8376 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8377 if (SplatBitSize <= 64) {
8379 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8380 SplatUndef.getZExtValue(), SplatBitSize,
8381 DAG, VorrVT, VT.is128BitVector(),
8383 if (Val.getNode()) {
8385 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8386 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8387 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8392 if (!Subtarget->isThumb1Only()) {
8393 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8394 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8395 if (Result.getNode())
8399 // The code below optimizes (or (and X, Y), Z).
8400 // The AND operand needs to have a single user to make these optimizations
8402 SDValue N0 = N->getOperand(0);
8403 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8405 SDValue N1 = N->getOperand(1);
8407 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8408 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8409 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8411 unsigned SplatBitSize;
8414 APInt SplatBits0, SplatBits1;
8415 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8416 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8417 // Ensure that the second operand of both ands are constants
8418 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8419 HasAnyUndefs) && !HasAnyUndefs) {
8420 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8421 HasAnyUndefs) && !HasAnyUndefs) {
8422 // Ensure that the bit width of the constants are the same and that
8423 // the splat arguments are logical inverses as per the pattern we
8424 // are trying to simplify.
8425 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8426 SplatBits0 == ~SplatBits1) {
8427 // Canonicalize the vector type to make instruction selection
8429 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8430 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8434 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8440 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8443 // BFI is only available on V6T2+
8444 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8448 // 1) or (and A, mask), val => ARMbfi A, val, mask
8449 // iff (val & mask) == val
8451 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8452 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8453 // && mask == ~mask2
8454 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8455 // && ~mask == mask2
8456 // (i.e., copy a bitfield value into another bitfield of the same width)
8461 SDValue N00 = N0.getOperand(0);
8463 // The value and the mask need to be constants so we can verify this is
8464 // actually a bitfield set. If the mask is 0xffff, we can do better
8465 // via a movt instruction, so don't use BFI in that case.
8466 SDValue MaskOp = N0.getOperand(1);
8467 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8470 unsigned Mask = MaskC->getZExtValue();
8474 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8475 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8477 unsigned Val = N1C->getZExtValue();
8478 if ((Val & ~Mask) != Val)
8481 if (ARM::isBitFieldInvertedMask(Mask)) {
8482 Val >>= countTrailingZeros(~Mask);
8484 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8485 DAG.getConstant(Val, MVT::i32),
8486 DAG.getConstant(Mask, MVT::i32));
8488 // Do not add new nodes to DAG combiner worklist.
8489 DCI.CombineTo(N, Res, false);
8492 } else if (N1.getOpcode() == ISD::AND) {
8493 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8494 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8497 unsigned Mask2 = N11C->getZExtValue();
8499 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8501 if (ARM::isBitFieldInvertedMask(Mask) &&
8503 // The pack halfword instruction works better for masks that fit it,
8504 // so use that when it's available.
8505 if (Subtarget->hasT2ExtractPack() &&
8506 (Mask == 0xffff || Mask == 0xffff0000))
8509 unsigned amt = countTrailingZeros(Mask2);
8510 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8511 DAG.getConstant(amt, MVT::i32));
8512 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8513 DAG.getConstant(Mask, MVT::i32));
8514 // Do not add new nodes to DAG combiner worklist.
8515 DCI.CombineTo(N, Res, false);
8517 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8519 // The pack halfword instruction works better for masks that fit it,
8520 // so use that when it's available.
8521 if (Subtarget->hasT2ExtractPack() &&
8522 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8525 unsigned lsb = countTrailingZeros(Mask);
8526 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8527 DAG.getConstant(lsb, MVT::i32));
8528 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8529 DAG.getConstant(Mask2, MVT::i32));
8530 // Do not add new nodes to DAG combiner worklist.
8531 DCI.CombineTo(N, Res, false);
8536 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8537 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8538 ARM::isBitFieldInvertedMask(~Mask)) {
8539 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8540 // where lsb(mask) == #shamt and masked bits of B are known zero.
8541 SDValue ShAmt = N00.getOperand(1);
8542 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8543 unsigned LSB = countTrailingZeros(Mask);
8547 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8548 DAG.getConstant(~Mask, MVT::i32));
8550 // Do not add new nodes to DAG combiner worklist.
8551 DCI.CombineTo(N, Res, false);
8557 static SDValue PerformXORCombine(SDNode *N,
8558 TargetLowering::DAGCombinerInfo &DCI,
8559 const ARMSubtarget *Subtarget) {
8560 EVT VT = N->getValueType(0);
8561 SelectionDAG &DAG = DCI.DAG;
8563 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8566 if (!Subtarget->isThumb1Only()) {
8567 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8568 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8569 if (Result.getNode())
8576 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8577 /// the bits being cleared by the AND are not demanded by the BFI.
8578 static SDValue PerformBFICombine(SDNode *N,
8579 TargetLowering::DAGCombinerInfo &DCI) {
8580 SDValue N1 = N->getOperand(1);
8581 if (N1.getOpcode() == ISD::AND) {
8582 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8585 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8586 unsigned LSB = countTrailingZeros(~InvMask);
8587 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8588 unsigned Mask = (1 << Width)-1;
8589 unsigned Mask2 = N11C->getZExtValue();
8590 if ((Mask & (~Mask2)) == 0)
8591 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8592 N->getOperand(0), N1.getOperand(0),
8598 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8599 /// ARMISD::VMOVRRD.
8600 static SDValue PerformVMOVRRDCombine(SDNode *N,
8601 TargetLowering::DAGCombinerInfo &DCI,
8602 const ARMSubtarget *Subtarget) {
8603 // vmovrrd(vmovdrr x, y) -> x,y
8604 SDValue InDouble = N->getOperand(0);
8605 if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8606 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8608 // vmovrrd(load f64) -> (load i32), (load i32)
8609 SDNode *InNode = InDouble.getNode();
8610 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8611 InNode->getValueType(0) == MVT::f64 &&
8612 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8613 !cast<LoadSDNode>(InNode)->isVolatile()) {
8614 // TODO: Should this be done for non-FrameIndex operands?
8615 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8617 SelectionDAG &DAG = DCI.DAG;
8619 SDValue BasePtr = LD->getBasePtr();
8620 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8621 LD->getPointerInfo(), LD->isVolatile(),
8622 LD->isNonTemporal(), LD->isInvariant(),
8623 LD->getAlignment());
8625 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8626 DAG.getConstant(4, MVT::i32));
8627 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8628 LD->getPointerInfo(), LD->isVolatile(),
8629 LD->isNonTemporal(), LD->isInvariant(),
8630 std::min(4U, LD->getAlignment() / 2));
8632 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8633 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8634 std::swap (NewLD1, NewLD2);
8635 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8642 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8643 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8644 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8645 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8646 SDValue Op0 = N->getOperand(0);
8647 SDValue Op1 = N->getOperand(1);
8648 if (Op0.getOpcode() == ISD::BITCAST)
8649 Op0 = Op0.getOperand(0);
8650 if (Op1.getOpcode() == ISD::BITCAST)
8651 Op1 = Op1.getOperand(0);
8652 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8653 Op0.getNode() == Op1.getNode() &&
8654 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8655 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8656 N->getValueType(0), Op0.getOperand(0));
8660 /// PerformSTORECombine - Target-specific dag combine xforms for
8662 static SDValue PerformSTORECombine(SDNode *N,
8663 TargetLowering::DAGCombinerInfo &DCI) {
8664 StoreSDNode *St = cast<StoreSDNode>(N);
8665 if (St->isVolatile())
8668 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8669 // pack all of the elements in one place. Next, store to memory in fewer
8671 SDValue StVal = St->getValue();
8672 EVT VT = StVal.getValueType();
8673 if (St->isTruncatingStore() && VT.isVector()) {
8674 SelectionDAG &DAG = DCI.DAG;
8675 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8676 EVT StVT = St->getMemoryVT();
8677 unsigned NumElems = VT.getVectorNumElements();
8678 assert(StVT != VT && "Cannot truncate to the same type");
8679 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8680 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8682 // From, To sizes and ElemCount must be pow of two
8683 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8685 // We are going to use the original vector elt for storing.
8686 // Accumulated smaller vector elements must be a multiple of the store size.
8687 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8689 unsigned SizeRatio = FromEltSz / ToEltSz;
8690 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8692 // Create a type on which we perform the shuffle.
8693 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8694 NumElems*SizeRatio);
8695 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8698 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8699 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8700 for (unsigned i = 0; i < NumElems; ++i)
8701 ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8703 // Can't shuffle using an illegal type.
8704 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8706 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8707 DAG.getUNDEF(WideVec.getValueType()),
8709 // At this point all of the data is stored at the bottom of the
8710 // register. We now need to save it to mem.
8712 // Find the largest store unit
8713 MVT StoreType = MVT::i8;
8714 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8715 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8716 MVT Tp = (MVT::SimpleValueType)tp;
8717 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8720 // Didn't find a legal store type.
8721 if (!TLI.isTypeLegal(StoreType))
8724 // Bitcast the original vector into a vector of store-size units
8725 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8726 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8727 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8728 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8729 SmallVector<SDValue, 8> Chains;
8730 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8731 TLI.getPointerTy());
8732 SDValue BasePtr = St->getBasePtr();
8734 // Perform one or more big stores into memory.
8735 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8736 for (unsigned I = 0; I < E; I++) {
8737 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8738 StoreType, ShuffWide,
8739 DAG.getIntPtrConstant(I));
8740 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8741 St->getPointerInfo(), St->isVolatile(),
8742 St->isNonTemporal(), St->getAlignment());
8743 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8745 Chains.push_back(Ch);
8747 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8750 if (!ISD::isNormalStore(St))
8753 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8754 // ARM stores of arguments in the same cache line.
8755 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8756 StVal.getNode()->hasOneUse()) {
8757 SelectionDAG &DAG = DCI.DAG;
8758 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8760 SDValue BasePtr = St->getBasePtr();
8761 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8762 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8763 BasePtr, St->getPointerInfo(), St->isVolatile(),
8764 St->isNonTemporal(), St->getAlignment());
8766 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8767 DAG.getConstant(4, MVT::i32));
8768 return DAG.getStore(NewST1.getValue(0), DL,
8769 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8770 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8771 St->isNonTemporal(),
8772 std::min(4U, St->getAlignment() / 2));
8775 if (StVal.getValueType() != MVT::i64 ||
8776 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8779 // Bitcast an i64 store extracted from a vector to f64.
8780 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8781 SelectionDAG &DAG = DCI.DAG;
8783 SDValue IntVec = StVal.getOperand(0);
8784 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8785 IntVec.getValueType().getVectorNumElements());
8786 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8787 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8788 Vec, StVal.getOperand(1));
8790 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8791 // Make the DAGCombiner fold the bitcasts.
8792 DCI.AddToWorklist(Vec.getNode());
8793 DCI.AddToWorklist(ExtElt.getNode());
8794 DCI.AddToWorklist(V.getNode());
8795 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8796 St->getPointerInfo(), St->isVolatile(),
8797 St->isNonTemporal(), St->getAlignment(),
8801 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8802 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8803 /// i64 vector to have f64 elements, since the value can then be loaded
8804 /// directly into a VFP register.
8805 static bool hasNormalLoadOperand(SDNode *N) {
8806 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8807 for (unsigned i = 0; i < NumElts; ++i) {
8808 SDNode *Elt = N->getOperand(i).getNode();
8809 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8815 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8816 /// ISD::BUILD_VECTOR.
8817 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8818 TargetLowering::DAGCombinerInfo &DCI,
8819 const ARMSubtarget *Subtarget) {
8820 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8821 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8822 // into a pair of GPRs, which is fine when the value is used as a scalar,
8823 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8824 SelectionDAG &DAG = DCI.DAG;
8825 if (N->getNumOperands() == 2) {
8826 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8831 // Load i64 elements as f64 values so that type legalization does not split
8832 // them up into i32 values.
8833 EVT VT = N->getValueType(0);
8834 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8837 SmallVector<SDValue, 8> Ops;
8838 unsigned NumElts = VT.getVectorNumElements();
8839 for (unsigned i = 0; i < NumElts; ++i) {
8840 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8842 // Make the DAGCombiner fold the bitcast.
8843 DCI.AddToWorklist(V.getNode());
8845 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8846 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8847 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8850 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8852 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8853 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8854 // At that time, we may have inserted bitcasts from integer to float.
8855 // If these bitcasts have survived DAGCombine, change the lowering of this
8856 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8857 // force to use floating point types.
8859 // Make sure we can change the type of the vector.
8860 // This is possible iff:
8861 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8862 // 1.1. Vector is used only once.
8863 // 1.2. Use is a bit convert to an integer type.
8864 // 2. The size of its operands are 32-bits (64-bits are not legal).
8865 EVT VT = N->getValueType(0);
8866 EVT EltVT = VT.getVectorElementType();
8868 // Check 1.1. and 2.
8869 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8872 // By construction, the input type must be float.
8873 assert(EltVT == MVT::f32 && "Unexpected type!");
8876 SDNode *Use = *N->use_begin();
8877 if (Use->getOpcode() != ISD::BITCAST ||
8878 Use->getValueType(0).isFloatingPoint())
8881 // Check profitability.
8882 // Model is, if more than half of the relevant operands are bitcast from
8883 // i32, turn the build_vector into a sequence of insert_vector_elt.
8884 // Relevant operands are everything that is not statically
8885 // (i.e., at compile time) bitcasted.
8886 unsigned NumOfBitCastedElts = 0;
8887 unsigned NumElts = VT.getVectorNumElements();
8888 unsigned NumOfRelevantElts = NumElts;
8889 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8890 SDValue Elt = N->getOperand(Idx);
8891 if (Elt->getOpcode() == ISD::BITCAST) {
8892 // Assume only bit cast to i32 will go away.
8893 if (Elt->getOperand(0).getValueType() == MVT::i32)
8894 ++NumOfBitCastedElts;
8895 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8896 // Constants are statically casted, thus do not count them as
8897 // relevant operands.
8898 --NumOfRelevantElts;
8901 // Check if more than half of the elements require a non-free bitcast.
8902 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8905 SelectionDAG &DAG = DCI.DAG;
8906 // Create the new vector type.
8907 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8908 // Check if the type is legal.
8909 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8910 if (!TLI.isTypeLegal(VecVT))
8914 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8915 // => BITCAST INSERT_VECTOR_ELT
8916 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8918 SDValue Vec = DAG.getUNDEF(VecVT);
8920 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8921 SDValue V = N->getOperand(Idx);
8922 if (V.getOpcode() == ISD::UNDEF)
8924 if (V.getOpcode() == ISD::BITCAST &&
8925 V->getOperand(0).getValueType() == MVT::i32)
8926 // Fold obvious case.
8927 V = V.getOperand(0);
8929 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8930 // Make the DAGCombiner fold the bitcasts.
8931 DCI.AddToWorklist(V.getNode());
8933 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8934 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8936 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8937 // Make the DAGCombiner fold the bitcasts.
8938 DCI.AddToWorklist(Vec.getNode());
8942 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8943 /// ISD::INSERT_VECTOR_ELT.
8944 static SDValue PerformInsertEltCombine(SDNode *N,
8945 TargetLowering::DAGCombinerInfo &DCI) {
8946 // Bitcast an i64 load inserted into a vector to f64.
8947 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8948 EVT VT = N->getValueType(0);
8949 SDNode *Elt = N->getOperand(1).getNode();
8950 if (VT.getVectorElementType() != MVT::i64 ||
8951 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8954 SelectionDAG &DAG = DCI.DAG;
8956 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8957 VT.getVectorNumElements());
8958 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8959 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8960 // Make the DAGCombiner fold the bitcasts.
8961 DCI.AddToWorklist(Vec.getNode());
8962 DCI.AddToWorklist(V.getNode());
8963 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8964 Vec, V, N->getOperand(2));
8965 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8968 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8969 /// ISD::VECTOR_SHUFFLE.
8970 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8971 // The LLVM shufflevector instruction does not require the shuffle mask
8972 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8973 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8974 // operands do not match the mask length, they are extended by concatenating
8975 // them with undef vectors. That is probably the right thing for other
8976 // targets, but for NEON it is better to concatenate two double-register
8977 // size vector operands into a single quad-register size vector. Do that
8978 // transformation here:
8979 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8980 // shuffle(concat(v1, v2), undef)
8981 SDValue Op0 = N->getOperand(0);
8982 SDValue Op1 = N->getOperand(1);
8983 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8984 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8985 Op0.getNumOperands() != 2 ||
8986 Op1.getNumOperands() != 2)
8988 SDValue Concat0Op1 = Op0.getOperand(1);
8989 SDValue Concat1Op1 = Op1.getOperand(1);
8990 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8991 Concat1Op1.getOpcode() != ISD::UNDEF)
8993 // Skip the transformation if any of the types are illegal.
8994 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8995 EVT VT = N->getValueType(0);
8996 if (!TLI.isTypeLegal(VT) ||
8997 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8998 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9001 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9002 Op0.getOperand(0), Op1.getOperand(0));
9003 // Translate the shuffle mask.
9004 SmallVector<int, 16> NewMask;
9005 unsigned NumElts = VT.getVectorNumElements();
9006 unsigned HalfElts = NumElts/2;
9007 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9008 for (unsigned n = 0; n < NumElts; ++n) {
9009 int MaskElt = SVN->getMaskElt(n);
9011 if (MaskElt < (int)HalfElts)
9013 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9014 NewElt = HalfElts + MaskElt - NumElts;
9015 NewMask.push_back(NewElt);
9017 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9018 DAG.getUNDEF(VT), NewMask.data());
9021 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9022 /// NEON load/store intrinsics to merge base address updates.
9023 static SDValue CombineBaseUpdate(SDNode *N,
9024 TargetLowering::DAGCombinerInfo &DCI) {
9025 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9028 SelectionDAG &DAG = DCI.DAG;
9029 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9030 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9031 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9032 SDValue Addr = N->getOperand(AddrOpIdx);
9034 // Search for a use of the address operand that is an increment.
9035 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9036 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9038 if (User->getOpcode() != ISD::ADD ||
9039 UI.getUse().getResNo() != Addr.getResNo())
9042 // Check that the add is independent of the load/store. Otherwise, folding
9043 // it would create a cycle.
9044 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9047 // Find the new opcode for the updating load/store.
9049 bool isLaneOp = false;
9050 unsigned NewOpc = 0;
9051 unsigned NumVecs = 0;
9053 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9055 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9056 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9058 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9060 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9062 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9064 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9065 NumVecs = 2; isLaneOp = true; break;
9066 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9067 NumVecs = 3; isLaneOp = true; break;
9068 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9069 NumVecs = 4; isLaneOp = true; break;
9070 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9071 NumVecs = 1; isLoad = false; break;
9072 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9073 NumVecs = 2; isLoad = false; break;
9074 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9075 NumVecs = 3; isLoad = false; break;
9076 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9077 NumVecs = 4; isLoad = false; break;
9078 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9079 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9080 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9081 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9082 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9083 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9087 switch (N->getOpcode()) {
9088 default: llvm_unreachable("unexpected opcode for Neon base update");
9089 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9090 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9091 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9095 // Find the size of memory referenced by the load/store.
9098 VecTy = N->getValueType(0);
9100 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9101 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9103 NumBytes /= VecTy.getVectorNumElements();
9105 // If the increment is a constant, it must match the memory ref size.
9106 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9107 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9108 uint64_t IncVal = CInc->getZExtValue();
9109 if (IncVal != NumBytes)
9111 } else if (NumBytes >= 3 * 16) {
9112 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9113 // separate instructions that make it harder to use a non-constant update.
9117 // Create the new updating load/store node.
9119 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9121 for (n = 0; n < NumResultVecs; ++n)
9123 Tys[n++] = MVT::i32;
9124 Tys[n] = MVT::Other;
9125 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9126 SmallVector<SDValue, 8> Ops;
9127 Ops.push_back(N->getOperand(0)); // incoming chain
9128 Ops.push_back(N->getOperand(AddrOpIdx));
9130 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9131 Ops.push_back(N->getOperand(i));
9133 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9134 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9135 Ops, MemInt->getMemoryVT(),
9136 MemInt->getMemOperand());
9139 std::vector<SDValue> NewResults;
9140 for (unsigned i = 0; i < NumResultVecs; ++i) {
9141 NewResults.push_back(SDValue(UpdN.getNode(), i));
9143 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9144 DCI.CombineTo(N, NewResults);
9145 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9152 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9153 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9154 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9156 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9157 SelectionDAG &DAG = DCI.DAG;
9158 EVT VT = N->getValueType(0);
9159 // vldN-dup instructions only support 64-bit vectors for N > 1.
9160 if (!VT.is64BitVector())
9163 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9164 SDNode *VLD = N->getOperand(0).getNode();
9165 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9167 unsigned NumVecs = 0;
9168 unsigned NewOpc = 0;
9169 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9170 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9172 NewOpc = ARMISD::VLD2DUP;
9173 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9175 NewOpc = ARMISD::VLD3DUP;
9176 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9178 NewOpc = ARMISD::VLD4DUP;
9183 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9184 // numbers match the load.
9185 unsigned VLDLaneNo =
9186 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9187 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9189 // Ignore uses of the chain result.
9190 if (UI.getUse().getResNo() == NumVecs)
9193 if (User->getOpcode() != ARMISD::VDUPLANE ||
9194 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9198 // Create the vldN-dup node.
9201 for (n = 0; n < NumVecs; ++n)
9203 Tys[n] = MVT::Other;
9204 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9205 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9206 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9207 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9208 Ops, VLDMemInt->getMemoryVT(),
9209 VLDMemInt->getMemOperand());
9212 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9214 unsigned ResNo = UI.getUse().getResNo();
9215 // Ignore uses of the chain result.
9216 if (ResNo == NumVecs)
9219 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9222 // Now the vldN-lane intrinsic is dead except for its chain result.
9223 // Update uses of the chain.
9224 std::vector<SDValue> VLDDupResults;
9225 for (unsigned n = 0; n < NumVecs; ++n)
9226 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9227 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9228 DCI.CombineTo(VLD, VLDDupResults);
9233 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9234 /// ARMISD::VDUPLANE.
9235 static SDValue PerformVDUPLANECombine(SDNode *N,
9236 TargetLowering::DAGCombinerInfo &DCI) {
9237 SDValue Op = N->getOperand(0);
9239 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9240 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9241 if (CombineVLDDUP(N, DCI))
9242 return SDValue(N, 0);
9244 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9245 // redundant. Ignore bit_converts for now; element sizes are checked below.
9246 while (Op.getOpcode() == ISD::BITCAST)
9247 Op = Op.getOperand(0);
9248 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9251 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9252 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9253 // The canonical VMOV for a zero vector uses a 32-bit element size.
9254 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9256 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9258 EVT VT = N->getValueType(0);
9259 if (EltSize > VT.getVectorElementType().getSizeInBits())
9262 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9265 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9266 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9267 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9271 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9273 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9278 APFloat APF = C->getValueAPF();
9279 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9280 != APFloat::opOK || !isExact)
9283 c0 = (I == 0) ? cN : c0;
9284 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9291 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9292 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9293 /// when the VMUL has a constant operand that is a power of 2.
9295 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9296 /// vmul.f32 d16, d17, d16
9297 /// vcvt.s32.f32 d16, d16
9299 /// vcvt.s32.f32 d16, d16, #3
9300 static SDValue PerformVCVTCombine(SDNode *N,
9301 TargetLowering::DAGCombinerInfo &DCI,
9302 const ARMSubtarget *Subtarget) {
9303 SelectionDAG &DAG = DCI.DAG;
9304 SDValue Op = N->getOperand(0);
9306 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9307 Op.getOpcode() != ISD::FMUL)
9311 SDValue N0 = Op->getOperand(0);
9312 SDValue ConstVec = Op->getOperand(1);
9313 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9315 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9316 !isConstVecPow2(ConstVec, isSigned, C))
9319 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9320 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9321 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9322 // These instructions only exist converting from f32 to i32. We can handle
9323 // smaller integers by generating an extra truncate, but larger ones would
9328 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9329 Intrinsic::arm_neon_vcvtfp2fxu;
9330 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9331 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9332 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9333 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9334 DAG.getConstant(Log2_64(C), MVT::i32));
9336 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9337 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9342 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9343 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9344 /// when the VDIV has a constant operand that is a power of 2.
9346 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9347 /// vcvt.f32.s32 d16, d16
9348 /// vdiv.f32 d16, d17, d16
9350 /// vcvt.f32.s32 d16, d16, #3
9351 static SDValue PerformVDIVCombine(SDNode *N,
9352 TargetLowering::DAGCombinerInfo &DCI,
9353 const ARMSubtarget *Subtarget) {
9354 SelectionDAG &DAG = DCI.DAG;
9355 SDValue Op = N->getOperand(0);
9356 unsigned OpOpcode = Op.getNode()->getOpcode();
9358 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9359 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9363 SDValue ConstVec = N->getOperand(1);
9364 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9366 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9367 !isConstVecPow2(ConstVec, isSigned, C))
9370 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9371 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9372 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9373 // These instructions only exist converting from i32 to f32. We can handle
9374 // smaller integers by generating an extra extend, but larger ones would
9379 SDValue ConvInput = Op.getOperand(0);
9380 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9381 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9382 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9383 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9386 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9387 Intrinsic::arm_neon_vcvtfxu2fp;
9388 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9390 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9391 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9394 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9395 /// operand of a vector shift operation, where all the elements of the
9396 /// build_vector must have the same constant integer value.
9397 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9398 // Ignore bit_converts.
9399 while (Op.getOpcode() == ISD::BITCAST)
9400 Op = Op.getOperand(0);
9401 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9402 APInt SplatBits, SplatUndef;
9403 unsigned SplatBitSize;
9405 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9406 HasAnyUndefs, ElementBits) ||
9407 SplatBitSize > ElementBits)
9409 Cnt = SplatBits.getSExtValue();
9413 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9414 /// operand of a vector shift left operation. That value must be in the range:
9415 /// 0 <= Value < ElementBits for a left shift; or
9416 /// 0 <= Value <= ElementBits for a long left shift.
9417 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9418 assert(VT.isVector() && "vector shift count is not a vector type");
9419 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9420 if (! getVShiftImm(Op, ElementBits, Cnt))
9422 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9425 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9426 /// operand of a vector shift right operation. For a shift opcode, the value
9427 /// is positive, but for an intrinsic the value count must be negative. The
9428 /// absolute value must be in the range:
9429 /// 1 <= |Value| <= ElementBits for a right shift; or
9430 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9431 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9433 assert(VT.isVector() && "vector shift count is not a vector type");
9434 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9435 if (! getVShiftImm(Op, ElementBits, Cnt))
9439 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9442 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9443 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9444 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9447 // Don't do anything for most intrinsics.
9450 // Vector shifts: check for immediate versions and lower them.
9451 // Note: This is done during DAG combining instead of DAG legalizing because
9452 // the build_vectors for 64-bit vector element shift counts are generally
9453 // not legal, and it is hard to see their values after they get legalized to
9454 // loads from a constant pool.
9455 case Intrinsic::arm_neon_vshifts:
9456 case Intrinsic::arm_neon_vshiftu:
9457 case Intrinsic::arm_neon_vrshifts:
9458 case Intrinsic::arm_neon_vrshiftu:
9459 case Intrinsic::arm_neon_vrshiftn:
9460 case Intrinsic::arm_neon_vqshifts:
9461 case Intrinsic::arm_neon_vqshiftu:
9462 case Intrinsic::arm_neon_vqshiftsu:
9463 case Intrinsic::arm_neon_vqshiftns:
9464 case Intrinsic::arm_neon_vqshiftnu:
9465 case Intrinsic::arm_neon_vqshiftnsu:
9466 case Intrinsic::arm_neon_vqrshiftns:
9467 case Intrinsic::arm_neon_vqrshiftnu:
9468 case Intrinsic::arm_neon_vqrshiftnsu: {
9469 EVT VT = N->getOperand(1).getValueType();
9471 unsigned VShiftOpc = 0;
9474 case Intrinsic::arm_neon_vshifts:
9475 case Intrinsic::arm_neon_vshiftu:
9476 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9477 VShiftOpc = ARMISD::VSHL;
9480 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9481 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9482 ARMISD::VSHRs : ARMISD::VSHRu);
9487 case Intrinsic::arm_neon_vrshifts:
9488 case Intrinsic::arm_neon_vrshiftu:
9489 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9493 case Intrinsic::arm_neon_vqshifts:
9494 case Intrinsic::arm_neon_vqshiftu:
9495 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9499 case Intrinsic::arm_neon_vqshiftsu:
9500 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9502 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9504 case Intrinsic::arm_neon_vrshiftn:
9505 case Intrinsic::arm_neon_vqshiftns:
9506 case Intrinsic::arm_neon_vqshiftnu:
9507 case Intrinsic::arm_neon_vqshiftnsu:
9508 case Intrinsic::arm_neon_vqrshiftns:
9509 case Intrinsic::arm_neon_vqrshiftnu:
9510 case Intrinsic::arm_neon_vqrshiftnsu:
9511 // Narrowing shifts require an immediate right shift.
9512 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9514 llvm_unreachable("invalid shift count for narrowing vector shift "
9518 llvm_unreachable("unhandled vector shift");
9522 case Intrinsic::arm_neon_vshifts:
9523 case Intrinsic::arm_neon_vshiftu:
9524 // Opcode already set above.
9526 case Intrinsic::arm_neon_vrshifts:
9527 VShiftOpc = ARMISD::VRSHRs; break;
9528 case Intrinsic::arm_neon_vrshiftu:
9529 VShiftOpc = ARMISD::VRSHRu; break;
9530 case Intrinsic::arm_neon_vrshiftn:
9531 VShiftOpc = ARMISD::VRSHRN; break;
9532 case Intrinsic::arm_neon_vqshifts:
9533 VShiftOpc = ARMISD::VQSHLs; break;
9534 case Intrinsic::arm_neon_vqshiftu:
9535 VShiftOpc = ARMISD::VQSHLu; break;
9536 case Intrinsic::arm_neon_vqshiftsu:
9537 VShiftOpc = ARMISD::VQSHLsu; break;
9538 case Intrinsic::arm_neon_vqshiftns:
9539 VShiftOpc = ARMISD::VQSHRNs; break;
9540 case Intrinsic::arm_neon_vqshiftnu:
9541 VShiftOpc = ARMISD::VQSHRNu; break;
9542 case Intrinsic::arm_neon_vqshiftnsu:
9543 VShiftOpc = ARMISD::VQSHRNsu; break;
9544 case Intrinsic::arm_neon_vqrshiftns:
9545 VShiftOpc = ARMISD::VQRSHRNs; break;
9546 case Intrinsic::arm_neon_vqrshiftnu:
9547 VShiftOpc = ARMISD::VQRSHRNu; break;
9548 case Intrinsic::arm_neon_vqrshiftnsu:
9549 VShiftOpc = ARMISD::VQRSHRNsu; break;
9552 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9553 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9556 case Intrinsic::arm_neon_vshiftins: {
9557 EVT VT = N->getOperand(1).getValueType();
9559 unsigned VShiftOpc = 0;
9561 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9562 VShiftOpc = ARMISD::VSLI;
9563 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9564 VShiftOpc = ARMISD::VSRI;
9566 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9569 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9570 N->getOperand(1), N->getOperand(2),
9571 DAG.getConstant(Cnt, MVT::i32));
9574 case Intrinsic::arm_neon_vqrshifts:
9575 case Intrinsic::arm_neon_vqrshiftu:
9576 // No immediate versions of these to check for.
9583 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9584 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9585 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9586 /// vector element shift counts are generally not legal, and it is hard to see
9587 /// their values after they get legalized to loads from a constant pool.
9588 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9589 const ARMSubtarget *ST) {
9590 EVT VT = N->getValueType(0);
9591 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9592 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9593 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9594 SDValue N1 = N->getOperand(1);
9595 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9596 SDValue N0 = N->getOperand(0);
9597 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9598 DAG.MaskedValueIsZero(N0.getOperand(0),
9599 APInt::getHighBitsSet(32, 16)))
9600 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9604 // Nothing to be done for scalar shifts.
9605 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9606 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9609 assert(ST->hasNEON() && "unexpected vector shift");
9612 switch (N->getOpcode()) {
9613 default: llvm_unreachable("unexpected shift opcode");
9616 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9617 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9618 DAG.getConstant(Cnt, MVT::i32));
9623 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9624 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9625 ARMISD::VSHRs : ARMISD::VSHRu);
9626 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9627 DAG.getConstant(Cnt, MVT::i32));
9633 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9634 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9635 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9636 const ARMSubtarget *ST) {
9637 SDValue N0 = N->getOperand(0);
9639 // Check for sign- and zero-extensions of vector extract operations of 8-
9640 // and 16-bit vector elements. NEON supports these directly. They are
9641 // handled during DAG combining because type legalization will promote them
9642 // to 32-bit types and it is messy to recognize the operations after that.
9643 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9644 SDValue Vec = N0.getOperand(0);
9645 SDValue Lane = N0.getOperand(1);
9646 EVT VT = N->getValueType(0);
9647 EVT EltVT = N0.getValueType();
9648 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9650 if (VT == MVT::i32 &&
9651 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9652 TLI.isTypeLegal(Vec.getValueType()) &&
9653 isa<ConstantSDNode>(Lane)) {
9656 switch (N->getOpcode()) {
9657 default: llvm_unreachable("unexpected opcode");
9658 case ISD::SIGN_EXTEND:
9659 Opc = ARMISD::VGETLANEs;
9661 case ISD::ZERO_EXTEND:
9662 case ISD::ANY_EXTEND:
9663 Opc = ARMISD::VGETLANEu;
9666 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9673 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9674 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9675 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9676 const ARMSubtarget *ST) {
9677 // If the target supports NEON, try to use vmax/vmin instructions for f32
9678 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9679 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9680 // a NaN; only do the transformation when it matches that behavior.
9682 // For now only do this when using NEON for FP operations; if using VFP, it
9683 // is not obvious that the benefit outweighs the cost of switching to the
9685 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9686 N->getValueType(0) != MVT::f32)
9689 SDValue CondLHS = N->getOperand(0);
9690 SDValue CondRHS = N->getOperand(1);
9691 SDValue LHS = N->getOperand(2);
9692 SDValue RHS = N->getOperand(3);
9693 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9695 unsigned Opcode = 0;
9697 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9698 IsReversed = false; // x CC y ? x : y
9699 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9700 IsReversed = true ; // x CC y ? y : x
9714 // If LHS is NaN, an ordered comparison will be false and the result will
9715 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9716 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9717 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9718 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9720 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9721 // will return -0, so vmin can only be used for unsafe math or if one of
9722 // the operands is known to be nonzero.
9723 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9724 !DAG.getTarget().Options.UnsafeFPMath &&
9725 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9727 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9736 // If LHS is NaN, an ordered comparison will be false and the result will
9737 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9738 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9739 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9740 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9742 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9743 // will return +0, so vmax can only be used for unsafe math or if one of
9744 // the operands is known to be nonzero.
9745 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9746 !DAG.getTarget().Options.UnsafeFPMath &&
9747 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9749 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9755 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9758 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9760 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9761 SDValue Cmp = N->getOperand(4);
9762 if (Cmp.getOpcode() != ARMISD::CMPZ)
9763 // Only looking at EQ and NE cases.
9766 EVT VT = N->getValueType(0);
9768 SDValue LHS = Cmp.getOperand(0);
9769 SDValue RHS = Cmp.getOperand(1);
9770 SDValue FalseVal = N->getOperand(0);
9771 SDValue TrueVal = N->getOperand(1);
9772 SDValue ARMcc = N->getOperand(2);
9773 ARMCC::CondCodes CC =
9774 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9792 /// FIXME: Turn this into a target neutral optimization?
9794 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9795 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9796 N->getOperand(3), Cmp);
9797 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9799 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9800 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9801 N->getOperand(3), NewCmp);
9804 if (Res.getNode()) {
9805 APInt KnownZero, KnownOne;
9806 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9807 // Capture demanded bits information that would be otherwise lost.
9808 if (KnownZero == 0xfffffffe)
9809 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9810 DAG.getValueType(MVT::i1));
9811 else if (KnownZero == 0xffffff00)
9812 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9813 DAG.getValueType(MVT::i8));
9814 else if (KnownZero == 0xffff0000)
9815 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9816 DAG.getValueType(MVT::i16));
9822 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9823 DAGCombinerInfo &DCI) const {
9824 switch (N->getOpcode()) {
9826 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9827 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9828 case ISD::SUB: return PerformSUBCombine(N, DCI);
9829 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9830 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9831 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9832 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9833 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9834 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9835 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9836 case ISD::STORE: return PerformSTORECombine(N, DCI);
9837 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9838 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9839 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9840 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9841 case ISD::FP_TO_SINT:
9842 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9843 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9844 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9847 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9848 case ISD::SIGN_EXTEND:
9849 case ISD::ZERO_EXTEND:
9850 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9851 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9852 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9853 case ARMISD::VLD2DUP:
9854 case ARMISD::VLD3DUP:
9855 case ARMISD::VLD4DUP:
9856 return CombineBaseUpdate(N, DCI);
9857 case ARMISD::BUILD_VECTOR:
9858 return PerformARMBUILD_VECTORCombine(N, DCI);
9859 case ISD::INTRINSIC_VOID:
9860 case ISD::INTRINSIC_W_CHAIN:
9861 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9862 case Intrinsic::arm_neon_vld1:
9863 case Intrinsic::arm_neon_vld2:
9864 case Intrinsic::arm_neon_vld3:
9865 case Intrinsic::arm_neon_vld4:
9866 case Intrinsic::arm_neon_vld2lane:
9867 case Intrinsic::arm_neon_vld3lane:
9868 case Intrinsic::arm_neon_vld4lane:
9869 case Intrinsic::arm_neon_vst1:
9870 case Intrinsic::arm_neon_vst2:
9871 case Intrinsic::arm_neon_vst3:
9872 case Intrinsic::arm_neon_vst4:
9873 case Intrinsic::arm_neon_vst2lane:
9874 case Intrinsic::arm_neon_vst3lane:
9875 case Intrinsic::arm_neon_vst4lane:
9876 return CombineBaseUpdate(N, DCI);
9884 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9886 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9889 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9893 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9894 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9896 switch (VT.getSimpleVT().SimpleTy) {
9902 // Unaligned access can use (for example) LRDB, LRDH, LDR
9903 if (AllowsUnaligned) {
9905 *Fast = Subtarget->hasV7Ops();
9912 // For any little-endian targets with neon, we can support unaligned ld/st
9913 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9914 // A big-endian target may also explicitly support unaligned accesses
9915 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9925 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9926 unsigned AlignCheck) {
9927 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9928 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9931 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9932 unsigned DstAlign, unsigned SrcAlign,
9933 bool IsMemset, bool ZeroMemset,
9935 MachineFunction &MF) const {
9936 const Function *F = MF.getFunction();
9938 // See if we can use NEON instructions for this...
9939 if ((!IsMemset || ZeroMemset) &&
9940 Subtarget->hasNEON() &&
9941 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9942 Attribute::NoImplicitFloat)) {
9945 (memOpAlign(SrcAlign, DstAlign, 16) ||
9946 (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9948 } else if (Size >= 8 &&
9949 (memOpAlign(SrcAlign, DstAlign, 8) ||
9950 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9956 // Lowering to i32/i16 if the size permits.
9962 // Let the target-independent logic figure it out.
9966 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9967 if (Val.getOpcode() != ISD::LOAD)
9970 EVT VT1 = Val.getValueType();
9971 if (!VT1.isSimple() || !VT1.isInteger() ||
9972 !VT2.isSimple() || !VT2.isInteger())
9975 switch (VT1.getSimpleVT().SimpleTy) {
9980 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9987 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9988 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9991 if (!isTypeLegal(EVT::getEVT(Ty1)))
9994 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9996 // Assuming the caller doesn't have a zeroext or signext return parameter,
9997 // truncation all the way down to i1 is valid.
10002 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10006 unsigned Scale = 1;
10007 switch (VT.getSimpleVT().SimpleTy) {
10008 default: return false;
10023 if ((V & (Scale - 1)) != 0)
10026 return V == (V & ((1LL << 5) - 1));
10029 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10030 const ARMSubtarget *Subtarget) {
10031 bool isNeg = false;
10037 switch (VT.getSimpleVT().SimpleTy) {
10038 default: return false;
10043 // + imm12 or - imm8
10045 return V == (V & ((1LL << 8) - 1));
10046 return V == (V & ((1LL << 12) - 1));
10049 // Same as ARM mode. FIXME: NEON?
10050 if (!Subtarget->hasVFP2())
10055 return V == (V & ((1LL << 8) - 1));
10059 /// isLegalAddressImmediate - Return true if the integer value can be used
10060 /// as the offset of the target addressing mode for load / store of the
10062 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10063 const ARMSubtarget *Subtarget) {
10067 if (!VT.isSimple())
10070 if (Subtarget->isThumb1Only())
10071 return isLegalT1AddressImmediate(V, VT);
10072 else if (Subtarget->isThumb2())
10073 return isLegalT2AddressImmediate(V, VT, Subtarget);
10078 switch (VT.getSimpleVT().SimpleTy) {
10079 default: return false;
10084 return V == (V & ((1LL << 12) - 1));
10087 return V == (V & ((1LL << 8) - 1));
10090 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10095 return V == (V & ((1LL << 8) - 1));
10099 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10101 int Scale = AM.Scale;
10105 switch (VT.getSimpleVT().SimpleTy) {
10106 default: return false;
10114 Scale = Scale & ~1;
10115 return Scale == 2 || Scale == 4 || Scale == 8;
10118 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10122 // Note, we allow "void" uses (basically, uses that aren't loads or
10123 // stores), because arm allows folding a scale into many arithmetic
10124 // operations. This should be made more precise and revisited later.
10126 // Allow r << imm, but the imm has to be a multiple of two.
10127 if (Scale & 1) return false;
10128 return isPowerOf2_32(Scale);
10132 /// isLegalAddressingMode - Return true if the addressing mode represented
10133 /// by AM is legal for this target, for a load/store of the specified type.
10134 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10136 EVT VT = getValueType(Ty, true);
10137 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10140 // Can never fold addr of global into load/store.
10144 switch (AM.Scale) {
10145 case 0: // no scale reg, must be "r+i" or "r", or "i".
10148 if (Subtarget->isThumb1Only())
10152 // ARM doesn't support any R+R*scale+imm addr modes.
10156 if (!VT.isSimple())
10159 if (Subtarget->isThumb2())
10160 return isLegalT2ScaledAddressingMode(AM, VT);
10162 int Scale = AM.Scale;
10163 switch (VT.getSimpleVT().SimpleTy) {
10164 default: return false;
10168 if (Scale < 0) Scale = -Scale;
10172 return isPowerOf2_32(Scale & ~1);
10176 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10181 // Note, we allow "void" uses (basically, uses that aren't loads or
10182 // stores), because arm allows folding a scale into many arithmetic
10183 // operations. This should be made more precise and revisited later.
10185 // Allow r << imm, but the imm has to be a multiple of two.
10186 if (Scale & 1) return false;
10187 return isPowerOf2_32(Scale);
10193 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10194 /// icmp immediate, that is the target has icmp instructions which can compare
10195 /// a register against the immediate without having to materialize the
10196 /// immediate into a register.
10197 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10198 // Thumb2 and ARM modes can use cmn for negative immediates.
10199 if (!Subtarget->isThumb())
10200 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10201 if (Subtarget->isThumb2())
10202 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10203 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10204 return Imm >= 0 && Imm <= 255;
10207 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10208 /// *or sub* immediate, that is the target has add or sub instructions which can
10209 /// add a register with the immediate without having to materialize the
10210 /// immediate into a register.
10211 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10212 // Same encoding for add/sub, just flip the sign.
10213 int64_t AbsImm = llvm::abs64(Imm);
10214 if (!Subtarget->isThumb())
10215 return ARM_AM::getSOImmVal(AbsImm) != -1;
10216 if (Subtarget->isThumb2())
10217 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10218 // Thumb1 only has 8-bit unsigned immediate.
10219 return AbsImm >= 0 && AbsImm <= 255;
10222 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10223 bool isSEXTLoad, SDValue &Base,
10224 SDValue &Offset, bool &isInc,
10225 SelectionDAG &DAG) {
10226 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10229 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10230 // AddressingMode 3
10231 Base = Ptr->getOperand(0);
10232 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10233 int RHSC = (int)RHS->getZExtValue();
10234 if (RHSC < 0 && RHSC > -256) {
10235 assert(Ptr->getOpcode() == ISD::ADD);
10237 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10241 isInc = (Ptr->getOpcode() == ISD::ADD);
10242 Offset = Ptr->getOperand(1);
10244 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10245 // AddressingMode 2
10246 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10247 int RHSC = (int)RHS->getZExtValue();
10248 if (RHSC < 0 && RHSC > -0x1000) {
10249 assert(Ptr->getOpcode() == ISD::ADD);
10251 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10252 Base = Ptr->getOperand(0);
10257 if (Ptr->getOpcode() == ISD::ADD) {
10259 ARM_AM::ShiftOpc ShOpcVal=
10260 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10261 if (ShOpcVal != ARM_AM::no_shift) {
10262 Base = Ptr->getOperand(1);
10263 Offset = Ptr->getOperand(0);
10265 Base = Ptr->getOperand(0);
10266 Offset = Ptr->getOperand(1);
10271 isInc = (Ptr->getOpcode() == ISD::ADD);
10272 Base = Ptr->getOperand(0);
10273 Offset = Ptr->getOperand(1);
10277 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10281 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10282 bool isSEXTLoad, SDValue &Base,
10283 SDValue &Offset, bool &isInc,
10284 SelectionDAG &DAG) {
10285 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10288 Base = Ptr->getOperand(0);
10289 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10290 int RHSC = (int)RHS->getZExtValue();
10291 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10292 assert(Ptr->getOpcode() == ISD::ADD);
10294 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10296 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10297 isInc = Ptr->getOpcode() == ISD::ADD;
10298 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10306 /// getPreIndexedAddressParts - returns true by value, base pointer and
10307 /// offset pointer and addressing mode by reference if the node's address
10308 /// can be legally represented as pre-indexed load / store address.
10310 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10312 ISD::MemIndexedMode &AM,
10313 SelectionDAG &DAG) const {
10314 if (Subtarget->isThumb1Only())
10319 bool isSEXTLoad = false;
10320 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10321 Ptr = LD->getBasePtr();
10322 VT = LD->getMemoryVT();
10323 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10324 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10325 Ptr = ST->getBasePtr();
10326 VT = ST->getMemoryVT();
10331 bool isLegal = false;
10332 if (Subtarget->isThumb2())
10333 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10334 Offset, isInc, DAG);
10336 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10337 Offset, isInc, DAG);
10341 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10345 /// getPostIndexedAddressParts - returns true by value, base pointer and
10346 /// offset pointer and addressing mode by reference if this node can be
10347 /// combined with a load / store to form a post-indexed load / store.
10348 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10351 ISD::MemIndexedMode &AM,
10352 SelectionDAG &DAG) const {
10353 if (Subtarget->isThumb1Only())
10358 bool isSEXTLoad = false;
10359 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10360 VT = LD->getMemoryVT();
10361 Ptr = LD->getBasePtr();
10362 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10363 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10364 VT = ST->getMemoryVT();
10365 Ptr = ST->getBasePtr();
10370 bool isLegal = false;
10371 if (Subtarget->isThumb2())
10372 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10375 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10381 // Swap base ptr and offset to catch more post-index load / store when
10382 // it's legal. In Thumb2 mode, offset must be an immediate.
10383 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10384 !Subtarget->isThumb2())
10385 std::swap(Base, Offset);
10387 // Post-indexed load / store update the base pointer.
10392 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10396 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10399 const SelectionDAG &DAG,
10400 unsigned Depth) const {
10401 unsigned BitWidth = KnownOne.getBitWidth();
10402 KnownZero = KnownOne = APInt(BitWidth, 0);
10403 switch (Op.getOpcode()) {
10409 // These nodes' second result is a boolean
10410 if (Op.getResNo() == 0)
10412 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10414 case ARMISD::CMOV: {
10415 // Bits are known zero/one if known on the LHS and RHS.
10416 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10417 if (KnownZero == 0 && KnownOne == 0) return;
10419 APInt KnownZeroRHS, KnownOneRHS;
10420 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10421 KnownZero &= KnownZeroRHS;
10422 KnownOne &= KnownOneRHS;
10425 case ISD::INTRINSIC_W_CHAIN: {
10426 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10427 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10430 case Intrinsic::arm_ldaex:
10431 case Intrinsic::arm_ldrex: {
10432 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10433 unsigned MemBits = VT.getScalarType().getSizeInBits();
10434 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10442 //===----------------------------------------------------------------------===//
10443 // ARM Inline Assembly Support
10444 //===----------------------------------------------------------------------===//
10446 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10447 // Looking for "rev" which is V6+.
10448 if (!Subtarget->hasV6Ops())
10451 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10452 std::string AsmStr = IA->getAsmString();
10453 SmallVector<StringRef, 4> AsmPieces;
10454 SplitString(AsmStr, AsmPieces, ";\n");
10456 switch (AsmPieces.size()) {
10457 default: return false;
10459 AsmStr = AsmPieces[0];
10461 SplitString(AsmStr, AsmPieces, " \t,");
10464 if (AsmPieces.size() == 3 &&
10465 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10466 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10467 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10468 if (Ty && Ty->getBitWidth() == 32)
10469 return IntrinsicLowering::LowerToByteSwap(CI);
10477 /// getConstraintType - Given a constraint letter, return the type of
10478 /// constraint it is for this target.
10479 ARMTargetLowering::ConstraintType
10480 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10481 if (Constraint.size() == 1) {
10482 switch (Constraint[0]) {
10484 case 'l': return C_RegisterClass;
10485 case 'w': return C_RegisterClass;
10486 case 'h': return C_RegisterClass;
10487 case 'x': return C_RegisterClass;
10488 case 't': return C_RegisterClass;
10489 case 'j': return C_Other; // Constant for movw.
10490 // An address with a single base register. Due to the way we
10491 // currently handle addresses it is the same as an 'r' memory constraint.
10492 case 'Q': return C_Memory;
10494 } else if (Constraint.size() == 2) {
10495 switch (Constraint[0]) {
10497 // All 'U+' constraints are addresses.
10498 case 'U': return C_Memory;
10501 return TargetLowering::getConstraintType(Constraint);
10504 /// Examine constraint type and operand type and determine a weight value.
10505 /// This object must already have been set up with the operand type
10506 /// and the current alternative constraint selected.
10507 TargetLowering::ConstraintWeight
10508 ARMTargetLowering::getSingleConstraintMatchWeight(
10509 AsmOperandInfo &info, const char *constraint) const {
10510 ConstraintWeight weight = CW_Invalid;
10511 Value *CallOperandVal = info.CallOperandVal;
10512 // If we don't have a value, we can't do a match,
10513 // but allow it at the lowest weight.
10514 if (!CallOperandVal)
10516 Type *type = CallOperandVal->getType();
10517 // Look at the constraint type.
10518 switch (*constraint) {
10520 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10523 if (type->isIntegerTy()) {
10524 if (Subtarget->isThumb())
10525 weight = CW_SpecificReg;
10527 weight = CW_Register;
10531 if (type->isFloatingPointTy())
10532 weight = CW_Register;
10538 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10540 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10542 if (Constraint.size() == 1) {
10543 // GCC ARM Constraint Letters
10544 switch (Constraint[0]) {
10545 case 'l': // Low regs or general regs.
10546 if (Subtarget->isThumb())
10547 return RCPair(0U, &ARM::tGPRRegClass);
10548 return RCPair(0U, &ARM::GPRRegClass);
10549 case 'h': // High regs or no regs.
10550 if (Subtarget->isThumb())
10551 return RCPair(0U, &ARM::hGPRRegClass);
10554 return RCPair(0U, &ARM::GPRRegClass);
10556 if (VT == MVT::Other)
10558 if (VT == MVT::f32)
10559 return RCPair(0U, &ARM::SPRRegClass);
10560 if (VT.getSizeInBits() == 64)
10561 return RCPair(0U, &ARM::DPRRegClass);
10562 if (VT.getSizeInBits() == 128)
10563 return RCPair(0U, &ARM::QPRRegClass);
10566 if (VT == MVT::Other)
10568 if (VT == MVT::f32)
10569 return RCPair(0U, &ARM::SPR_8RegClass);
10570 if (VT.getSizeInBits() == 64)
10571 return RCPair(0U, &ARM::DPR_8RegClass);
10572 if (VT.getSizeInBits() == 128)
10573 return RCPair(0U, &ARM::QPR_8RegClass);
10576 if (VT == MVT::f32)
10577 return RCPair(0U, &ARM::SPRRegClass);
10581 if (StringRef("{cc}").equals_lower(Constraint))
10582 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10584 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10587 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10588 /// vector. If it is invalid, don't add anything to Ops.
10589 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10590 std::string &Constraint,
10591 std::vector<SDValue>&Ops,
10592 SelectionDAG &DAG) const {
10595 // Currently only support length 1 constraints.
10596 if (Constraint.length() != 1) return;
10598 char ConstraintLetter = Constraint[0];
10599 switch (ConstraintLetter) {
10602 case 'I': case 'J': case 'K': case 'L':
10603 case 'M': case 'N': case 'O':
10604 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10608 int64_t CVal64 = C->getSExtValue();
10609 int CVal = (int) CVal64;
10610 // None of these constraints allow values larger than 32 bits. Check
10611 // that the value fits in an int.
10612 if (CVal != CVal64)
10615 switch (ConstraintLetter) {
10617 // Constant suitable for movw, must be between 0 and
10619 if (Subtarget->hasV6T2Ops())
10620 if (CVal >= 0 && CVal <= 65535)
10624 if (Subtarget->isThumb1Only()) {
10625 // This must be a constant between 0 and 255, for ADD
10627 if (CVal >= 0 && CVal <= 255)
10629 } else if (Subtarget->isThumb2()) {
10630 // A constant that can be used as an immediate value in a
10631 // data-processing instruction.
10632 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10635 // A constant that can be used as an immediate value in a
10636 // data-processing instruction.
10637 if (ARM_AM::getSOImmVal(CVal) != -1)
10643 if (Subtarget->isThumb()) { // FIXME thumb2
10644 // This must be a constant between -255 and -1, for negated ADD
10645 // immediates. This can be used in GCC with an "n" modifier that
10646 // prints the negated value, for use with SUB instructions. It is
10647 // not useful otherwise but is implemented for compatibility.
10648 if (CVal >= -255 && CVal <= -1)
10651 // This must be a constant between -4095 and 4095. It is not clear
10652 // what this constraint is intended for. Implemented for
10653 // compatibility with GCC.
10654 if (CVal >= -4095 && CVal <= 4095)
10660 if (Subtarget->isThumb1Only()) {
10661 // A 32-bit value where only one byte has a nonzero value. Exclude
10662 // zero to match GCC. This constraint is used by GCC internally for
10663 // constants that can be loaded with a move/shift combination.
10664 // It is not useful otherwise but is implemented for compatibility.
10665 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10667 } else if (Subtarget->isThumb2()) {
10668 // A constant whose bitwise inverse can be used as an immediate
10669 // value in a data-processing instruction. This can be used in GCC
10670 // with a "B" modifier that prints the inverted value, for use with
10671 // BIC and MVN instructions. It is not useful otherwise but is
10672 // implemented for compatibility.
10673 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10676 // A constant whose bitwise inverse can be used as an immediate
10677 // value in a data-processing instruction. This can be used in GCC
10678 // with a "B" modifier that prints the inverted value, for use with
10679 // BIC and MVN instructions. It is not useful otherwise but is
10680 // implemented for compatibility.
10681 if (ARM_AM::getSOImmVal(~CVal) != -1)
10687 if (Subtarget->isThumb1Only()) {
10688 // This must be a constant between -7 and 7,
10689 // for 3-operand ADD/SUB immediate instructions.
10690 if (CVal >= -7 && CVal < 7)
10692 } else if (Subtarget->isThumb2()) {
10693 // A constant whose negation can be used as an immediate value in a
10694 // data-processing instruction. This can be used in GCC with an "n"
10695 // modifier that prints the negated value, for use with SUB
10696 // instructions. It is not useful otherwise but is implemented for
10698 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10701 // A constant whose negation can be used as an immediate value in a
10702 // data-processing instruction. This can be used in GCC with an "n"
10703 // modifier that prints the negated value, for use with SUB
10704 // instructions. It is not useful otherwise but is implemented for
10706 if (ARM_AM::getSOImmVal(-CVal) != -1)
10712 if (Subtarget->isThumb()) { // FIXME thumb2
10713 // This must be a multiple of 4 between 0 and 1020, for
10714 // ADD sp + immediate.
10715 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10718 // A power of two or a constant between 0 and 32. This is used in
10719 // GCC for the shift amount on shifted register operands, but it is
10720 // useful in general for any shift amounts.
10721 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10727 if (Subtarget->isThumb()) { // FIXME thumb2
10728 // This must be a constant between 0 and 31, for shift amounts.
10729 if (CVal >= 0 && CVal <= 31)
10735 if (Subtarget->isThumb()) { // FIXME thumb2
10736 // This must be a multiple of 4 between -508 and 508, for
10737 // ADD/SUB sp = sp + immediate.
10738 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10743 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10747 if (Result.getNode()) {
10748 Ops.push_back(Result);
10751 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10754 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10755 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10756 unsigned Opcode = Op->getOpcode();
10757 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10758 "Invalid opcode for Div/Rem lowering");
10759 bool isSigned = (Opcode == ISD::SDIVREM);
10760 EVT VT = Op->getValueType(0);
10761 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10764 switch (VT.getSimpleVT().SimpleTy) {
10765 default: llvm_unreachable("Unexpected request for libcall!");
10766 case MVT::i8: LC = isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10767 case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10768 case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10769 case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10772 SDValue InChain = DAG.getEntryNode();
10774 TargetLowering::ArgListTy Args;
10775 TargetLowering::ArgListEntry Entry;
10776 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10777 EVT ArgVT = Op->getOperand(i).getValueType();
10778 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10779 Entry.Node = Op->getOperand(i);
10781 Entry.isSExt = isSigned;
10782 Entry.isZExt = !isSigned;
10783 Args.push_back(Entry);
10786 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10789 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10792 TargetLowering::CallLoweringInfo CLI(DAG);
10793 CLI.setDebugLoc(dl).setChain(InChain)
10794 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10795 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10797 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10798 return CallInfo.first;
10802 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10803 assert(Subtarget->isTargetWindows() && "unsupported target platform");
10807 SDValue Chain = Op.getOperand(0);
10808 SDValue Size = Op.getOperand(1);
10810 SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10811 DAG.getConstant(2, MVT::i32));
10814 Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10815 Flag = Chain.getValue(1);
10817 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10818 Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10820 SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10821 Chain = NewSP.getValue(1);
10823 SDValue Ops[2] = { NewSP, Chain };
10824 return DAG.getMergeValues(Ops, DL);
10827 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10828 assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10829 "Unexpected type for custom-lowering FP_EXTEND");
10832 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10834 SDValue SrcVal = Op.getOperand(0);
10835 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10836 /*isSigned*/ false, SDLoc(Op)).first;
10839 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10840 assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10841 Subtarget->isFPOnlySP() &&
10842 "Unexpected type for custom-lowering FP_ROUND");
10845 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10847 SDValue SrcVal = Op.getOperand(0);
10848 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10849 /*isSigned*/ false, SDLoc(Op)).first;
10853 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10854 // The ARM target isn't yet aware of offsets.
10858 bool ARM::isBitFieldInvertedMask(unsigned v) {
10859 if (v == 0xffffffff)
10862 // there can be 1's on either or both "outsides", all the "inside"
10863 // bits must be 0's
10864 unsigned TO = CountTrailingOnes_32(v);
10865 unsigned LO = CountLeadingOnes_32(v);
10866 v = (v >> TO) << TO;
10867 v = (v << LO) >> LO;
10871 /// isFPImmLegal - Returns true if the target can instruction select the
10872 /// specified FP immediate natively. If false, the legalizer will
10873 /// materialize the FP immediate as a load from a constant pool.
10874 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10875 if (!Subtarget->hasVFP3())
10877 if (VT == MVT::f32)
10878 return ARM_AM::getFP32Imm(Imm) != -1;
10879 if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10880 return ARM_AM::getFP64Imm(Imm) != -1;
10884 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10885 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10886 /// specified in the intrinsic calls.
10887 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10889 unsigned Intrinsic) const {
10890 switch (Intrinsic) {
10891 case Intrinsic::arm_neon_vld1:
10892 case Intrinsic::arm_neon_vld2:
10893 case Intrinsic::arm_neon_vld3:
10894 case Intrinsic::arm_neon_vld4:
10895 case Intrinsic::arm_neon_vld2lane:
10896 case Intrinsic::arm_neon_vld3lane:
10897 case Intrinsic::arm_neon_vld4lane: {
10898 Info.opc = ISD::INTRINSIC_W_CHAIN;
10899 // Conservatively set memVT to the entire set of vectors loaded.
10900 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10901 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10902 Info.ptrVal = I.getArgOperand(0);
10904 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10905 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10906 Info.vol = false; // volatile loads with NEON intrinsics not supported
10907 Info.readMem = true;
10908 Info.writeMem = false;
10911 case Intrinsic::arm_neon_vst1:
10912 case Intrinsic::arm_neon_vst2:
10913 case Intrinsic::arm_neon_vst3:
10914 case Intrinsic::arm_neon_vst4:
10915 case Intrinsic::arm_neon_vst2lane:
10916 case Intrinsic::arm_neon_vst3lane:
10917 case Intrinsic::arm_neon_vst4lane: {
10918 Info.opc = ISD::INTRINSIC_VOID;
10919 // Conservatively set memVT to the entire set of vectors stored.
10920 unsigned NumElts = 0;
10921 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10922 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10923 if (!ArgTy->isVectorTy())
10925 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10927 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10928 Info.ptrVal = I.getArgOperand(0);
10930 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10931 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10932 Info.vol = false; // volatile stores with NEON intrinsics not supported
10933 Info.readMem = false;
10934 Info.writeMem = true;
10937 case Intrinsic::arm_ldaex:
10938 case Intrinsic::arm_ldrex: {
10939 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10940 Info.opc = ISD::INTRINSIC_W_CHAIN;
10941 Info.memVT = MVT::getVT(PtrTy->getElementType());
10942 Info.ptrVal = I.getArgOperand(0);
10944 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10946 Info.readMem = true;
10947 Info.writeMem = false;
10950 case Intrinsic::arm_stlex:
10951 case Intrinsic::arm_strex: {
10952 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10953 Info.opc = ISD::INTRINSIC_W_CHAIN;
10954 Info.memVT = MVT::getVT(PtrTy->getElementType());
10955 Info.ptrVal = I.getArgOperand(1);
10957 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10959 Info.readMem = false;
10960 Info.writeMem = true;
10963 case Intrinsic::arm_stlexd:
10964 case Intrinsic::arm_strexd: {
10965 Info.opc = ISD::INTRINSIC_W_CHAIN;
10966 Info.memVT = MVT::i64;
10967 Info.ptrVal = I.getArgOperand(2);
10971 Info.readMem = false;
10972 Info.writeMem = true;
10975 case Intrinsic::arm_ldaexd:
10976 case Intrinsic::arm_ldrexd: {
10977 Info.opc = ISD::INTRINSIC_W_CHAIN;
10978 Info.memVT = MVT::i64;
10979 Info.ptrVal = I.getArgOperand(0);
10983 Info.readMem = true;
10984 Info.writeMem = false;
10994 /// \brief Returns true if it is beneficial to convert a load of a constant
10995 /// to just the constant itself.
10996 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10998 assert(Ty->isIntegerTy());
11000 unsigned Bits = Ty->getPrimitiveSizeInBits();
11001 if (Bits == 0 || Bits > 32)
11006 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11008 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11009 ARM_MB::MemBOpt Domain) const {
11010 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11012 // First, if the target has no DMB, see what fallback we can use.
11013 if (!Subtarget->hasDataBarrier()) {
11014 // Some ARMv6 cpus can support data barriers with an mcr instruction.
11015 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11017 if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11018 Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11019 Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11020 Builder.getInt32(0), Builder.getInt32(7),
11021 Builder.getInt32(10), Builder.getInt32(5)};
11022 return Builder.CreateCall(MCR, args);
11024 // Instead of using barriers, atomic accesses on these subtargets use
11026 llvm_unreachable("makeDMB on a target so old that it has no barriers");
11029 Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11030 // Only a full system barrier exists in the M-class architectures.
11031 Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11032 Constant *CDomain = Builder.getInt32(Domain);
11033 return Builder.CreateCall(DMB, CDomain);
11037 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11038 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11039 AtomicOrdering Ord, bool IsStore,
11040 bool IsLoad) const {
11041 if (!getInsertFencesForAtomic())
11047 llvm_unreachable("Invalid fence: unordered/non-atomic");
11050 return nullptr; // Nothing to do
11051 case SequentiallyConsistent:
11053 return nullptr; // Nothing to do
11056 case AcquireRelease:
11057 if (Subtarget->isSwift())
11058 return makeDMB(Builder, ARM_MB::ISHST);
11059 // FIXME: add a comment with a link to documentation justifying this.
11061 return makeDMB(Builder, ARM_MB::ISH);
11063 llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11066 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11067 AtomicOrdering Ord, bool IsStore,
11068 bool IsLoad) const {
11069 if (!getInsertFencesForAtomic())
11075 llvm_unreachable("Invalid fence: unordered/not-atomic");
11078 return nullptr; // Nothing to do
11080 case AcquireRelease:
11081 case SequentiallyConsistent:
11082 return makeDMB(Builder, ARM_MB::ISH);
11084 llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11087 // Loads and stores less than 64-bits are already atomic; ones above that
11088 // are doomed anyway, so defer to the default libcall and blame the OS when
11089 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11090 // anything for those.
11091 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11092 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11093 return (Size == 64) && !Subtarget->isMClass();
11096 // Loads and stores less than 64-bits are already atomic; ones above that
11097 // are doomed anyway, so defer to the default libcall and blame the OS when
11098 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11099 // anything for those.
11100 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11101 // guarantee, see DDI0406C ARM architecture reference manual,
11102 // sections A8.8.72-74 LDRD)
11103 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11104 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11105 return (Size == 64) && !Subtarget->isMClass();
11108 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11109 // and up to 64 bits on the non-M profiles
11110 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11111 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11112 return Size <= (Subtarget->isMClass() ? 32U : 64U);
11115 // This has so far only been implemented for MachO.
11116 bool ARMTargetLowering::useLoadStackGuardNode() const {
11117 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11120 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11121 AtomicOrdering Ord) const {
11122 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11123 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11124 bool IsAcquire = isAtLeastAcquire(Ord);
11126 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11127 // intrinsic must return {i32, i32} and we have to recombine them into a
11128 // single i64 here.
11129 if (ValTy->getPrimitiveSizeInBits() == 64) {
11130 Intrinsic::ID Int =
11131 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11132 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11134 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11135 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11137 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11138 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11139 if (!Subtarget->isLittle())
11140 std::swap (Lo, Hi);
11141 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11142 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11143 return Builder.CreateOr(
11144 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11147 Type *Tys[] = { Addr->getType() };
11148 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11149 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11151 return Builder.CreateTruncOrBitCast(
11152 Builder.CreateCall(Ldrex, Addr),
11153 cast<PointerType>(Addr->getType())->getElementType());
11156 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11158 AtomicOrdering Ord) const {
11159 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11160 bool IsRelease = isAtLeastRelease(Ord);
11162 // Since the intrinsics must have legal type, the i64 intrinsics take two
11163 // parameters: "i32, i32". We must marshal Val into the appropriate form
11164 // before the call.
11165 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11166 Intrinsic::ID Int =
11167 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11168 Function *Strex = Intrinsic::getDeclaration(M, Int);
11169 Type *Int32Ty = Type::getInt32Ty(M->getContext());
11171 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11172 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11173 if (!Subtarget->isLittle())
11174 std::swap (Lo, Hi);
11175 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11176 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11179 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11180 Type *Tys[] = { Addr->getType() };
11181 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11183 return Builder.CreateCall2(
11184 Strex, Builder.CreateZExtOrBitCast(
11185 Val, Strex->getFunctionType()->getParamType(0)),
11197 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11198 uint64_t &Members) {
11199 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11200 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11201 uint64_t SubMembers = 0;
11202 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11204 Members += SubMembers;
11206 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11207 uint64_t SubMembers = 0;
11208 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11210 Members += SubMembers * AT->getNumElements();
11211 } else if (Ty->isFloatTy()) {
11212 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11216 } else if (Ty->isDoubleTy()) {
11217 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11221 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11228 return VT->getBitWidth() == 64;
11230 return VT->getBitWidth() == 128;
11232 switch (VT->getBitWidth()) {
11245 return (Members > 0 && Members <= 4);
11248 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11249 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11250 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11251 if (getEffectiveCallingConv(CallConv, isVarArg) !=
11252 CallingConv::ARM_AAPCS_VFP)
11255 HABaseType Base = HA_UNKNOWN;
11256 uint64_t Members = 0;
11257 bool result = isHomogeneousAggregate(Ty, Base, Members);
11258 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());