1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
53 #define DEBUG_TYPE "arm-isel"
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61 cl::desc("Generate calls via indirect call instructions"),
65 ARMInterworking("arm-interworking", cl::Hidden,
66 cl::desc("Enable / disable ARM interworking (for debugging only)"),
70 class ARMCCState : public CCState {
72 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74 LLVMContext &C, ParmContext PC)
75 : CCState(CC, isVarArg, MF, TM, locs, C) {
76 assert(((PC == Call) || (PC == Prologue)) &&
77 "ARMCCState users must specify whether their context is call"
78 "or prologue generation.");
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86 ARM::R0, ARM::R1, ARM::R2, ARM::R3
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90 MVT PromotedBitwiseVT) {
91 if (VT != PromotedLdStVT) {
92 setOperationAction(ISD::LOAD, VT, Promote);
93 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95 setOperationAction(ISD::STORE, VT, Promote);
96 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
99 MVT ElemTy = VT.getVectorElementType();
100 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101 setOperationAction(ISD::SETCC, VT, Custom);
102 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104 if (ElemTy == MVT::i32) {
105 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
116 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
117 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
118 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119 setOperationAction(ISD::SELECT, VT, Expand);
120 setOperationAction(ISD::SELECT_CC, VT, Expand);
121 setOperationAction(ISD::VSELECT, VT, Expand);
122 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123 if (VT.isInteger()) {
124 setOperationAction(ISD::SHL, VT, Custom);
125 setOperationAction(ISD::SRA, VT, Custom);
126 setOperationAction(ISD::SRL, VT, Custom);
129 // Promote all bit-wise operations.
130 if (VT.isInteger() && VT != PromotedBitwiseVT) {
131 setOperationAction(ISD::AND, VT, Promote);
132 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133 setOperationAction(ISD::OR, VT, Promote);
134 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
135 setOperationAction(ISD::XOR, VT, Promote);
136 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
139 // Neon does not support vector divide/remainder operations.
140 setOperationAction(ISD::SDIV, VT, Expand);
141 setOperationAction(ISD::UDIV, VT, Expand);
142 setOperationAction(ISD::FDIV, VT, Expand);
143 setOperationAction(ISD::SREM, VT, Expand);
144 setOperationAction(ISD::UREM, VT, Expand);
145 setOperationAction(ISD::FREM, VT, Expand);
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149 addRegisterClass(VT, &ARM::DPRRegClass);
150 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPairRegClass);
155 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159 if (TT.isOSBinFormatMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TT.isOSWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168 Subtarget = &TM.getSubtarget<ARMSubtarget>();
169 RegInfo = TM.getRegisterInfo();
170 Itins = TM.getInstrItineraryData();
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 if (Subtarget->isTargetMachO()) {
175 // Uses VFP for Thumb libfuncs if available.
176 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178 // Single-precision floating-point arithmetic.
179 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184 // Double-precision floating-point arithmetic.
185 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190 // Single-precision comparisons.
191 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
198 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
200 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
209 // Double-precision comparisons.
210 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
217 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
219 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
228 // Floating-point to integer conversions.
229 // i64 conversions are done via library routines even when generating VFP
230 // instructions, so use the same ones.
231 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236 // Conversions between floating types.
237 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
240 // Integer to floating-point conversions.
241 // i64 conversions are done via library routines even when generating VFP
242 // instructions, so use the same ones.
243 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244 // e.g., __floatunsidf vs. __floatunssidfvfp.
245 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
252 // These libcalls are not available in 32-bit.
253 setLibcallName(RTLIB::SHL_I128, nullptr);
254 setLibcallName(RTLIB::SRL_I128, nullptr);
255 setLibcallName(RTLIB::SRA_I128, nullptr);
257 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258 !Subtarget->isTargetWindows()) {
259 static const struct {
260 const RTLIB::Libcall Op;
261 const char * const Name;
262 const CallingConv::ID CC;
263 const ISD::CondCode Cond;
265 // Double-precision floating-point arithmetic helper functions
266 // RTABI chapter 4.1.2, Table 2
267 { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268 { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269 { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270 { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275 { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276 { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277 { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278 { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279 { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280 { RTLIB::UO_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281 { RTLIB::O_F64, "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283 // Single-precision floating-point arithmetic helper functions
284 // RTABI chapter 4.1.2, Table 4
285 { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286 { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287 { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288 { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290 // Single-precision floating-point comparison helper functions
291 // RTABI chapter 4.1.2, Table 5
292 { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293 { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294 { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295 { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296 { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297 { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298 { RTLIB::UO_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299 { RTLIB::O_F32, "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301 // Floating-point to integer conversions.
302 // RTABI chapter 4.1.2, Table 6
303 { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304 { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305 { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306 { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307 { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308 { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309 { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310 { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312 // Conversions between floating types.
313 // RTABI chapter 4.1.2, Table 7
314 { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315 { RTLIB::FPEXT_F32_F64, "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317 // Integer to floating-point conversions.
318 // RTABI chapter 4.1.2, Table 8
319 { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320 { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321 { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322 { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323 { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324 { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325 { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326 { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328 // Long long helper functions
329 // RTABI chapter 4.2, Table 9
330 { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331 { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332 { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333 { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335 // Integer division functions
336 // RTABI chapter 4.3.1
337 { RTLIB::SDIV_I8, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338 { RTLIB::SDIV_I16, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339 { RTLIB::SDIV_I32, "__aeabi_idiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340 { RTLIB::SDIV_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 { RTLIB::UDIV_I8, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342 { RTLIB::UDIV_I16, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343 { RTLIB::UDIV_I32, "__aeabi_uidiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344 { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347 // RTABI chapter 4.3.4
348 { RTLIB::MEMCPY, "__aeabi_memcpy", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350 { RTLIB::MEMSET, "__aeabi_memset", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353 for (const auto &LC : LibraryCalls) {
354 setLibcallName(LC.Op, LC.Name);
355 setLibcallCallingConv(LC.Op, LC.CC);
356 if (LC.Cond != ISD::SETCC_INVALID)
357 setCmpLibcallCC(LC.Op, LC.Cond);
361 if (Subtarget->isTargetWindows()) {
362 static const struct {
363 const RTLIB::Libcall Op;
364 const char * const Name;
365 const CallingConv::ID CC;
367 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377 for (const auto &LC : LibraryCalls) {
378 setLibcallName(LC.Op, LC.Name);
379 setLibcallCallingConv(LC.Op, LC.CC);
383 // Use divmod compiler-rt calls for iOS 5.0 and later.
384 if (Subtarget->getTargetTriple().isiOS() &&
385 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390 if (Subtarget->isThumb1Only())
391 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
393 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395 !Subtarget->isThumb1Only()) {
396 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397 if (!Subtarget->isFPOnlySP())
398 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
400 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
403 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407 setTruncStoreAction((MVT::SimpleValueType)VT,
408 (MVT::SimpleValueType)InnerVT, Expand);
409 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
413 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
418 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
421 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
424 if (Subtarget->hasNEON()) {
425 addDRTypeForNEON(MVT::v2f32);
426 addDRTypeForNEON(MVT::v8i8);
427 addDRTypeForNEON(MVT::v4i16);
428 addDRTypeForNEON(MVT::v2i32);
429 addDRTypeForNEON(MVT::v1i64);
431 addQRTypeForNEON(MVT::v4f32);
432 addQRTypeForNEON(MVT::v2f64);
433 addQRTypeForNEON(MVT::v16i8);
434 addQRTypeForNEON(MVT::v8i16);
435 addQRTypeForNEON(MVT::v4i32);
436 addQRTypeForNEON(MVT::v2i64);
438 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439 // neither Neon nor VFP support any arithmetic operations on it.
440 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441 // supported for v4f32.
442 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445 // FIXME: Code duplication: FDIV and FREM are expanded always, see
446 // ARMTargetLowering::addTypeForNEON method for details.
447 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449 // FIXME: Create unittest.
450 // In another words, find a way when "copysign" appears in DAG with vector
452 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453 // FIXME: Code duplication: SETCC has custom operation action, see
454 // ARMTargetLowering::addTypeForNEON method for details.
455 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456 // FIXME: Create unittest for FNEG and for FABS.
457 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
477 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
493 // Mark v2f32 intrinsics.
494 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
510 // Neon does not support some operations on v1i64 and v2i64 types.
511 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512 // Custom handling for some quad-vector types to detect VMULL.
513 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516 // Custom handling for some vector types to avoid expensive expansions
517 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524 // a destination type that is wider than the source, and nor does
525 // it have a FP_TO_[SU]INT instruction with a narrower destination than
527 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
532 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
533 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
535 // NEON does not have single instruction CTPOP for vectors with element
536 // types wider than 8-bits. However, custom lowering can leverage the
537 // v8i8/v16i8 vcnt instruction.
538 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
539 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
540 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
541 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
543 // NEON only has FMA instructions as of VFP4.
544 if (!Subtarget->hasVFP4()) {
545 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
549 setTargetDAGCombine(ISD::INTRINSIC_VOID);
550 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552 setTargetDAGCombine(ISD::SHL);
553 setTargetDAGCombine(ISD::SRL);
554 setTargetDAGCombine(ISD::SRA);
555 setTargetDAGCombine(ISD::SIGN_EXTEND);
556 setTargetDAGCombine(ISD::ZERO_EXTEND);
557 setTargetDAGCombine(ISD::ANY_EXTEND);
558 setTargetDAGCombine(ISD::SELECT_CC);
559 setTargetDAGCombine(ISD::BUILD_VECTOR);
560 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562 setTargetDAGCombine(ISD::STORE);
563 setTargetDAGCombine(ISD::FP_TO_SINT);
564 setTargetDAGCombine(ISD::FP_TO_UINT);
565 setTargetDAGCombine(ISD::FDIV);
567 // It is legal to extload from v4i8 to v4i16 or v4i32.
568 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569 MVT::v4i16, MVT::v2i16,
571 for (unsigned i = 0; i < 6; ++i) {
572 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
578 // ARM and Thumb2 support UMLAL/SMLAL.
579 if (!Subtarget->isThumb1Only())
580 setTargetDAGCombine(ISD::ADDC);
583 computeRegisterProperties();
585 // ARM does not have f32 extending load.
586 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
588 // ARM does not have i1 sign extending load.
589 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
591 // ARM supports all 4 flavors of integer indexed load / store.
592 if (!Subtarget->isThumb1Only()) {
593 for (unsigned im = (unsigned)ISD::PRE_INC;
594 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595 setIndexedLoadAction(im, MVT::i1, Legal);
596 setIndexedLoadAction(im, MVT::i8, Legal);
597 setIndexedLoadAction(im, MVT::i16, Legal);
598 setIndexedLoadAction(im, MVT::i32, Legal);
599 setIndexedStoreAction(im, MVT::i1, Legal);
600 setIndexedStoreAction(im, MVT::i8, Legal);
601 setIndexedStoreAction(im, MVT::i16, Legal);
602 setIndexedStoreAction(im, MVT::i32, Legal);
606 setOperationAction(ISD::SADDO, MVT::i32, Custom);
607 setOperationAction(ISD::UADDO, MVT::i32, Custom);
608 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609 setOperationAction(ISD::USUBO, MVT::i32, Custom);
611 // i64 operation support.
612 setOperationAction(ISD::MUL, MVT::i64, Expand);
613 setOperationAction(ISD::MULHU, MVT::i32, Expand);
614 if (Subtarget->isThumb1Only()) {
615 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
618 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620 setOperationAction(ISD::MULHS, MVT::i32, Expand);
622 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625 setOperationAction(ISD::SRL, MVT::i64, Custom);
626 setOperationAction(ISD::SRA, MVT::i64, Custom);
628 if (!Subtarget->isThumb1Only()) {
629 // FIXME: We should do this for Thumb1 as well.
630 setOperationAction(ISD::ADDC, MVT::i32, Custom);
631 setOperationAction(ISD::ADDE, MVT::i32, Custom);
632 setOperationAction(ISD::SUBC, MVT::i32, Custom);
633 setOperationAction(ISD::SUBE, MVT::i32, Custom);
636 // ARM does not have ROTL.
637 setOperationAction(ISD::ROTL, MVT::i32, Expand);
638 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
639 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
643 // These just redirect to CTTZ and CTLZ on ARM.
644 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
645 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
647 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
649 // Only ARMv6 has BSWAP.
650 if (!Subtarget->hasV6Ops())
651 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
653 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655 // These are expanded into libcalls if the cpu doesn't have HW divider.
656 setOperationAction(ISD::SDIV, MVT::i32, Expand);
657 setOperationAction(ISD::UDIV, MVT::i32, Expand);
660 // FIXME: Also set divmod for SREM on EABI
661 setOperationAction(ISD::SREM, MVT::i32, Expand);
662 setOperationAction(ISD::UREM, MVT::i32, Expand);
663 // Register based DivRem for AEABI (RTABI 4.2)
664 if (Subtarget->isTargetAEABI()) {
665 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
666 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
670 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
674 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
683 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
686 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
690 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
691 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
692 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
696 setOperationAction(ISD::TRAP, MVT::Other, Legal);
698 // Use the default implementation.
699 setOperationAction(ISD::VASTART, MVT::Other, Custom);
700 setOperationAction(ISD::VAARG, MVT::Other, Expand);
701 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
702 setOperationAction(ISD::VAEND, MVT::Other, Expand);
703 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
704 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
706 if (!Subtarget->isTargetMachO()) {
707 // Non-MachO platforms may return values in these registers via the
708 // personality function.
709 setExceptionPointerRegister(ARM::R0);
710 setExceptionSelectorRegister(ARM::R1);
713 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
714 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
715 // the default expansion.
716 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
717 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
718 // to ldrex/strex loops already.
719 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
721 // On v8, we have particularly efficient implementations of atomic fences
722 // if they can be combined with nearby atomic loads and stores.
723 if (!Subtarget->hasV8Ops()) {
724 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
725 setInsertFencesForAtomic(true);
728 // If there's anything we can use as a barrier, go through custom lowering
730 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
731 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
733 // Set them all for expansion, which will force libcalls.
734 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
735 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
736 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
737 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
738 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
739 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
740 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
741 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
742 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
743 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
744 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
745 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
746 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
747 // Unordered/Monotonic case.
748 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
749 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
752 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
754 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
755 if (!Subtarget->hasV6Ops()) {
756 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
757 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
759 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
761 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
762 !Subtarget->isThumb1Only()) {
763 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
764 // iff target supports vfp2.
765 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
766 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
769 // We want to custom lower some of our intrinsics.
770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
771 if (Subtarget->isTargetDarwin()) {
772 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
773 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
774 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
777 setOperationAction(ISD::SETCC, MVT::i32, Expand);
778 setOperationAction(ISD::SETCC, MVT::f32, Expand);
779 setOperationAction(ISD::SETCC, MVT::f64, Expand);
780 setOperationAction(ISD::SELECT, MVT::i32, Custom);
781 setOperationAction(ISD::SELECT, MVT::f32, Custom);
782 setOperationAction(ISD::SELECT, MVT::f64, Custom);
783 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
784 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
785 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
787 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
788 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
789 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
790 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
791 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
793 // We don't support sin/cos/fmod/copysign/pow
794 setOperationAction(ISD::FSIN, MVT::f64, Expand);
795 setOperationAction(ISD::FSIN, MVT::f32, Expand);
796 setOperationAction(ISD::FCOS, MVT::f32, Expand);
797 setOperationAction(ISD::FCOS, MVT::f64, Expand);
798 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
799 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
800 setOperationAction(ISD::FREM, MVT::f64, Expand);
801 setOperationAction(ISD::FREM, MVT::f32, Expand);
802 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
803 !Subtarget->isThumb1Only()) {
804 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
805 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
807 setOperationAction(ISD::FPOW, MVT::f64, Expand);
808 setOperationAction(ISD::FPOW, MVT::f32, Expand);
810 if (!Subtarget->hasVFP4()) {
811 setOperationAction(ISD::FMA, MVT::f64, Expand);
812 setOperationAction(ISD::FMA, MVT::f32, Expand);
815 // Various VFP goodness
816 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
817 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
818 if (Subtarget->hasVFP2()) {
819 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
820 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
821 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
822 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
824 // Special handling for half-precision FP.
825 if (!Subtarget->hasFP16()) {
826 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
827 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
831 // Combine sin / cos into one node or libcall if possible.
832 if (Subtarget->hasSinCos()) {
833 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
834 setLibcallName(RTLIB::SINCOS_F64, "sincos");
835 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
836 // For iOS, we don't want to the normal expansion of a libcall to
837 // sincos. We want to issue a libcall to __sincos_stret.
838 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
839 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
843 // We have target-specific dag combine patterns for the following nodes:
844 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
845 setTargetDAGCombine(ISD::ADD);
846 setTargetDAGCombine(ISD::SUB);
847 setTargetDAGCombine(ISD::MUL);
848 setTargetDAGCombine(ISD::AND);
849 setTargetDAGCombine(ISD::OR);
850 setTargetDAGCombine(ISD::XOR);
852 if (Subtarget->hasV6Ops())
853 setTargetDAGCombine(ISD::SRL);
855 setStackPointerRegisterToSaveRestore(ARM::SP);
857 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
858 !Subtarget->hasVFP2())
859 setSchedulingPreference(Sched::RegPressure);
861 setSchedulingPreference(Sched::Hybrid);
863 //// temporary - rewrite interface to use type
864 MaxStoresPerMemset = 8;
865 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
866 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
867 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
868 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
869 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
871 // On ARM arguments smaller than 4 bytes are extended, so all arguments
872 // are at least 4 bytes aligned.
873 setMinStackArgumentAlignment(4);
875 // Prefer likely predicted branches to selects on out-of-order cores.
876 PredictableSelectIsExpensive = Subtarget->isLikeA9();
878 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
881 // FIXME: It might make sense to define the representative register class as the
882 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
883 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
884 // SPR's representative would be DPR_VFP2. This should work well if register
885 // pressure tracking were modified such that a register use would increment the
886 // pressure of the register class's representative and all of it's super
887 // classes' representatives transitively. We have not implemented this because
888 // of the difficulty prior to coalescing of modeling operand register classes
889 // due to the common occurrence of cross class copies and subregister insertions
891 std::pair<const TargetRegisterClass*, uint8_t>
892 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
893 const TargetRegisterClass *RRC = nullptr;
895 switch (VT.SimpleTy) {
897 return TargetLowering::findRepresentativeClass(VT);
898 // Use DPR as representative register class for all floating point
899 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
900 // the cost is 1 for both f32 and f64.
901 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
902 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
903 RRC = &ARM::DPRRegClass;
904 // When NEON is used for SP, only half of the register file is available
905 // because operations that define both SP and DP results will be constrained
906 // to the VFP2 class (D0-D15). We currently model this constraint prior to
907 // coalescing by double-counting the SP regs. See the FIXME above.
908 if (Subtarget->useNEONForSinglePrecisionFP())
911 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
912 case MVT::v4f32: case MVT::v2f64:
913 RRC = &ARM::DPRRegClass;
917 RRC = &ARM::DPRRegClass;
921 RRC = &ARM::DPRRegClass;
925 return std::make_pair(RRC, Cost);
928 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
930 default: return nullptr;
931 case ARMISD::Wrapper: return "ARMISD::Wrapper";
932 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
933 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
934 case ARMISD::CALL: return "ARMISD::CALL";
935 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
936 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
937 case ARMISD::tCALL: return "ARMISD::tCALL";
938 case ARMISD::BRCOND: return "ARMISD::BRCOND";
939 case ARMISD::BR_JT: return "ARMISD::BR_JT";
940 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
941 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
942 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
943 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
944 case ARMISD::CMP: return "ARMISD::CMP";
945 case ARMISD::CMN: return "ARMISD::CMN";
946 case ARMISD::CMPZ: return "ARMISD::CMPZ";
947 case ARMISD::CMPFP: return "ARMISD::CMPFP";
948 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
949 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
950 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
952 case ARMISD::CMOV: return "ARMISD::CMOV";
954 case ARMISD::RBIT: return "ARMISD::RBIT";
956 case ARMISD::FTOSI: return "ARMISD::FTOSI";
957 case ARMISD::FTOUI: return "ARMISD::FTOUI";
958 case ARMISD::SITOF: return "ARMISD::SITOF";
959 case ARMISD::UITOF: return "ARMISD::UITOF";
961 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
962 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
963 case ARMISD::RRX: return "ARMISD::RRX";
965 case ARMISD::ADDC: return "ARMISD::ADDC";
966 case ARMISD::ADDE: return "ARMISD::ADDE";
967 case ARMISD::SUBC: return "ARMISD::SUBC";
968 case ARMISD::SUBE: return "ARMISD::SUBE";
970 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
971 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
973 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
974 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
976 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
978 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
980 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
982 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
984 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
986 case ARMISD::VCEQ: return "ARMISD::VCEQ";
987 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
988 case ARMISD::VCGE: return "ARMISD::VCGE";
989 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
990 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
991 case ARMISD::VCGEU: return "ARMISD::VCGEU";
992 case ARMISD::VCGT: return "ARMISD::VCGT";
993 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
994 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
995 case ARMISD::VCGTU: return "ARMISD::VCGTU";
996 case ARMISD::VTST: return "ARMISD::VTST";
998 case ARMISD::VSHL: return "ARMISD::VSHL";
999 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1000 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1001 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1002 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1003 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1004 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1005 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1006 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1007 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1008 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1009 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1010 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1011 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1012 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1013 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1014 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1015 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1016 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1017 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1018 case ARMISD::VDUP: return "ARMISD::VDUP";
1019 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1020 case ARMISD::VEXT: return "ARMISD::VEXT";
1021 case ARMISD::VREV64: return "ARMISD::VREV64";
1022 case ARMISD::VREV32: return "ARMISD::VREV32";
1023 case ARMISD::VREV16: return "ARMISD::VREV16";
1024 case ARMISD::VZIP: return "ARMISD::VZIP";
1025 case ARMISD::VUZP: return "ARMISD::VUZP";
1026 case ARMISD::VTRN: return "ARMISD::VTRN";
1027 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1028 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1029 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1030 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1031 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1032 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1033 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1034 case ARMISD::FMAX: return "ARMISD::FMAX";
1035 case ARMISD::FMIN: return "ARMISD::FMIN";
1036 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1037 case ARMISD::VMINNM: return "ARMISD::VMIN";
1038 case ARMISD::BFI: return "ARMISD::BFI";
1039 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1040 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1041 case ARMISD::VBSL: return "ARMISD::VBSL";
1042 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1043 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1044 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1045 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1046 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1047 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1048 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1049 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1050 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1051 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1052 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1053 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1054 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1055 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1056 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1057 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1058 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1059 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1060 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1061 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1065 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1066 if (!VT.isVector()) return getPointerTy();
1067 return VT.changeVectorElementTypeToInteger();
1070 /// getRegClassFor - Return the register class that should be used for the
1071 /// specified value type.
1072 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1073 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1074 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1075 // load / store 4 to 8 consecutive D registers.
1076 if (Subtarget->hasNEON()) {
1077 if (VT == MVT::v4i64)
1078 return &ARM::QQPRRegClass;
1079 if (VT == MVT::v8i64)
1080 return &ARM::QQQQPRRegClass;
1082 return TargetLowering::getRegClassFor(VT);
1085 // Create a fast isel object.
1087 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1088 const TargetLibraryInfo *libInfo) const {
1089 return ARM::createFastISel(funcInfo, libInfo);
1092 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1093 /// be used for loads / stores from the global.
1094 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1095 return (Subtarget->isThumb1Only() ? 127 : 4095);
1098 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1099 unsigned NumVals = N->getNumValues();
1101 return Sched::RegPressure;
1103 for (unsigned i = 0; i != NumVals; ++i) {
1104 EVT VT = N->getValueType(i);
1105 if (VT == MVT::Glue || VT == MVT::Other)
1107 if (VT.isFloatingPoint() || VT.isVector())
1111 if (!N->isMachineOpcode())
1112 return Sched::RegPressure;
1114 // Load are scheduled for latency even if there instruction itinerary
1115 // is not available.
1116 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1117 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1119 if (MCID.getNumDefs() == 0)
1120 return Sched::RegPressure;
1121 if (!Itins->isEmpty() &&
1122 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1125 return Sched::RegPressure;
1128 //===----------------------------------------------------------------------===//
1130 //===----------------------------------------------------------------------===//
1132 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1133 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1135 default: llvm_unreachable("Unknown condition code!");
1136 case ISD::SETNE: return ARMCC::NE;
1137 case ISD::SETEQ: return ARMCC::EQ;
1138 case ISD::SETGT: return ARMCC::GT;
1139 case ISD::SETGE: return ARMCC::GE;
1140 case ISD::SETLT: return ARMCC::LT;
1141 case ISD::SETLE: return ARMCC::LE;
1142 case ISD::SETUGT: return ARMCC::HI;
1143 case ISD::SETUGE: return ARMCC::HS;
1144 case ISD::SETULT: return ARMCC::LO;
1145 case ISD::SETULE: return ARMCC::LS;
1149 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1150 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1151 ARMCC::CondCodes &CondCode2) {
1152 CondCode2 = ARMCC::AL;
1154 default: llvm_unreachable("Unknown FP condition!");
1156 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1158 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1160 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1161 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1162 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1163 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1164 case ISD::SETO: CondCode = ARMCC::VC; break;
1165 case ISD::SETUO: CondCode = ARMCC::VS; break;
1166 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1167 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1168 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1170 case ISD::SETULT: CondCode = ARMCC::LT; break;
1172 case ISD::SETULE: CondCode = ARMCC::LE; break;
1174 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1178 //===----------------------------------------------------------------------===//
1179 // Calling Convention Implementation
1180 //===----------------------------------------------------------------------===//
1182 #include "ARMGenCallingConv.inc"
1184 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1185 /// account presence of floating point hardware and calling convention
1186 /// limitations, such as support for variadic functions.
1188 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1189 bool isVarArg) const {
1192 llvm_unreachable("Unsupported calling convention");
1193 case CallingConv::ARM_AAPCS:
1194 case CallingConv::ARM_APCS:
1195 case CallingConv::GHC:
1197 case CallingConv::ARM_AAPCS_VFP:
1198 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1199 case CallingConv::C:
1200 if (!Subtarget->isAAPCS_ABI())
1201 return CallingConv::ARM_APCS;
1202 else if (Subtarget->hasVFP2() &&
1203 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1205 return CallingConv::ARM_AAPCS_VFP;
1207 return CallingConv::ARM_AAPCS;
1208 case CallingConv::Fast:
1209 if (!Subtarget->isAAPCS_ABI()) {
1210 if (Subtarget->hasVFP2() && !isVarArg)
1211 return CallingConv::Fast;
1212 return CallingConv::ARM_APCS;
1213 } else if (Subtarget->hasVFP2() && !isVarArg)
1214 return CallingConv::ARM_AAPCS_VFP;
1216 return CallingConv::ARM_AAPCS;
1220 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1221 /// CallingConvention.
1222 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1224 bool isVarArg) const {
1225 switch (getEffectiveCallingConv(CC, isVarArg)) {
1227 llvm_unreachable("Unsupported calling convention");
1228 case CallingConv::ARM_APCS:
1229 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1230 case CallingConv::ARM_AAPCS:
1231 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1232 case CallingConv::ARM_AAPCS_VFP:
1233 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1234 case CallingConv::Fast:
1235 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1236 case CallingConv::GHC:
1237 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1241 /// LowerCallResult - Lower the result values of a call into the
1242 /// appropriate copies out of appropriate physical registers.
1244 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1245 CallingConv::ID CallConv, bool isVarArg,
1246 const SmallVectorImpl<ISD::InputArg> &Ins,
1247 SDLoc dl, SelectionDAG &DAG,
1248 SmallVectorImpl<SDValue> &InVals,
1249 bool isThisReturn, SDValue ThisVal) const {
1251 // Assign locations to each value returned by this call.
1252 SmallVector<CCValAssign, 16> RVLocs;
1253 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1254 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1255 CCInfo.AnalyzeCallResult(Ins,
1256 CCAssignFnForNode(CallConv, /* Return*/ true,
1259 // Copy all of the result registers out of their specified physreg.
1260 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1261 CCValAssign VA = RVLocs[i];
1263 // Pass 'this' value directly from the argument to return value, to avoid
1264 // reg unit interference
1265 if (i == 0 && isThisReturn) {
1266 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1267 "unexpected return calling convention register assignment");
1268 InVals.push_back(ThisVal);
1273 if (VA.needsCustom()) {
1274 // Handle f64 or half of a v2f64.
1275 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1277 Chain = Lo.getValue(1);
1278 InFlag = Lo.getValue(2);
1279 VA = RVLocs[++i]; // skip ahead to next loc
1280 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1282 Chain = Hi.getValue(1);
1283 InFlag = Hi.getValue(2);
1284 if (!Subtarget->isLittle())
1286 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1288 if (VA.getLocVT() == MVT::v2f64) {
1289 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1290 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1291 DAG.getConstant(0, MVT::i32));
1293 VA = RVLocs[++i]; // skip ahead to next loc
1294 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1295 Chain = Lo.getValue(1);
1296 InFlag = Lo.getValue(2);
1297 VA = RVLocs[++i]; // skip ahead to next loc
1298 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1299 Chain = Hi.getValue(1);
1300 InFlag = Hi.getValue(2);
1301 if (!Subtarget->isLittle())
1303 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1304 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1305 DAG.getConstant(1, MVT::i32));
1308 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1310 Chain = Val.getValue(1);
1311 InFlag = Val.getValue(2);
1314 switch (VA.getLocInfo()) {
1315 default: llvm_unreachable("Unknown loc info!");
1316 case CCValAssign::Full: break;
1317 case CCValAssign::BCvt:
1318 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1322 InVals.push_back(Val);
1328 /// LowerMemOpCallTo - Store the argument to the stack.
1330 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1331 SDValue StackPtr, SDValue Arg,
1332 SDLoc dl, SelectionDAG &DAG,
1333 const CCValAssign &VA,
1334 ISD::ArgFlagsTy Flags) const {
1335 unsigned LocMemOffset = VA.getLocMemOffset();
1336 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1337 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1338 return DAG.getStore(Chain, dl, Arg, PtrOff,
1339 MachinePointerInfo::getStack(LocMemOffset),
1343 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1344 SDValue Chain, SDValue &Arg,
1345 RegsToPassVector &RegsToPass,
1346 CCValAssign &VA, CCValAssign &NextVA,
1348 SmallVectorImpl<SDValue> &MemOpChains,
1349 ISD::ArgFlagsTy Flags) const {
1351 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1352 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1353 unsigned id = Subtarget->isLittle() ? 0 : 1;
1354 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1356 if (NextVA.isRegLoc())
1357 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1359 assert(NextVA.isMemLoc());
1360 if (!StackPtr.getNode())
1361 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1363 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1369 /// LowerCall - Lowering a call into a callseq_start <-
1370 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1373 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1374 SmallVectorImpl<SDValue> &InVals) const {
1375 SelectionDAG &DAG = CLI.DAG;
1377 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1378 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1379 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1380 SDValue Chain = CLI.Chain;
1381 SDValue Callee = CLI.Callee;
1382 bool &isTailCall = CLI.IsTailCall;
1383 CallingConv::ID CallConv = CLI.CallConv;
1384 bool doesNotRet = CLI.DoesNotReturn;
1385 bool isVarArg = CLI.IsVarArg;
1387 MachineFunction &MF = DAG.getMachineFunction();
1388 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1389 bool isThisReturn = false;
1390 bool isSibCall = false;
1392 // Disable tail calls if they're not supported.
1393 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1397 // Check if it's really possible to do a tail call.
1398 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1399 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1400 Outs, OutVals, Ins, DAG);
1401 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1402 report_fatal_error("failed to perform tail call elimination on a call "
1403 "site marked musttail");
1404 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1405 // detected sibcalls.
1412 // Analyze operands of the call, assigning locations to each operand.
1413 SmallVector<CCValAssign, 16> ArgLocs;
1414 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1415 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1416 CCInfo.AnalyzeCallOperands(Outs,
1417 CCAssignFnForNode(CallConv, /* Return*/ false,
1420 // Get a count of how many bytes are to be pushed on the stack.
1421 unsigned NumBytes = CCInfo.getNextStackOffset();
1423 // For tail calls, memory operands are available in our caller's stack.
1427 // Adjust the stack pointer for the new arguments...
1428 // These operations are automatically eliminated by the prolog/epilog pass
1430 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1433 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1435 RegsToPassVector RegsToPass;
1436 SmallVector<SDValue, 8> MemOpChains;
1438 // Walk the register/memloc assignments, inserting copies/loads. In the case
1439 // of tail call optimization, arguments are handled later.
1440 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1442 ++i, ++realArgIdx) {
1443 CCValAssign &VA = ArgLocs[i];
1444 SDValue Arg = OutVals[realArgIdx];
1445 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1446 bool isByVal = Flags.isByVal();
1448 // Promote the value if needed.
1449 switch (VA.getLocInfo()) {
1450 default: llvm_unreachable("Unknown loc info!");
1451 case CCValAssign::Full: break;
1452 case CCValAssign::SExt:
1453 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1455 case CCValAssign::ZExt:
1456 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1458 case CCValAssign::AExt:
1459 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1461 case CCValAssign::BCvt:
1462 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1466 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1467 if (VA.needsCustom()) {
1468 if (VA.getLocVT() == MVT::v2f64) {
1469 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1470 DAG.getConstant(0, MVT::i32));
1471 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1472 DAG.getConstant(1, MVT::i32));
1474 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1475 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1477 VA = ArgLocs[++i]; // skip ahead to next loc
1478 if (VA.isRegLoc()) {
1479 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1480 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1482 assert(VA.isMemLoc());
1484 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1485 dl, DAG, VA, Flags));
1488 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1489 StackPtr, MemOpChains, Flags);
1491 } else if (VA.isRegLoc()) {
1492 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1493 assert(VA.getLocVT() == MVT::i32 &&
1494 "unexpected calling convention register assignment");
1495 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1496 "unexpected use of 'returned'");
1497 isThisReturn = true;
1499 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1500 } else if (isByVal) {
1501 assert(VA.isMemLoc());
1502 unsigned offset = 0;
1504 // True if this byval aggregate will be split between registers
1506 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1507 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1509 if (CurByValIdx < ByValArgsCount) {
1511 unsigned RegBegin, RegEnd;
1512 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1514 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1516 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1517 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1518 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1519 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1520 MachinePointerInfo(),
1521 false, false, false,
1522 DAG.InferPtrAlignment(AddArg));
1523 MemOpChains.push_back(Load.getValue(1));
1524 RegsToPass.push_back(std::make_pair(j, Load));
1527 // If parameter size outsides register area, "offset" value
1528 // helps us to calculate stack slot for remained part properly.
1529 offset = RegEnd - RegBegin;
1531 CCInfo.nextInRegsParam();
1534 if (Flags.getByValSize() > 4*offset) {
1535 unsigned LocMemOffset = VA.getLocMemOffset();
1536 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1537 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1539 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1540 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1541 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1543 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1545 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1546 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1547 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1550 } else if (!isSibCall) {
1551 assert(VA.isMemLoc());
1553 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1554 dl, DAG, VA, Flags));
1558 if (!MemOpChains.empty())
1559 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1561 // Build a sequence of copy-to-reg nodes chained together with token chain
1562 // and flag operands which copy the outgoing args into the appropriate regs.
1564 // Tail call byval lowering might overwrite argument registers so in case of
1565 // tail call optimization the copies to registers are lowered later.
1567 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1568 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1569 RegsToPass[i].second, InFlag);
1570 InFlag = Chain.getValue(1);
1573 // For tail calls lower the arguments to the 'real' stack slot.
1575 // Force all the incoming stack arguments to be loaded from the stack
1576 // before any new outgoing arguments are stored to the stack, because the
1577 // outgoing stack slots may alias the incoming argument stack slots, and
1578 // the alias isn't otherwise explicit. This is slightly more conservative
1579 // than necessary, because it means that each store effectively depends
1580 // on every argument instead of just those arguments it would clobber.
1582 // Do not flag preceding copytoreg stuff together with the following stuff.
1584 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1585 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1586 RegsToPass[i].second, InFlag);
1587 InFlag = Chain.getValue(1);
1592 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1593 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1594 // node so that legalize doesn't hack it.
1595 bool isDirect = false;
1596 bool isARMFunc = false;
1597 bool isLocalARMFunc = false;
1598 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1600 if (EnableARMLongCalls) {
1601 assert((Subtarget->isTargetWindows() ||
1602 getTargetMachine().getRelocationModel() == Reloc::Static) &&
1603 "long-calls with non-static relocation model!");
1604 // Handle a global address or an external symbol. If it's not one of
1605 // those, the target's already in a register, so we don't need to do
1607 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1608 const GlobalValue *GV = G->getGlobal();
1609 // Create a constant pool entry for the callee address
1610 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1611 ARMConstantPoolValue *CPV =
1612 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1614 // Get the address of the callee into a register
1615 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1616 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1617 Callee = DAG.getLoad(getPointerTy(), dl,
1618 DAG.getEntryNode(), CPAddr,
1619 MachinePointerInfo::getConstantPool(),
1620 false, false, false, 0);
1621 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1622 const char *Sym = S->getSymbol();
1624 // Create a constant pool entry for the callee address
1625 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1626 ARMConstantPoolValue *CPV =
1627 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1628 ARMPCLabelIndex, 0);
1629 // Get the address of the callee into a register
1630 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1631 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1632 Callee = DAG.getLoad(getPointerTy(), dl,
1633 DAG.getEntryNode(), CPAddr,
1634 MachinePointerInfo::getConstantPool(),
1635 false, false, false, 0);
1637 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1638 const GlobalValue *GV = G->getGlobal();
1640 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1641 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1642 getTargetMachine().getRelocationModel() != Reloc::Static;
1643 isARMFunc = !Subtarget->isThumb() || isStub;
1644 // ARM call to a local ARM function is predicable.
1645 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1646 // tBX takes a register source operand.
1647 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1648 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1649 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1650 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1652 // On ELF targets for PIC code, direct calls should go through the PLT
1653 unsigned OpFlags = 0;
1654 if (Subtarget->isTargetELF() &&
1655 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1656 OpFlags = ARMII::MO_PLT;
1657 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1659 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1661 bool isStub = Subtarget->isTargetMachO() &&
1662 getTargetMachine().getRelocationModel() != Reloc::Static;
1663 isARMFunc = !Subtarget->isThumb() || isStub;
1664 // tBX takes a register source operand.
1665 const char *Sym = S->getSymbol();
1666 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1667 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1668 ARMConstantPoolValue *CPV =
1669 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1670 ARMPCLabelIndex, 4);
1671 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1672 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1673 Callee = DAG.getLoad(getPointerTy(), dl,
1674 DAG.getEntryNode(), CPAddr,
1675 MachinePointerInfo::getConstantPool(),
1676 false, false, false, 0);
1677 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1678 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1679 getPointerTy(), Callee, PICLabel);
1681 unsigned OpFlags = 0;
1682 // On ELF targets for PIC code, direct calls should go through the PLT
1683 if (Subtarget->isTargetELF() &&
1684 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1685 OpFlags = ARMII::MO_PLT;
1686 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1690 // FIXME: handle tail calls differently.
1692 bool HasMinSizeAttr = Subtarget->isMinSize();
1693 if (Subtarget->isThumb()) {
1694 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1695 CallOpc = ARMISD::CALL_NOLINK;
1697 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1699 if (!isDirect && !Subtarget->hasV5TOps())
1700 CallOpc = ARMISD::CALL_NOLINK;
1701 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1702 // Emit regular call when code size is the priority
1704 // "mov lr, pc; b _foo" to avoid confusing the RSP
1705 CallOpc = ARMISD::CALL_NOLINK;
1707 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1710 std::vector<SDValue> Ops;
1711 Ops.push_back(Chain);
1712 Ops.push_back(Callee);
1714 // Add argument registers to the end of the list so that they are known live
1716 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1717 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1718 RegsToPass[i].second.getValueType()));
1720 // Add a register mask operand representing the call-preserved registers.
1722 const uint32_t *Mask;
1723 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1724 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1726 // For 'this' returns, use the R0-preserving mask if applicable
1727 Mask = ARI->getThisReturnPreservedMask(CallConv);
1729 // Set isThisReturn to false if the calling convention is not one that
1730 // allows 'returned' to be modeled in this way, so LowerCallResult does
1731 // not try to pass 'this' straight through
1732 isThisReturn = false;
1733 Mask = ARI->getCallPreservedMask(CallConv);
1736 Mask = ARI->getCallPreservedMask(CallConv);
1738 assert(Mask && "Missing call preserved mask for calling convention");
1739 Ops.push_back(DAG.getRegisterMask(Mask));
1742 if (InFlag.getNode())
1743 Ops.push_back(InFlag);
1745 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1747 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1749 // Returns a chain and a flag for retval copy to use.
1750 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1751 InFlag = Chain.getValue(1);
1753 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1754 DAG.getIntPtrConstant(0, true), InFlag, dl);
1756 InFlag = Chain.getValue(1);
1758 // Handle result values, copying them out of physregs into vregs that we
1760 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1761 InVals, isThisReturn,
1762 isThisReturn ? OutVals[0] : SDValue());
1765 /// HandleByVal - Every parameter *after* a byval parameter is passed
1766 /// on the stack. Remember the next parameter register to allocate,
1767 /// and then confiscate the rest of the parameter registers to insure
1770 ARMTargetLowering::HandleByVal(
1771 CCState *State, unsigned &size, unsigned Align) const {
1772 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1773 assert((State->getCallOrPrologue() == Prologue ||
1774 State->getCallOrPrologue() == Call) &&
1775 "unhandled ParmContext");
1777 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1778 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1779 unsigned AlignInRegs = Align / 4;
1780 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1781 for (unsigned i = 0; i < Waste; ++i)
1782 reg = State->AllocateReg(GPRArgRegs, 4);
1785 unsigned excess = 4 * (ARM::R4 - reg);
1787 // Special case when NSAA != SP and parameter size greater than size of
1788 // all remained GPR regs. In that case we can't split parameter, we must
1789 // send it to stack. We also must set NCRN to R4, so waste all
1790 // remained registers.
1791 const unsigned NSAAOffset = State->getNextStackOffset();
1792 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1793 while (State->AllocateReg(GPRArgRegs, 4))
1798 // First register for byval parameter is the first register that wasn't
1799 // allocated before this method call, so it would be "reg".
1800 // If parameter is small enough to be saved in range [reg, r4), then
1801 // the end (first after last) register would be reg + param-size-in-regs,
1802 // else parameter would be splitted between registers and stack,
1803 // end register would be r4 in this case.
1804 unsigned ByValRegBegin = reg;
1805 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1806 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1807 // Note, first register is allocated in the beginning of function already,
1808 // allocate remained amount of registers we need.
1809 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1810 State->AllocateReg(GPRArgRegs, 4);
1811 // A byval parameter that is split between registers and memory needs its
1812 // size truncated here.
1813 // In the case where the entire structure fits in registers, we set the
1814 // size in memory to zero.
1823 /// MatchingStackOffset - Return true if the given stack call argument is
1824 /// already available in the same position (relatively) of the caller's
1825 /// incoming argument stack.
1827 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1828 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1829 const TargetInstrInfo *TII) {
1830 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1832 if (Arg.getOpcode() == ISD::CopyFromReg) {
1833 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1834 if (!TargetRegisterInfo::isVirtualRegister(VR))
1836 MachineInstr *Def = MRI->getVRegDef(VR);
1839 if (!Flags.isByVal()) {
1840 if (!TII->isLoadFromStackSlot(Def, FI))
1845 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1846 if (Flags.isByVal())
1847 // ByVal argument is passed in as a pointer but it's now being
1848 // dereferenced. e.g.
1849 // define @foo(%struct.X* %A) {
1850 // tail call @bar(%struct.X* byval %A)
1853 SDValue Ptr = Ld->getBasePtr();
1854 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1857 FI = FINode->getIndex();
1861 assert(FI != INT_MAX);
1862 if (!MFI->isFixedObjectIndex(FI))
1864 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1867 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1868 /// for tail call optimization. Targets which want to do tail call
1869 /// optimization should implement this function.
1871 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1872 CallingConv::ID CalleeCC,
1874 bool isCalleeStructRet,
1875 bool isCallerStructRet,
1876 const SmallVectorImpl<ISD::OutputArg> &Outs,
1877 const SmallVectorImpl<SDValue> &OutVals,
1878 const SmallVectorImpl<ISD::InputArg> &Ins,
1879 SelectionDAG& DAG) const {
1880 const Function *CallerF = DAG.getMachineFunction().getFunction();
1881 CallingConv::ID CallerCC = CallerF->getCallingConv();
1882 bool CCMatch = CallerCC == CalleeCC;
1884 // Look for obvious safe cases to perform tail call optimization that do not
1885 // require ABI changes. This is what gcc calls sibcall.
1887 // Do not sibcall optimize vararg calls unless the call site is not passing
1889 if (isVarArg && !Outs.empty())
1892 // Exception-handling functions need a special set of instructions to indicate
1893 // a return to the hardware. Tail-calling another function would probably
1895 if (CallerF->hasFnAttribute("interrupt"))
1898 // Also avoid sibcall optimization if either caller or callee uses struct
1899 // return semantics.
1900 if (isCalleeStructRet || isCallerStructRet)
1903 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1904 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1905 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1906 // support in the assembler and linker to be used. This would need to be
1907 // fixed to fully support tail calls in Thumb1.
1909 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1910 // LR. This means if we need to reload LR, it takes an extra instructions,
1911 // which outweighs the value of the tail call; but here we don't know yet
1912 // whether LR is going to be used. Probably the right approach is to
1913 // generate the tail call here and turn it back into CALL/RET in
1914 // emitEpilogue if LR is used.
1916 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1917 // but we need to make sure there are enough registers; the only valid
1918 // registers are the 4 used for parameters. We don't currently do this
1920 if (Subtarget->isThumb1Only())
1923 // If the calling conventions do not match, then we'd better make sure the
1924 // results are returned in the same way as what the caller expects.
1926 SmallVector<CCValAssign, 16> RVLocs1;
1927 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1928 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1929 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1931 SmallVector<CCValAssign, 16> RVLocs2;
1932 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1933 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1934 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1936 if (RVLocs1.size() != RVLocs2.size())
1938 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1939 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1941 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1943 if (RVLocs1[i].isRegLoc()) {
1944 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1947 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1953 // If Caller's vararg or byval argument has been split between registers and
1954 // stack, do not perform tail call, since part of the argument is in caller's
1956 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1957 getInfo<ARMFunctionInfo>();
1958 if (AFI_Caller->getArgRegsSaveSize())
1961 // If the callee takes no arguments then go on to check the results of the
1963 if (!Outs.empty()) {
1964 // Check if stack adjustment is needed. For now, do not do this if any
1965 // argument is passed on the stack.
1966 SmallVector<CCValAssign, 16> ArgLocs;
1967 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1968 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1969 CCInfo.AnalyzeCallOperands(Outs,
1970 CCAssignFnForNode(CalleeCC, false, isVarArg));
1971 if (CCInfo.getNextStackOffset()) {
1972 MachineFunction &MF = DAG.getMachineFunction();
1974 // Check if the arguments are already laid out in the right way as
1975 // the caller's fixed stack objects.
1976 MachineFrameInfo *MFI = MF.getFrameInfo();
1977 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1978 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1979 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1981 ++i, ++realArgIdx) {
1982 CCValAssign &VA = ArgLocs[i];
1983 EVT RegVT = VA.getLocVT();
1984 SDValue Arg = OutVals[realArgIdx];
1985 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1986 if (VA.getLocInfo() == CCValAssign::Indirect)
1988 if (VA.needsCustom()) {
1989 // f64 and vector types are split into multiple registers or
1990 // register/stack-slot combinations. The types will not match
1991 // the registers; give up on memory f64 refs until we figure
1992 // out what to do about this.
1995 if (!ArgLocs[++i].isRegLoc())
1997 if (RegVT == MVT::v2f64) {
1998 if (!ArgLocs[++i].isRegLoc())
2000 if (!ArgLocs[++i].isRegLoc())
2003 } else if (!VA.isRegLoc()) {
2004 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2016 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2017 MachineFunction &MF, bool isVarArg,
2018 const SmallVectorImpl<ISD::OutputArg> &Outs,
2019 LLVMContext &Context) const {
2020 SmallVector<CCValAssign, 16> RVLocs;
2021 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2022 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2026 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2027 SDLoc DL, SelectionDAG &DAG) {
2028 const MachineFunction &MF = DAG.getMachineFunction();
2029 const Function *F = MF.getFunction();
2031 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2033 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2034 // version of the "preferred return address". These offsets affect the return
2035 // instruction if this is a return from PL1 without hypervisor extensions.
2036 // IRQ/FIQ: +4 "subs pc, lr, #4"
2037 // SWI: 0 "subs pc, lr, #0"
2038 // ABORT: +4 "subs pc, lr, #4"
2039 // UNDEF: +4/+2 "subs pc, lr, #0"
2040 // UNDEF varies depending on where the exception came from ARM or Thumb
2041 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2044 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2047 else if (IntKind == "SWI" || IntKind == "UNDEF")
2050 report_fatal_error("Unsupported interrupt attribute. If present, value "
2051 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2053 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2055 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2059 ARMTargetLowering::LowerReturn(SDValue Chain,
2060 CallingConv::ID CallConv, bool isVarArg,
2061 const SmallVectorImpl<ISD::OutputArg> &Outs,
2062 const SmallVectorImpl<SDValue> &OutVals,
2063 SDLoc dl, SelectionDAG &DAG) const {
2065 // CCValAssign - represent the assignment of the return value to a location.
2066 SmallVector<CCValAssign, 16> RVLocs;
2068 // CCState - Info about the registers and stack slots.
2069 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2070 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2072 // Analyze outgoing return values.
2073 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2077 SmallVector<SDValue, 4> RetOps;
2078 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2079 bool isLittleEndian = Subtarget->isLittle();
2081 // Copy the result values into the output registers.
2082 for (unsigned i = 0, realRVLocIdx = 0;
2084 ++i, ++realRVLocIdx) {
2085 CCValAssign &VA = RVLocs[i];
2086 assert(VA.isRegLoc() && "Can only return in registers!");
2088 SDValue Arg = OutVals[realRVLocIdx];
2090 switch (VA.getLocInfo()) {
2091 default: llvm_unreachable("Unknown loc info!");
2092 case CCValAssign::Full: break;
2093 case CCValAssign::BCvt:
2094 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2098 if (VA.needsCustom()) {
2099 if (VA.getLocVT() == MVT::v2f64) {
2100 // Extract the first half and return it in two registers.
2101 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2102 DAG.getConstant(0, MVT::i32));
2103 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2104 DAG.getVTList(MVT::i32, MVT::i32), Half);
2106 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2107 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2109 Flag = Chain.getValue(1);
2110 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2111 VA = RVLocs[++i]; // skip ahead to next loc
2112 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2113 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2115 Flag = Chain.getValue(1);
2116 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2117 VA = RVLocs[++i]; // skip ahead to next loc
2119 // Extract the 2nd half and fall through to handle it as an f64 value.
2120 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2121 DAG.getConstant(1, MVT::i32));
2123 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2125 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2126 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2127 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2128 fmrrd.getValue(isLittleEndian ? 0 : 1),
2130 Flag = Chain.getValue(1);
2131 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2132 VA = RVLocs[++i]; // skip ahead to next loc
2133 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2134 fmrrd.getValue(isLittleEndian ? 1 : 0),
2137 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2139 // Guarantee that all emitted copies are
2140 // stuck together, avoiding something bad.
2141 Flag = Chain.getValue(1);
2142 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2145 // Update chain and glue.
2148 RetOps.push_back(Flag);
2150 // CPUs which aren't M-class use a special sequence to return from
2151 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2152 // though we use "subs pc, lr, #N").
2154 // M-class CPUs actually use a normal return sequence with a special
2155 // (hardware-provided) value in LR, so the normal code path works.
2156 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2157 !Subtarget->isMClass()) {
2158 if (Subtarget->isThumb1Only())
2159 report_fatal_error("interrupt attribute is not supported in Thumb1");
2160 return LowerInterruptReturn(RetOps, dl, DAG);
2163 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2166 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2167 if (N->getNumValues() != 1)
2169 if (!N->hasNUsesOfValue(1, 0))
2172 SDValue TCChain = Chain;
2173 SDNode *Copy = *N->use_begin();
2174 if (Copy->getOpcode() == ISD::CopyToReg) {
2175 // If the copy has a glue operand, we conservatively assume it isn't safe to
2176 // perform a tail call.
2177 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2179 TCChain = Copy->getOperand(0);
2180 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2181 SDNode *VMov = Copy;
2182 // f64 returned in a pair of GPRs.
2183 SmallPtrSet<SDNode*, 2> Copies;
2184 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2186 if (UI->getOpcode() != ISD::CopyToReg)
2190 if (Copies.size() > 2)
2193 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2195 SDValue UseChain = UI->getOperand(0);
2196 if (Copies.count(UseChain.getNode()))
2203 } else if (Copy->getOpcode() == ISD::BITCAST) {
2204 // f32 returned in a single GPR.
2205 if (!Copy->hasOneUse())
2207 Copy = *Copy->use_begin();
2208 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2210 TCChain = Copy->getOperand(0);
2215 bool HasRet = false;
2216 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2218 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2219 UI->getOpcode() != ARMISD::INTRET_FLAG)
2231 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2232 if (!Subtarget->supportsTailCall())
2235 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2238 return !Subtarget->isThumb1Only();
2241 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2242 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2243 // one of the above mentioned nodes. It has to be wrapped because otherwise
2244 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2245 // be used to form addressing mode. These wrapped nodes will be selected
2247 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2248 EVT PtrVT = Op.getValueType();
2249 // FIXME there is no actual debug info here
2251 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2253 if (CP->isMachineConstantPoolEntry())
2254 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2255 CP->getAlignment());
2257 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2258 CP->getAlignment());
2259 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2262 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2263 return MachineJumpTableInfo::EK_Inline;
2266 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2267 SelectionDAG &DAG) const {
2268 MachineFunction &MF = DAG.getMachineFunction();
2269 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2270 unsigned ARMPCLabelIndex = 0;
2272 EVT PtrVT = getPointerTy();
2273 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2274 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2276 if (RelocM == Reloc::Static) {
2277 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2279 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2280 ARMPCLabelIndex = AFI->createPICLabelUId();
2281 ARMConstantPoolValue *CPV =
2282 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2283 ARMCP::CPBlockAddress, PCAdj);
2284 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2286 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2287 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2288 MachinePointerInfo::getConstantPool(),
2289 false, false, false, 0);
2290 if (RelocM == Reloc::Static)
2292 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2293 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2296 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2298 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2299 SelectionDAG &DAG) const {
2301 EVT PtrVT = getPointerTy();
2302 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2303 MachineFunction &MF = DAG.getMachineFunction();
2304 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2306 ARMConstantPoolValue *CPV =
2307 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2308 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2309 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2310 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2311 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2312 MachinePointerInfo::getConstantPool(),
2313 false, false, false, 0);
2314 SDValue Chain = Argument.getValue(1);
2316 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2317 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2319 // call __tls_get_addr.
2322 Entry.Node = Argument;
2323 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2324 Args.push_back(Entry);
2326 // FIXME: is there useful debug info available here?
2327 TargetLowering::CallLoweringInfo CLI(DAG);
2328 CLI.setDebugLoc(dl).setChain(Chain)
2329 .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2330 DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2332 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2333 return CallResult.first;
2336 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2337 // "local exec" model.
2339 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2341 TLSModel::Model model) const {
2342 const GlobalValue *GV = GA->getGlobal();
2345 SDValue Chain = DAG.getEntryNode();
2346 EVT PtrVT = getPointerTy();
2347 // Get the Thread Pointer
2348 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2350 if (model == TLSModel::InitialExec) {
2351 MachineFunction &MF = DAG.getMachineFunction();
2352 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2353 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2354 // Initial exec model.
2355 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2356 ARMConstantPoolValue *CPV =
2357 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2358 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2360 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2361 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2362 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2363 MachinePointerInfo::getConstantPool(),
2364 false, false, false, 0);
2365 Chain = Offset.getValue(1);
2367 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2368 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2370 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2371 MachinePointerInfo::getConstantPool(),
2372 false, false, false, 0);
2375 assert(model == TLSModel::LocalExec);
2376 ARMConstantPoolValue *CPV =
2377 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2378 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2379 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2380 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2381 MachinePointerInfo::getConstantPool(),
2382 false, false, false, 0);
2385 // The address of the thread local variable is the add of the thread
2386 // pointer with the offset of the variable.
2387 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2391 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2392 // TODO: implement the "local dynamic" model
2393 assert(Subtarget->isTargetELF() &&
2394 "TLS not implemented for non-ELF targets");
2395 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2397 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2400 case TLSModel::GeneralDynamic:
2401 case TLSModel::LocalDynamic:
2402 return LowerToTLSGeneralDynamicModel(GA, DAG);
2403 case TLSModel::InitialExec:
2404 case TLSModel::LocalExec:
2405 return LowerToTLSExecModels(GA, DAG, model);
2407 llvm_unreachable("bogus TLS model");
2410 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2411 SelectionDAG &DAG) const {
2412 EVT PtrVT = getPointerTy();
2414 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2415 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2416 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2417 ARMConstantPoolValue *CPV =
2418 ARMConstantPoolConstant::Create(GV,
2419 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2420 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2421 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2422 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2424 MachinePointerInfo::getConstantPool(),
2425 false, false, false, 0);
2426 SDValue Chain = Result.getValue(1);
2427 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2428 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2430 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2431 MachinePointerInfo::getGOT(),
2432 false, false, false, 0);
2436 // If we have T2 ops, we can materialize the address directly via movt/movw
2437 // pair. This is always cheaper.
2438 if (Subtarget->useMovt()) {
2440 // FIXME: Once remat is capable of dealing with instructions with register
2441 // operands, expand this into two nodes.
2442 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2443 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2445 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2446 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2447 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2448 MachinePointerInfo::getConstantPool(),
2449 false, false, false, 0);
2453 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2454 SelectionDAG &DAG) const {
2455 EVT PtrVT = getPointerTy();
2457 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2458 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2460 if (Subtarget->useMovt())
2463 // FIXME: Once remat is capable of dealing with instructions with register
2464 // operands, expand this into multiple nodes
2466 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2468 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2469 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2471 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2472 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2473 MachinePointerInfo::getGOT(), false, false, false, 0);
2477 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2478 SelectionDAG &DAG) const {
2479 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2480 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2482 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2483 EVT PtrVT = getPointerTy();
2488 // FIXME: Once remat is capable of dealing with instructions with register
2489 // operands, expand this into two nodes.
2490 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2491 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2494 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2495 SelectionDAG &DAG) const {
2496 assert(Subtarget->isTargetELF() &&
2497 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2498 MachineFunction &MF = DAG.getMachineFunction();
2499 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2500 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2501 EVT PtrVT = getPointerTy();
2503 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2504 ARMConstantPoolValue *CPV =
2505 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2506 ARMPCLabelIndex, PCAdj);
2507 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2508 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2509 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2510 MachinePointerInfo::getConstantPool(),
2511 false, false, false, 0);
2512 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2513 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2517 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2519 SDValue Val = DAG.getConstant(0, MVT::i32);
2520 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2521 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2522 Op.getOperand(1), Val);
2526 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2528 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2529 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2533 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2534 const ARMSubtarget *Subtarget) const {
2535 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2538 default: return SDValue(); // Don't custom lower most intrinsics.
2539 case Intrinsic::arm_thread_pointer: {
2540 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2541 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2543 case Intrinsic::eh_sjlj_lsda: {
2544 MachineFunction &MF = DAG.getMachineFunction();
2545 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2546 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2547 EVT PtrVT = getPointerTy();
2548 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2550 unsigned PCAdj = (RelocM != Reloc::PIC_)
2551 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2552 ARMConstantPoolValue *CPV =
2553 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2554 ARMCP::CPLSDA, PCAdj);
2555 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2556 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2558 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2559 MachinePointerInfo::getConstantPool(),
2560 false, false, false, 0);
2562 if (RelocM == Reloc::PIC_) {
2563 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2564 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2568 case Intrinsic::arm_neon_vmulls:
2569 case Intrinsic::arm_neon_vmullu: {
2570 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2571 ? ARMISD::VMULLs : ARMISD::VMULLu;
2572 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2573 Op.getOperand(1), Op.getOperand(2));
2578 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2579 const ARMSubtarget *Subtarget) {
2580 // FIXME: handle "fence singlethread" more efficiently.
2582 if (!Subtarget->hasDataBarrier()) {
2583 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2584 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2586 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2587 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2588 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2589 DAG.getConstant(0, MVT::i32));
2592 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2593 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2594 unsigned Domain = ARM_MB::ISH;
2595 if (Subtarget->isMClass()) {
2596 // Only a full system barrier exists in the M-class architectures.
2597 Domain = ARM_MB::SY;
2598 } else if (Subtarget->isSwift() && Ord == Release) {
2599 // Swift happens to implement ISHST barriers in a way that's compatible with
2600 // Release semantics but weaker than ISH so we'd be fools not to use
2601 // it. Beware: other processors probably don't!
2602 Domain = ARM_MB::ISHST;
2605 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2606 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2607 DAG.getConstant(Domain, MVT::i32));
2610 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2611 const ARMSubtarget *Subtarget) {
2612 // ARM pre v5TE and Thumb1 does not have preload instructions.
2613 if (!(Subtarget->isThumb2() ||
2614 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2615 // Just preserve the chain.
2616 return Op.getOperand(0);
2619 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2621 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2622 // ARMv7 with MP extension has PLDW.
2623 return Op.getOperand(0);
2625 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2626 if (Subtarget->isThumb()) {
2628 isRead = ~isRead & 1;
2629 isData = ~isData & 1;
2632 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2633 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2634 DAG.getConstant(isData, MVT::i32));
2637 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2638 MachineFunction &MF = DAG.getMachineFunction();
2639 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2641 // vastart just stores the address of the VarArgsFrameIndex slot into the
2642 // memory location argument.
2644 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2645 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2646 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2647 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2648 MachinePointerInfo(SV), false, false, 0);
2652 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2653 SDValue &Root, SelectionDAG &DAG,
2655 MachineFunction &MF = DAG.getMachineFunction();
2656 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2658 const TargetRegisterClass *RC;
2659 if (AFI->isThumb1OnlyFunction())
2660 RC = &ARM::tGPRRegClass;
2662 RC = &ARM::GPRRegClass;
2664 // Transform the arguments stored in physical registers into virtual ones.
2665 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2666 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2669 if (NextVA.isMemLoc()) {
2670 MachineFrameInfo *MFI = MF.getFrameInfo();
2671 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2673 // Create load node to retrieve arguments from the stack.
2674 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2675 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2676 MachinePointerInfo::getFixedStack(FI),
2677 false, false, false, 0);
2679 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2680 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2682 if (!Subtarget->isLittle())
2683 std::swap (ArgValue, ArgValue2);
2684 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2688 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2689 unsigned InRegsParamRecordIdx,
2691 unsigned &ArgRegsSize,
2692 unsigned &ArgRegsSaveSize)
2695 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2696 unsigned RBegin, REnd;
2697 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2698 NumGPRs = REnd - RBegin;
2700 unsigned int firstUnalloced;
2701 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2702 sizeof(GPRArgRegs) /
2703 sizeof(GPRArgRegs[0]));
2704 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2707 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2708 ArgRegsSize = NumGPRs * 4;
2710 // If parameter is split between stack and GPRs...
2711 if (NumGPRs && Align > 4 &&
2712 (ArgRegsSize < ArgSize ||
2713 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2714 // Add padding for part of param recovered from GPRs. For example,
2715 // if Align == 8, its last byte must be at address K*8 - 1.
2716 // We need to do it, since remained (stack) part of parameter has
2717 // stack alignment, and we need to "attach" "GPRs head" without gaps
2720 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2721 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2723 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2725 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2726 ArgRegsSaveSize = ArgRegsSize + Padding;
2728 // We don't need to extend regs save size for byval parameters if they
2729 // are passed via GPRs only.
2730 ArgRegsSaveSize = ArgRegsSize;
2733 // The remaining GPRs hold either the beginning of variable-argument
2734 // data, or the beginning of an aggregate passed by value (usually
2735 // byval). Either way, we allocate stack slots adjacent to the data
2736 // provided by our caller, and store the unallocated registers there.
2737 // If this is a variadic function, the va_list pointer will begin with
2738 // these values; otherwise, this reassembles a (byval) structure that
2739 // was split between registers and memory.
2740 // Return: The frame index registers were stored into.
2742 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2743 SDLoc dl, SDValue &Chain,
2744 const Value *OrigArg,
2745 unsigned InRegsParamRecordIdx,
2746 unsigned OffsetFromOrigArg,
2750 unsigned ByValStoreOffset,
2751 unsigned TotalArgRegsSaveSize) const {
2753 // Currently, two use-cases possible:
2754 // Case #1. Non-var-args function, and we meet first byval parameter.
2755 // Setup first unallocated register as first byval register;
2756 // eat all remained registers
2757 // (these two actions are performed by HandleByVal method).
2758 // Then, here, we initialize stack frame with
2759 // "store-reg" instructions.
2760 // Case #2. Var-args function, that doesn't contain byval parameters.
2761 // The same: eat all remained unallocated registers,
2762 // initialize stack frame.
2764 MachineFunction &MF = DAG.getMachineFunction();
2765 MachineFrameInfo *MFI = MF.getFrameInfo();
2766 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2767 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2768 unsigned RBegin, REnd;
2769 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2770 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2771 firstRegToSaveIndex = RBegin - ARM::R0;
2772 lastRegToSaveIndex = REnd - ARM::R0;
2774 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2775 (GPRArgRegs, array_lengthof(GPRArgRegs));
2776 lastRegToSaveIndex = 4;
2779 unsigned ArgRegsSize, ArgRegsSaveSize;
2780 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2781 ArgRegsSize, ArgRegsSaveSize);
2783 // Store any by-val regs to their spots on the stack so that they may be
2784 // loaded by deferencing the result of formal parameter pointer or va_next.
2785 // Note: once stack area for byval/varargs registers
2786 // was initialized, it can't be initialized again.
2787 if (ArgRegsSaveSize) {
2788 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2791 assert(AFI->getStoredByValParamsPadding() == 0 &&
2792 "The only parameter may be padded.");
2793 AFI->setStoredByValParamsPadding(Padding);
2796 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2799 (int64_t)TotalArgRegsSaveSize,
2801 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2803 MFI->CreateFixedObject(Padding,
2804 ArgOffset + ByValStoreOffset -
2805 (int64_t)ArgRegsSaveSize,
2809 SmallVector<SDValue, 4> MemOps;
2810 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2811 ++firstRegToSaveIndex, ++i) {
2812 const TargetRegisterClass *RC;
2813 if (AFI->isThumb1OnlyFunction())
2814 RC = &ARM::tGPRRegClass;
2816 RC = &ARM::GPRRegClass;
2818 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2819 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2821 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2822 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2824 MemOps.push_back(Store);
2825 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2826 DAG.getConstant(4, getPointerTy()));
2829 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2831 if (!MemOps.empty())
2832 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2836 // We cannot allocate a zero-byte object for the first variadic argument,
2837 // so just make up a size.
2840 // This will point to the next argument passed via stack.
2841 return MFI->CreateFixedObject(
2842 ArgSize, ArgOffset, !ForceMutable);
2846 // Setup stack frame, the va_list pointer will start from.
2848 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2849 SDLoc dl, SDValue &Chain,
2851 unsigned TotalArgRegsSaveSize,
2852 bool ForceMutable) const {
2853 MachineFunction &MF = DAG.getMachineFunction();
2854 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2856 // Try to store any remaining integer argument regs
2857 // to their spots on the stack so that they may be loaded by deferencing
2858 // the result of va_next.
2859 // If there is no regs to be stored, just point address after last
2860 // argument passed via stack.
2862 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2863 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2864 0, TotalArgRegsSaveSize);
2866 AFI->setVarArgsFrameIndex(FrameIndex);
2870 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2871 CallingConv::ID CallConv, bool isVarArg,
2872 const SmallVectorImpl<ISD::InputArg>
2874 SDLoc dl, SelectionDAG &DAG,
2875 SmallVectorImpl<SDValue> &InVals)
2877 MachineFunction &MF = DAG.getMachineFunction();
2878 MachineFrameInfo *MFI = MF.getFrameInfo();
2880 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2882 // Assign locations to all of the incoming arguments.
2883 SmallVector<CCValAssign, 16> ArgLocs;
2884 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2885 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2886 CCInfo.AnalyzeFormalArguments(Ins,
2887 CCAssignFnForNode(CallConv, /* Return*/ false,
2890 SmallVector<SDValue, 16> ArgValues;
2891 int lastInsIndex = -1;
2893 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2894 unsigned CurArgIdx = 0;
2896 // Initially ArgRegsSaveSize is zero.
2897 // Then we increase this value each time we meet byval parameter.
2898 // We also increase this value in case of varargs function.
2899 AFI->setArgRegsSaveSize(0);
2901 unsigned ByValStoreOffset = 0;
2902 unsigned TotalArgRegsSaveSize = 0;
2903 unsigned ArgRegsSaveSizeMaxAlign = 4;
2905 // Calculate the amount of stack space that we need to allocate to store
2906 // byval and variadic arguments that are passed in registers.
2907 // We need to know this before we allocate the first byval or variadic
2908 // argument, as they will be allocated a stack slot below the CFA (Canonical
2909 // Frame Address, the stack pointer at entry to the function).
2910 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2911 CCValAssign &VA = ArgLocs[i];
2912 if (VA.isMemLoc()) {
2913 int index = VA.getValNo();
2914 if (index != lastInsIndex) {
2915 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2916 if (Flags.isByVal()) {
2917 unsigned ExtraArgRegsSize;
2918 unsigned ExtraArgRegsSaveSize;
2919 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2920 Flags.getByValSize(),
2921 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2923 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2924 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2925 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2926 CCInfo.nextInRegsParam();
2928 lastInsIndex = index;
2932 CCInfo.rewindByValRegsInfo();
2935 unsigned ExtraArgRegsSize;
2936 unsigned ExtraArgRegsSaveSize;
2937 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2938 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2939 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2941 // If the arg regs save area contains N-byte aligned values, the
2942 // bottom of it must be at least N-byte aligned.
2943 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2944 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2946 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2947 CCValAssign &VA = ArgLocs[i];
2948 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2949 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2950 // Arguments stored in registers.
2951 if (VA.isRegLoc()) {
2952 EVT RegVT = VA.getLocVT();
2954 if (VA.needsCustom()) {
2955 // f64 and vector types are split up into multiple registers or
2956 // combinations of registers and stack slots.
2957 if (VA.getLocVT() == MVT::v2f64) {
2958 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2960 VA = ArgLocs[++i]; // skip ahead to next loc
2962 if (VA.isMemLoc()) {
2963 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2964 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2965 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2966 MachinePointerInfo::getFixedStack(FI),
2967 false, false, false, 0);
2969 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2972 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2973 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2974 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2975 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2976 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2978 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2981 const TargetRegisterClass *RC;
2983 if (RegVT == MVT::f32)
2984 RC = &ARM::SPRRegClass;
2985 else if (RegVT == MVT::f64)
2986 RC = &ARM::DPRRegClass;
2987 else if (RegVT == MVT::v2f64)
2988 RC = &ARM::QPRRegClass;
2989 else if (RegVT == MVT::i32)
2990 RC = AFI->isThumb1OnlyFunction() ?
2991 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2992 (const TargetRegisterClass*)&ARM::GPRRegClass;
2994 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2996 // Transform the arguments in physical registers into virtual ones.
2997 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2998 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3001 // If this is an 8 or 16-bit value, it is really passed promoted
3002 // to 32 bits. Insert an assert[sz]ext to capture this, then
3003 // truncate to the right size.
3004 switch (VA.getLocInfo()) {
3005 default: llvm_unreachable("Unknown loc info!");
3006 case CCValAssign::Full: break;
3007 case CCValAssign::BCvt:
3008 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3010 case CCValAssign::SExt:
3011 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3012 DAG.getValueType(VA.getValVT()));
3013 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3015 case CCValAssign::ZExt:
3016 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3017 DAG.getValueType(VA.getValVT()));
3018 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3022 InVals.push_back(ArgValue);
3024 } else { // VA.isRegLoc()
3027 assert(VA.isMemLoc());
3028 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3030 int index = ArgLocs[i].getValNo();
3032 // Some Ins[] entries become multiple ArgLoc[] entries.
3033 // Process them only once.
3034 if (index != lastInsIndex)
3036 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3037 // FIXME: For now, all byval parameter objects are marked mutable.
3038 // This can be changed with more analysis.
3039 // In case of tail call optimization mark all arguments mutable.
3040 // Since they could be overwritten by lowering of arguments in case of
3042 if (Flags.isByVal()) {
3043 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3045 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3046 int FrameIndex = StoreByValRegs(
3047 CCInfo, DAG, dl, Chain, CurOrigArg,
3049 Ins[VA.getValNo()].PartOffset,
3050 VA.getLocMemOffset(),
3051 Flags.getByValSize(),
3052 true /*force mutable frames*/,
3054 TotalArgRegsSaveSize);
3055 ByValStoreOffset += Flags.getByValSize();
3056 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3057 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3058 CCInfo.nextInRegsParam();
3060 unsigned FIOffset = VA.getLocMemOffset();
3061 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3064 // Create load nodes to retrieve arguments from the stack.
3065 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3066 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3067 MachinePointerInfo::getFixedStack(FI),
3068 false, false, false, 0));
3070 lastInsIndex = index;
3077 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3078 CCInfo.getNextStackOffset(),
3079 TotalArgRegsSaveSize);
3081 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3086 /// isFloatingPointZero - Return true if this is +0.0.
3087 static bool isFloatingPointZero(SDValue Op) {
3088 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3089 return CFP->getValueAPF().isPosZero();
3090 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3091 // Maybe this has already been legalized into the constant pool?
3092 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3093 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3094 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3095 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3096 return CFP->getValueAPF().isPosZero();
3102 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3103 /// the given operands.
3105 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3106 SDValue &ARMcc, SelectionDAG &DAG,
3108 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3109 unsigned C = RHSC->getZExtValue();
3110 if (!isLegalICmpImmediate(C)) {
3111 // Constant does not fit, try adjusting it by one?
3116 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3117 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3118 RHS = DAG.getConstant(C-1, MVT::i32);
3123 if (C != 0 && isLegalICmpImmediate(C-1)) {
3124 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3125 RHS = DAG.getConstant(C-1, MVT::i32);
3130 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3131 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3132 RHS = DAG.getConstant(C+1, MVT::i32);
3137 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3138 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3139 RHS = DAG.getConstant(C+1, MVT::i32);
3146 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3147 ARMISD::NodeType CompareType;
3150 CompareType = ARMISD::CMP;
3155 CompareType = ARMISD::CMPZ;
3158 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3159 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3162 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3164 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3167 if (!isFloatingPointZero(RHS))
3168 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3170 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3171 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3174 /// duplicateCmp - Glue values can have only one use, so this function
3175 /// duplicates a comparison node.
3177 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3178 unsigned Opc = Cmp.getOpcode();
3180 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3181 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3183 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3184 Cmp = Cmp.getOperand(0);
3185 Opc = Cmp.getOpcode();
3186 if (Opc == ARMISD::CMPFP)
3187 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3189 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3190 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3192 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3195 std::pair<SDValue, SDValue>
3196 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3197 SDValue &ARMcc) const {
3198 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3200 SDValue Value, OverflowCmp;
3201 SDValue LHS = Op.getOperand(0);
3202 SDValue RHS = Op.getOperand(1);
3205 // FIXME: We are currently always generating CMPs because we don't support
3206 // generating CMN through the backend. This is not as good as the natural
3207 // CMP case because it causes a register dependency and cannot be folded
3210 switch (Op.getOpcode()) {
3212 llvm_unreachable("Unknown overflow instruction!");
3214 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3215 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3216 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3219 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3220 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3221 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3224 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3225 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3226 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3229 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3230 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3231 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3235 return std::make_pair(Value, OverflowCmp);
3240 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3241 // Let legalize expand this if it isn't a legal type yet.
3242 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3245 SDValue Value, OverflowCmp;
3247 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3248 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3249 // We use 0 and 1 as false and true values.
3250 SDValue TVal = DAG.getConstant(1, MVT::i32);
3251 SDValue FVal = DAG.getConstant(0, MVT::i32);
3252 EVT VT = Op.getValueType();
3254 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3255 ARMcc, CCR, OverflowCmp);
3257 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3258 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3262 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3263 SDValue Cond = Op.getOperand(0);
3264 SDValue SelectTrue = Op.getOperand(1);
3265 SDValue SelectFalse = Op.getOperand(2);
3267 unsigned Opc = Cond.getOpcode();
3269 if (Cond.getResNo() == 1 &&
3270 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3271 Opc == ISD::USUBO)) {
3272 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3275 SDValue Value, OverflowCmp;
3277 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3278 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3279 EVT VT = Op.getValueType();
3281 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3282 ARMcc, CCR, OverflowCmp);
3288 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3289 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3291 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3292 const ConstantSDNode *CMOVTrue =
3293 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3294 const ConstantSDNode *CMOVFalse =
3295 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3297 if (CMOVTrue && CMOVFalse) {
3298 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3299 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3303 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3305 False = SelectFalse;
3306 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3311 if (True.getNode() && False.getNode()) {
3312 EVT VT = Op.getValueType();
3313 SDValue ARMcc = Cond.getOperand(2);
3314 SDValue CCR = Cond.getOperand(3);
3315 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3316 assert(True.getValueType() == VT);
3317 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3322 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3323 // undefined bits before doing a full-word comparison with zero.
3324 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3325 DAG.getConstant(1, Cond.getValueType()));
3327 return DAG.getSelectCC(dl, Cond,
3328 DAG.getConstant(0, Cond.getValueType()),
3329 SelectTrue, SelectFalse, ISD::SETNE);
3332 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3333 if (CC == ISD::SETNE)
3335 return ISD::getSetCCInverse(CC, true);
3338 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3339 bool &swpCmpOps, bool &swpVselOps) {
3340 // Start by selecting the GE condition code for opcodes that return true for
3342 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3344 CondCode = ARMCC::GE;
3346 // and GT for opcodes that return false for 'equality'.
3347 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3349 CondCode = ARMCC::GT;
3351 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3352 // to swap the compare operands.
3353 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3357 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3358 // If we have an unordered opcode, we need to swap the operands to the VSEL
3359 // instruction (effectively negating the condition).
3361 // This also has the effect of swapping which one of 'less' or 'greater'
3362 // returns true, so we also swap the compare operands. It also switches
3363 // whether we return true for 'equality', so we compensate by picking the
3364 // opposite condition code to our original choice.
3365 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3366 CC == ISD::SETUGT) {
3367 swpCmpOps = !swpCmpOps;
3368 swpVselOps = !swpVselOps;
3369 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3372 // 'ordered' is 'anything but unordered', so use the VS condition code and
3373 // swap the VSEL operands.
3374 if (CC == ISD::SETO) {
3375 CondCode = ARMCC::VS;
3379 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3380 // code and swap the VSEL operands.
3381 if (CC == ISD::SETUNE) {
3382 CondCode = ARMCC::EQ;
3387 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3388 EVT VT = Op.getValueType();
3389 SDValue LHS = Op.getOperand(0);
3390 SDValue RHS = Op.getOperand(1);
3391 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3392 SDValue TrueVal = Op.getOperand(2);
3393 SDValue FalseVal = Op.getOperand(3);
3396 if (LHS.getValueType() == MVT::i32) {
3397 // Try to generate VSEL on ARMv8.
3398 // The VSEL instruction can't use all the usual ARM condition
3399 // codes: it only has two bits to select the condition code, so it's
3400 // constrained to use only GE, GT, VS and EQ.
3402 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3403 // swap the operands of the previous compare instruction (effectively
3404 // inverting the compare condition, swapping 'less' and 'greater') and
3405 // sometimes need to swap the operands to the VSEL (which inverts the
3406 // condition in the sense of firing whenever the previous condition didn't)
3407 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3408 TrueVal.getValueType() == MVT::f64)) {
3409 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3410 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3411 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3412 CC = getInverseCCForVSEL(CC);
3413 std::swap(TrueVal, FalseVal);
3418 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3419 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3420 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3424 ARMCC::CondCodes CondCode, CondCode2;
3425 FPCCToARMCC(CC, CondCode, CondCode2);
3427 // Try to generate VSEL on ARMv8.
3428 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3429 TrueVal.getValueType() == MVT::f64)) {
3430 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3431 // same operands, as follows:
3432 // c = fcmp [ogt, olt, ugt, ult] a, b
3434 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3435 // handled differently than the original code sequence.
3436 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3438 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3439 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3440 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3441 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3444 bool swpCmpOps = false;
3445 bool swpVselOps = false;
3446 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3448 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3449 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3451 std::swap(LHS, RHS);
3453 std::swap(TrueVal, FalseVal);
3457 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3458 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3459 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3460 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3462 if (CondCode2 != ARMCC::AL) {
3463 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3464 // FIXME: Needs another CMP because flag can have but one use.
3465 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3466 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3467 Result, TrueVal, ARMcc2, CCR, Cmp2);
3472 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3473 /// to morph to an integer compare sequence.
3474 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3475 const ARMSubtarget *Subtarget) {
3476 SDNode *N = Op.getNode();
3477 if (!N->hasOneUse())
3478 // Otherwise it requires moving the value from fp to integer registers.
3480 if (!N->getNumValues())
3482 EVT VT = Op.getValueType();
3483 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3484 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3485 // vmrs are very slow, e.g. cortex-a8.
3488 if (isFloatingPointZero(Op)) {
3492 return ISD::isNormalLoad(N);
3495 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3496 if (isFloatingPointZero(Op))
3497 return DAG.getConstant(0, MVT::i32);
3499 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3500 return DAG.getLoad(MVT::i32, SDLoc(Op),
3501 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3502 Ld->isVolatile(), Ld->isNonTemporal(),
3503 Ld->isInvariant(), Ld->getAlignment());
3505 llvm_unreachable("Unknown VFP cmp argument!");
3508 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3509 SDValue &RetVal1, SDValue &RetVal2) {
3510 if (isFloatingPointZero(Op)) {
3511 RetVal1 = DAG.getConstant(0, MVT::i32);
3512 RetVal2 = DAG.getConstant(0, MVT::i32);
3516 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3517 SDValue Ptr = Ld->getBasePtr();
3518 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3519 Ld->getChain(), Ptr,
3520 Ld->getPointerInfo(),
3521 Ld->isVolatile(), Ld->isNonTemporal(),
3522 Ld->isInvariant(), Ld->getAlignment());
3524 EVT PtrType = Ptr.getValueType();
3525 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3526 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3527 PtrType, Ptr, DAG.getConstant(4, PtrType));
3528 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3529 Ld->getChain(), NewPtr,
3530 Ld->getPointerInfo().getWithOffset(4),
3531 Ld->isVolatile(), Ld->isNonTemporal(),
3532 Ld->isInvariant(), NewAlign);
3536 llvm_unreachable("Unknown VFP cmp argument!");
3539 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3540 /// f32 and even f64 comparisons to integer ones.
3542 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3543 SDValue Chain = Op.getOperand(0);
3544 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3545 SDValue LHS = Op.getOperand(2);
3546 SDValue RHS = Op.getOperand(3);
3547 SDValue Dest = Op.getOperand(4);
3550 bool LHSSeenZero = false;
3551 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3552 bool RHSSeenZero = false;
3553 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3554 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3555 // If unsafe fp math optimization is enabled and there are no other uses of
3556 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3557 // to an integer comparison.
3558 if (CC == ISD::SETOEQ)
3560 else if (CC == ISD::SETUNE)
3563 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3565 if (LHS.getValueType() == MVT::f32) {
3566 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3567 bitcastf32Toi32(LHS, DAG), Mask);
3568 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3569 bitcastf32Toi32(RHS, DAG), Mask);
3570 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3571 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3572 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3573 Chain, Dest, ARMcc, CCR, Cmp);
3578 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3579 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3580 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3581 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3582 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3583 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3584 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3585 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3586 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3592 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3593 SDValue Chain = Op.getOperand(0);
3594 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3595 SDValue LHS = Op.getOperand(2);
3596 SDValue RHS = Op.getOperand(3);
3597 SDValue Dest = Op.getOperand(4);
3600 if (LHS.getValueType() == MVT::i32) {
3602 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3603 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3604 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3605 Chain, Dest, ARMcc, CCR, Cmp);
3608 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3610 if (getTargetMachine().Options.UnsafeFPMath &&
3611 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3612 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3613 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3614 if (Result.getNode())
3618 ARMCC::CondCodes CondCode, CondCode2;
3619 FPCCToARMCC(CC, CondCode, CondCode2);
3621 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3622 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3623 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3624 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3625 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3626 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3627 if (CondCode2 != ARMCC::AL) {
3628 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3629 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3630 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3635 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3636 SDValue Chain = Op.getOperand(0);
3637 SDValue Table = Op.getOperand(1);
3638 SDValue Index = Op.getOperand(2);
3641 EVT PTy = getPointerTy();
3642 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3643 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3644 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3645 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3646 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3647 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3648 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3649 if (Subtarget->isThumb2()) {
3650 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3651 // which does another jump to the destination. This also makes it easier
3652 // to translate it to TBB / TBH later.
3653 // FIXME: This might not work if the function is extremely large.
3654 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3655 Addr, Op.getOperand(2), JTI, UId);
3657 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3658 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3659 MachinePointerInfo::getJumpTable(),
3660 false, false, false, 0);
3661 Chain = Addr.getValue(1);
3662 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3663 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3665 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3666 MachinePointerInfo::getJumpTable(),
3667 false, false, false, 0);
3668 Chain = Addr.getValue(1);
3669 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3673 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3674 EVT VT = Op.getValueType();
3677 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3678 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3680 return DAG.UnrollVectorOp(Op.getNode());
3683 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3684 "Invalid type for custom lowering!");
3685 if (VT != MVT::v4i16)
3686 return DAG.UnrollVectorOp(Op.getNode());
3688 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3689 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3692 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3693 EVT VT = Op.getValueType();
3695 return LowerVectorFP_TO_INT(Op, DAG);
3700 switch (Op.getOpcode()) {
3701 default: llvm_unreachable("Invalid opcode!");
3702 case ISD::FP_TO_SINT:
3703 Opc = ARMISD::FTOSI;
3705 case ISD::FP_TO_UINT:
3706 Opc = ARMISD::FTOUI;
3709 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3710 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3713 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3714 EVT VT = Op.getValueType();
3717 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3718 if (VT.getVectorElementType() == MVT::f32)
3720 return DAG.UnrollVectorOp(Op.getNode());
3723 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3724 "Invalid type for custom lowering!");
3725 if (VT != MVT::v4f32)
3726 return DAG.UnrollVectorOp(Op.getNode());
3730 switch (Op.getOpcode()) {
3731 default: llvm_unreachable("Invalid opcode!");
3732 case ISD::SINT_TO_FP:
3733 CastOpc = ISD::SIGN_EXTEND;
3734 Opc = ISD::SINT_TO_FP;
3736 case ISD::UINT_TO_FP:
3737 CastOpc = ISD::ZERO_EXTEND;
3738 Opc = ISD::UINT_TO_FP;
3742 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3743 return DAG.getNode(Opc, dl, VT, Op);
3746 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3747 EVT VT = Op.getValueType();
3749 return LowerVectorINT_TO_FP(Op, DAG);
3754 switch (Op.getOpcode()) {
3755 default: llvm_unreachable("Invalid opcode!");
3756 case ISD::SINT_TO_FP:
3757 Opc = ARMISD::SITOF;
3759 case ISD::UINT_TO_FP:
3760 Opc = ARMISD::UITOF;
3764 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3765 return DAG.getNode(Opc, dl, VT, Op);
3768 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3769 // Implement fcopysign with a fabs and a conditional fneg.
3770 SDValue Tmp0 = Op.getOperand(0);
3771 SDValue Tmp1 = Op.getOperand(1);
3773 EVT VT = Op.getValueType();
3774 EVT SrcVT = Tmp1.getValueType();
3775 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3776 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3777 bool UseNEON = !InGPR && Subtarget->hasNEON();
3780 // Use VBSL to copy the sign bit.
3781 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3782 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3783 DAG.getTargetConstant(EncodedVal, MVT::i32));
3784 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3786 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3787 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3788 DAG.getConstant(32, MVT::i32));
3789 else /*if (VT == MVT::f32)*/
3790 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3791 if (SrcVT == MVT::f32) {
3792 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3794 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3795 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3796 DAG.getConstant(32, MVT::i32));
3797 } else if (VT == MVT::f32)
3798 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3799 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3800 DAG.getConstant(32, MVT::i32));
3801 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3802 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3804 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3806 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3807 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3808 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3810 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3811 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3812 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3813 if (VT == MVT::f32) {
3814 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3815 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3816 DAG.getConstant(0, MVT::i32));
3818 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3824 // Bitcast operand 1 to i32.
3825 if (SrcVT == MVT::f64)
3826 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3828 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3830 // Or in the signbit with integer operations.
3831 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3832 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3833 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3834 if (VT == MVT::f32) {
3835 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3836 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3837 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3838 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3841 // f64: Or the high part with signbit and then combine two parts.
3842 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3844 SDValue Lo = Tmp0.getValue(0);
3845 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3846 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3847 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3850 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3851 MachineFunction &MF = DAG.getMachineFunction();
3852 MachineFrameInfo *MFI = MF.getFrameInfo();
3853 MFI->setReturnAddressIsTaken(true);
3855 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3858 EVT VT = Op.getValueType();
3860 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3862 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3863 SDValue Offset = DAG.getConstant(4, MVT::i32);
3864 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3865 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3866 MachinePointerInfo(), false, false, false, 0);
3869 // Return LR, which contains the return address. Mark it an implicit live-in.
3870 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3871 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3874 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3875 const ARMBaseRegisterInfo &ARI =
3876 *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3877 MachineFunction &MF = DAG.getMachineFunction();
3878 MachineFrameInfo *MFI = MF.getFrameInfo();
3879 MFI->setFrameAddressIsTaken(true);
3881 EVT VT = Op.getValueType();
3882 SDLoc dl(Op); // FIXME probably not meaningful
3883 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3884 unsigned FrameReg = ARI.getFrameRegister(MF);
3885 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3887 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3888 MachinePointerInfo(),
3889 false, false, false, 0);
3893 // FIXME? Maybe this could be a TableGen attribute on some registers and
3894 // this table could be generated automatically from RegInfo.
3895 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3897 unsigned Reg = StringSwitch<unsigned>(RegName)
3898 .Case("sp", ARM::SP)
3902 report_fatal_error("Invalid register name global variable");
3905 /// ExpandBITCAST - If the target supports VFP, this function is called to
3906 /// expand a bit convert where either the source or destination type is i64 to
3907 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3908 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3909 /// vectors), since the legalizer won't know what to do with that.
3910 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3911 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3913 SDValue Op = N->getOperand(0);
3915 // This function is only supposed to be called for i64 types, either as the
3916 // source or destination of the bit convert.
3917 EVT SrcVT = Op.getValueType();
3918 EVT DstVT = N->getValueType(0);
3919 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3920 "ExpandBITCAST called for non-i64 type");
3922 // Turn i64->f64 into VMOVDRR.
3923 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3924 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3925 DAG.getConstant(0, MVT::i32));
3926 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3927 DAG.getConstant(1, MVT::i32));
3928 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3929 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3932 // Turn f64->i64 into VMOVRRD.
3933 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3935 if (TLI.isBigEndian() && SrcVT.isVector() &&
3936 SrcVT.getVectorNumElements() > 1)
3937 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3938 DAG.getVTList(MVT::i32, MVT::i32),
3939 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3941 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3942 DAG.getVTList(MVT::i32, MVT::i32), Op);
3943 // Merge the pieces into a single i64 value.
3944 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3950 /// getZeroVector - Returns a vector of specified type with all zero elements.
3951 /// Zero vectors are used to represent vector negation and in those cases
3952 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3953 /// not support i64 elements, so sometimes the zero vectors will need to be
3954 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3956 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3957 assert(VT.isVector() && "Expected a vector type");
3958 // The canonical modified immediate encoding of a zero vector is....0!
3959 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3960 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3961 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3962 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3965 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3966 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3967 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3968 SelectionDAG &DAG) const {
3969 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3970 EVT VT = Op.getValueType();
3971 unsigned VTBits = VT.getSizeInBits();
3973 SDValue ShOpLo = Op.getOperand(0);
3974 SDValue ShOpHi = Op.getOperand(1);
3975 SDValue ShAmt = Op.getOperand(2);
3977 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3979 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3981 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3982 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3983 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3984 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3985 DAG.getConstant(VTBits, MVT::i32));
3986 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3987 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3988 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3990 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3991 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3993 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3994 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3997 SDValue Ops[2] = { Lo, Hi };
3998 return DAG.getMergeValues(Ops, dl);
4001 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4002 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4003 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4004 SelectionDAG &DAG) const {
4005 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4006 EVT VT = Op.getValueType();
4007 unsigned VTBits = VT.getSizeInBits();
4009 SDValue ShOpLo = Op.getOperand(0);
4010 SDValue ShOpHi = Op.getOperand(1);
4011 SDValue ShAmt = Op.getOperand(2);
4014 assert(Op.getOpcode() == ISD::SHL_PARTS);
4015 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4016 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4017 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4018 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4019 DAG.getConstant(VTBits, MVT::i32));
4020 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4021 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4023 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4024 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4025 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4027 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4028 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4031 SDValue Ops[2] = { Lo, Hi };
4032 return DAG.getMergeValues(Ops, dl);
4035 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4036 SelectionDAG &DAG) const {
4037 // The rounding mode is in bits 23:22 of the FPSCR.
4038 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4039 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4040 // so that the shift + and get folded into a bitfield extract.
4042 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4043 DAG.getConstant(Intrinsic::arm_get_fpscr,
4045 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4046 DAG.getConstant(1U << 22, MVT::i32));
4047 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4048 DAG.getConstant(22, MVT::i32));
4049 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4050 DAG.getConstant(3, MVT::i32));
4053 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4054 const ARMSubtarget *ST) {
4055 EVT VT = N->getValueType(0);
4058 if (!ST->hasV6T2Ops())
4061 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4062 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4065 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4066 /// for each 16-bit element from operand, repeated. The basic idea is to
4067 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4069 /// Trace for v4i16:
4070 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4071 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4072 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4073 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4074 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4075 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4076 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4077 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4078 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4079 EVT VT = N->getValueType(0);
4082 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4083 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4084 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4085 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4086 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4087 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4090 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4091 /// bit-count for each 16-bit element from the operand. We need slightly
4092 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4093 /// 64/128-bit registers.
4095 /// Trace for v4i16:
4096 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4097 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4098 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4099 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4100 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4101 EVT VT = N->getValueType(0);
4104 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4105 if (VT.is64BitVector()) {
4106 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4107 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4108 DAG.getIntPtrConstant(0));
4110 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4111 BitCounts, DAG.getIntPtrConstant(0));
4112 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4116 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4117 /// bit-count for each 32-bit element from the operand. The idea here is
4118 /// to split the vector into 16-bit elements, leverage the 16-bit count
4119 /// routine, and then combine the results.
4121 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4122 /// input = [v0 v1 ] (vi: 32-bit elements)
4123 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4124 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4125 /// vrev: N0 = [k1 k0 k3 k2 ]
4127 /// N1 =+[k1 k0 k3 k2 ]
4129 /// N2 =+[k1 k3 k0 k2 ]
4131 /// Extended =+[k1 k3 k0 k2 ]
4133 /// Extracted=+[k1 k3 ]
4135 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4136 EVT VT = N->getValueType(0);
4139 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4141 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4142 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4143 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4144 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4145 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4147 if (VT.is64BitVector()) {
4148 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4149 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4150 DAG.getIntPtrConstant(0));
4152 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4153 DAG.getIntPtrConstant(0));
4154 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4158 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4159 const ARMSubtarget *ST) {
4160 EVT VT = N->getValueType(0);
4162 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4163 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4164 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4165 "Unexpected type for custom ctpop lowering");
4167 if (VT.getVectorElementType() == MVT::i32)
4168 return lowerCTPOP32BitElements(N, DAG);
4170 return lowerCTPOP16BitElements(N, DAG);
4173 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4174 const ARMSubtarget *ST) {
4175 EVT VT = N->getValueType(0);
4181 // Lower vector shifts on NEON to use VSHL.
4182 assert(ST->hasNEON() && "unexpected vector shift");
4184 // Left shifts translate directly to the vshiftu intrinsic.
4185 if (N->getOpcode() == ISD::SHL)
4186 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4187 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4188 N->getOperand(0), N->getOperand(1));
4190 assert((N->getOpcode() == ISD::SRA ||
4191 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4193 // NEON uses the same intrinsics for both left and right shifts. For
4194 // right shifts, the shift amounts are negative, so negate the vector of
4196 EVT ShiftVT = N->getOperand(1).getValueType();
4197 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4198 getZeroVector(ShiftVT, DAG, dl),
4200 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4201 Intrinsic::arm_neon_vshifts :
4202 Intrinsic::arm_neon_vshiftu);
4203 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4204 DAG.getConstant(vshiftInt, MVT::i32),
4205 N->getOperand(0), NegatedCount);
4208 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4209 const ARMSubtarget *ST) {
4210 EVT VT = N->getValueType(0);
4213 // We can get here for a node like i32 = ISD::SHL i32, i64
4217 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4218 "Unknown shift to lower!");
4220 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4221 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4222 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4225 // If we are in thumb mode, we don't have RRX.
4226 if (ST->isThumb1Only()) return SDValue();
4228 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4229 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4230 DAG.getConstant(0, MVT::i32));
4231 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4232 DAG.getConstant(1, MVT::i32));
4234 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4235 // captures the result into a carry flag.
4236 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4237 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4239 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4240 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4242 // Merge the pieces into a single i64 value.
4243 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4246 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4247 SDValue TmpOp0, TmpOp1;
4248 bool Invert = false;
4252 SDValue Op0 = Op.getOperand(0);
4253 SDValue Op1 = Op.getOperand(1);
4254 SDValue CC = Op.getOperand(2);
4255 EVT VT = Op.getValueType();
4256 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4259 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4260 switch (SetCCOpcode) {
4261 default: llvm_unreachable("Illegal FP comparison");
4263 case ISD::SETNE: Invert = true; // Fallthrough
4265 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4267 case ISD::SETLT: Swap = true; // Fallthrough
4269 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4271 case ISD::SETLE: Swap = true; // Fallthrough
4273 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4274 case ISD::SETUGE: Swap = true; // Fallthrough
4275 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4276 case ISD::SETUGT: Swap = true; // Fallthrough
4277 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4278 case ISD::SETUEQ: Invert = true; // Fallthrough
4280 // Expand this to (OLT | OGT).
4284 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4285 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4287 case ISD::SETUO: Invert = true; // Fallthrough
4289 // Expand this to (OLT | OGE).
4293 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4294 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4298 // Integer comparisons.
4299 switch (SetCCOpcode) {
4300 default: llvm_unreachable("Illegal integer comparison");
4301 case ISD::SETNE: Invert = true;
4302 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4303 case ISD::SETLT: Swap = true;
4304 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4305 case ISD::SETLE: Swap = true;
4306 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4307 case ISD::SETULT: Swap = true;
4308 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4309 case ISD::SETULE: Swap = true;
4310 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4313 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4314 if (Opc == ARMISD::VCEQ) {
4317 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4319 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4322 // Ignore bitconvert.
4323 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4324 AndOp = AndOp.getOperand(0);
4326 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4328 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4329 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4336 std::swap(Op0, Op1);
4338 // If one of the operands is a constant vector zero, attempt to fold the
4339 // comparison to a specialized compare-against-zero form.
4341 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4343 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4344 if (Opc == ARMISD::VCGE)
4345 Opc = ARMISD::VCLEZ;
4346 else if (Opc == ARMISD::VCGT)
4347 Opc = ARMISD::VCLTZ;
4352 if (SingleOp.getNode()) {
4355 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4357 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4359 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4361 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4363 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4365 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4368 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4372 Result = DAG.getNOT(dl, Result, VT);
4377 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4378 /// valid vector constant for a NEON instruction with a "modified immediate"
4379 /// operand (e.g., VMOV). If so, return the encoded value.
4380 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4381 unsigned SplatBitSize, SelectionDAG &DAG,
4382 EVT &VT, bool is128Bits, NEONModImmType type) {
4383 unsigned OpCmode, Imm;
4385 // SplatBitSize is set to the smallest size that splats the vector, so a
4386 // zero vector will always have SplatBitSize == 8. However, NEON modified
4387 // immediate instructions others than VMOV do not support the 8-bit encoding
4388 // of a zero vector, and the default encoding of zero is supposed to be the
4393 switch (SplatBitSize) {
4395 if (type != VMOVModImm)
4397 // Any 1-byte value is OK. Op=0, Cmode=1110.
4398 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4401 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4405 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4406 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4407 if ((SplatBits & ~0xff) == 0) {
4408 // Value = 0x00nn: Op=x, Cmode=100x.
4413 if ((SplatBits & ~0xff00) == 0) {
4414 // Value = 0xnn00: Op=x, Cmode=101x.
4416 Imm = SplatBits >> 8;
4422 // NEON's 32-bit VMOV supports splat values where:
4423 // * only one byte is nonzero, or
4424 // * the least significant byte is 0xff and the second byte is nonzero, or
4425 // * the least significant 2 bytes are 0xff and the third is nonzero.
4426 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4427 if ((SplatBits & ~0xff) == 0) {
4428 // Value = 0x000000nn: Op=x, Cmode=000x.
4433 if ((SplatBits & ~0xff00) == 0) {
4434 // Value = 0x0000nn00: Op=x, Cmode=001x.
4436 Imm = SplatBits >> 8;
4439 if ((SplatBits & ~0xff0000) == 0) {
4440 // Value = 0x00nn0000: Op=x, Cmode=010x.
4442 Imm = SplatBits >> 16;
4445 if ((SplatBits & ~0xff000000) == 0) {
4446 // Value = 0xnn000000: Op=x, Cmode=011x.
4448 Imm = SplatBits >> 24;
4452 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4453 if (type == OtherModImm) return SDValue();
4455 if ((SplatBits & ~0xffff) == 0 &&
4456 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4457 // Value = 0x0000nnff: Op=x, Cmode=1100.
4459 Imm = SplatBits >> 8;
4463 if ((SplatBits & ~0xffffff) == 0 &&
4464 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4465 // Value = 0x00nnffff: Op=x, Cmode=1101.
4467 Imm = SplatBits >> 16;
4471 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4472 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4473 // VMOV.I32. A (very) minor optimization would be to replicate the value
4474 // and fall through here to test for a valid 64-bit splat. But, then the
4475 // caller would also need to check and handle the change in size.
4479 if (type != VMOVModImm)
4481 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4482 uint64_t BitMask = 0xff;
4484 unsigned ImmMask = 1;
4486 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4487 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4490 } else if ((SplatBits & BitMask) != 0) {
4496 // Op=1, Cmode=1110.
4498 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4503 llvm_unreachable("unexpected size for isNEONModifiedImm");
4506 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4507 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4510 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4511 const ARMSubtarget *ST) const {
4515 bool IsDouble = Op.getValueType() == MVT::f64;
4516 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4518 // Try splatting with a VMOV.f32...
4519 APFloat FPVal = CFP->getValueAPF();
4520 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4523 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4524 // We have code in place to select a valid ConstantFP already, no need to
4529 // It's a float and we are trying to use NEON operations where
4530 // possible. Lower it to a splat followed by an extract.
4532 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4533 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4535 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4536 DAG.getConstant(0, MVT::i32));
4539 // The rest of our options are NEON only, make sure that's allowed before
4541 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4545 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4547 // It wouldn't really be worth bothering for doubles except for one very
4548 // important value, which does happen to match: 0.0. So make sure we don't do
4550 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4553 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4554 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4556 if (NewVal != SDValue()) {
4558 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4561 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4563 // It's a float: cast and extract a vector element.
4564 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4566 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4567 DAG.getConstant(0, MVT::i32));
4570 // Finally, try a VMVN.i32
4571 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4573 if (NewVal != SDValue()) {
4575 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4578 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4580 // It's a float: cast and extract a vector element.
4581 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4583 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4584 DAG.getConstant(0, MVT::i32));
4590 // check if an VEXT instruction can handle the shuffle mask when the
4591 // vector sources of the shuffle are the same.
4592 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4593 unsigned NumElts = VT.getVectorNumElements();
4595 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4601 // If this is a VEXT shuffle, the immediate value is the index of the first
4602 // element. The other shuffle indices must be the successive elements after
4604 unsigned ExpectedElt = Imm;
4605 for (unsigned i = 1; i < NumElts; ++i) {
4606 // Increment the expected index. If it wraps around, just follow it
4607 // back to index zero and keep going.
4609 if (ExpectedElt == NumElts)
4612 if (M[i] < 0) continue; // ignore UNDEF indices
4613 if (ExpectedElt != static_cast<unsigned>(M[i]))
4621 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4622 bool &ReverseVEXT, unsigned &Imm) {
4623 unsigned NumElts = VT.getVectorNumElements();
4624 ReverseVEXT = false;
4626 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4632 // If this is a VEXT shuffle, the immediate value is the index of the first
4633 // element. The other shuffle indices must be the successive elements after
4635 unsigned ExpectedElt = Imm;
4636 for (unsigned i = 1; i < NumElts; ++i) {
4637 // Increment the expected index. If it wraps around, it may still be
4638 // a VEXT but the source vectors must be swapped.
4640 if (ExpectedElt == NumElts * 2) {
4645 if (M[i] < 0) continue; // ignore UNDEF indices
4646 if (ExpectedElt != static_cast<unsigned>(M[i]))
4650 // Adjust the index value if the source operands will be swapped.
4657 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4658 /// instruction with the specified blocksize. (The order of the elements
4659 /// within each block of the vector is reversed.)
4660 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4661 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4662 "Only possible block sizes for VREV are: 16, 32, 64");
4664 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4668 unsigned NumElts = VT.getVectorNumElements();
4669 unsigned BlockElts = M[0] + 1;
4670 // If the first shuffle index is UNDEF, be optimistic.
4672 BlockElts = BlockSize / EltSz;
4674 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4677 for (unsigned i = 0; i < NumElts; ++i) {
4678 if (M[i] < 0) continue; // ignore UNDEF indices
4679 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4686 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4687 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4688 // range, then 0 is placed into the resulting vector. So pretty much any mask
4689 // of 8 elements can work here.
4690 return VT == MVT::v8i8 && M.size() == 8;
4693 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4694 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4698 unsigned NumElts = VT.getVectorNumElements();
4699 WhichResult = (M[0] == 0 ? 0 : 1);
4700 for (unsigned i = 0; i < NumElts; i += 2) {
4701 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4702 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4708 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4709 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4710 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4711 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4712 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4716 unsigned NumElts = VT.getVectorNumElements();
4717 WhichResult = (M[0] == 0 ? 0 : 1);
4718 for (unsigned i = 0; i < NumElts; i += 2) {
4719 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4720 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4726 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4727 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4731 unsigned NumElts = VT.getVectorNumElements();
4732 WhichResult = (M[0] == 0 ? 0 : 1);
4733 for (unsigned i = 0; i != NumElts; ++i) {
4734 if (M[i] < 0) continue; // ignore UNDEF indices
4735 if ((unsigned) M[i] != 2 * i + WhichResult)
4739 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4740 if (VT.is64BitVector() && EltSz == 32)
4746 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4747 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4748 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4749 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4750 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4754 unsigned Half = VT.getVectorNumElements() / 2;
4755 WhichResult = (M[0] == 0 ? 0 : 1);
4756 for (unsigned j = 0; j != 2; ++j) {
4757 unsigned Idx = WhichResult;
4758 for (unsigned i = 0; i != Half; ++i) {
4759 int MIdx = M[i + j * Half];
4760 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4766 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4767 if (VT.is64BitVector() && EltSz == 32)
4773 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4774 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4778 unsigned NumElts = VT.getVectorNumElements();
4779 WhichResult = (M[0] == 0 ? 0 : 1);
4780 unsigned Idx = WhichResult * NumElts / 2;
4781 for (unsigned i = 0; i != NumElts; i += 2) {
4782 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4783 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4788 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4789 if (VT.is64BitVector() && EltSz == 32)
4795 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4796 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4797 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4798 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4799 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4803 unsigned NumElts = VT.getVectorNumElements();
4804 WhichResult = (M[0] == 0 ? 0 : 1);
4805 unsigned Idx = WhichResult * NumElts / 2;
4806 for (unsigned i = 0; i != NumElts; i += 2) {
4807 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4808 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4813 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4814 if (VT.is64BitVector() && EltSz == 32)
4820 /// \return true if this is a reverse operation on an vector.
4821 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4822 unsigned NumElts = VT.getVectorNumElements();
4823 // Make sure the mask has the right size.
4824 if (NumElts != M.size())
4827 // Look for <15, ..., 3, -1, 1, 0>.
4828 for (unsigned i = 0; i != NumElts; ++i)
4829 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4835 // If N is an integer constant that can be moved into a register in one
4836 // instruction, return an SDValue of such a constant (will become a MOV
4837 // instruction). Otherwise return null.
4838 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4839 const ARMSubtarget *ST, SDLoc dl) {
4841 if (!isa<ConstantSDNode>(N))
4843 Val = cast<ConstantSDNode>(N)->getZExtValue();
4845 if (ST->isThumb1Only()) {
4846 if (Val <= 255 || ~Val <= 255)
4847 return DAG.getConstant(Val, MVT::i32);
4849 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4850 return DAG.getConstant(Val, MVT::i32);
4855 // If this is a case we can't handle, return null and let the default
4856 // expansion code take care of it.
4857 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4858 const ARMSubtarget *ST) const {
4859 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4861 EVT VT = Op.getValueType();
4863 APInt SplatBits, SplatUndef;
4864 unsigned SplatBitSize;
4866 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4867 if (SplatBitSize <= 64) {
4868 // Check if an immediate VMOV works.
4870 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4871 SplatUndef.getZExtValue(), SplatBitSize,
4872 DAG, VmovVT, VT.is128BitVector(),
4874 if (Val.getNode()) {
4875 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4876 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4879 // Try an immediate VMVN.
4880 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4881 Val = isNEONModifiedImm(NegatedImm,
4882 SplatUndef.getZExtValue(), SplatBitSize,
4883 DAG, VmovVT, VT.is128BitVector(),
4885 if (Val.getNode()) {
4886 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4887 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4890 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4891 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4892 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4894 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4895 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4901 // Scan through the operands to see if only one value is used.
4903 // As an optimisation, even if more than one value is used it may be more
4904 // profitable to splat with one value then change some lanes.
4906 // Heuristically we decide to do this if the vector has a "dominant" value,
4907 // defined as splatted to more than half of the lanes.
4908 unsigned NumElts = VT.getVectorNumElements();
4909 bool isOnlyLowElement = true;
4910 bool usesOnlyOneValue = true;
4911 bool hasDominantValue = false;
4912 bool isConstant = true;
4914 // Map of the number of times a particular SDValue appears in the
4916 DenseMap<SDValue, unsigned> ValueCounts;
4918 for (unsigned i = 0; i < NumElts; ++i) {
4919 SDValue V = Op.getOperand(i);
4920 if (V.getOpcode() == ISD::UNDEF)
4923 isOnlyLowElement = false;
4924 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4927 ValueCounts.insert(std::make_pair(V, 0));
4928 unsigned &Count = ValueCounts[V];
4930 // Is this value dominant? (takes up more than half of the lanes)
4931 if (++Count > (NumElts / 2)) {
4932 hasDominantValue = true;
4936 if (ValueCounts.size() != 1)
4937 usesOnlyOneValue = false;
4938 if (!Value.getNode() && ValueCounts.size() > 0)
4939 Value = ValueCounts.begin()->first;
4941 if (ValueCounts.size() == 0)
4942 return DAG.getUNDEF(VT);
4944 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4945 // Keep going if we are hitting this case.
4946 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4947 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4949 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4951 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4952 // i32 and try again.
4953 if (hasDominantValue && EltSize <= 32) {
4957 // If we are VDUPing a value that comes directly from a vector, that will
4958 // cause an unnecessary move to and from a GPR, where instead we could
4959 // just use VDUPLANE. We can only do this if the lane being extracted
4960 // is at a constant index, as the VDUP from lane instructions only have
4961 // constant-index forms.
4962 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4963 isa<ConstantSDNode>(Value->getOperand(1))) {
4964 // We need to create a new undef vector to use for the VDUPLANE if the
4965 // size of the vector from which we get the value is different than the
4966 // size of the vector that we need to create. We will insert the element
4967 // such that the register coalescer will remove unnecessary copies.
4968 if (VT != Value->getOperand(0).getValueType()) {
4969 ConstantSDNode *constIndex;
4970 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4971 assert(constIndex && "The index is not a constant!");
4972 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4973 VT.getVectorNumElements();
4974 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4975 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4976 Value, DAG.getConstant(index, MVT::i32)),
4977 DAG.getConstant(index, MVT::i32));
4979 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4980 Value->getOperand(0), Value->getOperand(1));
4982 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4984 if (!usesOnlyOneValue) {
4985 // The dominant value was splatted as 'N', but we now have to insert
4986 // all differing elements.
4987 for (unsigned I = 0; I < NumElts; ++I) {
4988 if (Op.getOperand(I) == Value)
4990 SmallVector<SDValue, 3> Ops;
4992 Ops.push_back(Op.getOperand(I));
4993 Ops.push_back(DAG.getConstant(I, MVT::i32));
4994 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4999 if (VT.getVectorElementType().isFloatingPoint()) {
5000 SmallVector<SDValue, 8> Ops;
5001 for (unsigned i = 0; i < NumElts; ++i)
5002 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5004 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5005 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5006 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5008 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5010 if (usesOnlyOneValue) {
5011 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5012 if (isConstant && Val.getNode())
5013 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5017 // If all elements are constants and the case above didn't get hit, fall back
5018 // to the default expansion, which will generate a load from the constant
5023 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5025 SDValue shuffle = ReconstructShuffle(Op, DAG);
5026 if (shuffle != SDValue())
5030 // Vectors with 32- or 64-bit elements can be built by directly assigning
5031 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5032 // will be legalized.
5033 if (EltSize >= 32) {
5034 // Do the expansion with floating-point types, since that is what the VFP
5035 // registers are defined to use, and since i64 is not legal.
5036 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5037 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5038 SmallVector<SDValue, 8> Ops;
5039 for (unsigned i = 0; i < NumElts; ++i)
5040 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5041 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5042 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5045 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5046 // know the default expansion would otherwise fall back on something even
5047 // worse. For a vector with one or two non-undef values, that's
5048 // scalar_to_vector for the elements followed by a shuffle (provided the
5049 // shuffle is valid for the target) and materialization element by element
5050 // on the stack followed by a load for everything else.
5051 if (!isConstant && !usesOnlyOneValue) {
5052 SDValue Vec = DAG.getUNDEF(VT);
5053 for (unsigned i = 0 ; i < NumElts; ++i) {
5054 SDValue V = Op.getOperand(i);
5055 if (V.getOpcode() == ISD::UNDEF)
5057 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5058 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5066 // Gather data to see if the operation can be modelled as a
5067 // shuffle in combination with VEXTs.
5068 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5069 SelectionDAG &DAG) const {
5071 EVT VT = Op.getValueType();
5072 unsigned NumElts = VT.getVectorNumElements();
5074 SmallVector<SDValue, 2> SourceVecs;
5075 SmallVector<unsigned, 2> MinElts;
5076 SmallVector<unsigned, 2> MaxElts;
5078 for (unsigned i = 0; i < NumElts; ++i) {
5079 SDValue V = Op.getOperand(i);
5080 if (V.getOpcode() == ISD::UNDEF)
5082 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5083 // A shuffle can only come from building a vector from various
5084 // elements of other vectors.
5086 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5087 VT.getVectorElementType()) {
5088 // This code doesn't know how to handle shuffles where the vector
5089 // element types do not match (this happens because type legalization
5090 // promotes the return type of EXTRACT_VECTOR_ELT).
5091 // FIXME: It might be appropriate to extend this code to handle
5092 // mismatched types.
5096 // Record this extraction against the appropriate vector if possible...
5097 SDValue SourceVec = V.getOperand(0);
5098 // If the element number isn't a constant, we can't effectively
5099 // analyze what's going on.
5100 if (!isa<ConstantSDNode>(V.getOperand(1)))
5102 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5103 bool FoundSource = false;
5104 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5105 if (SourceVecs[j] == SourceVec) {
5106 if (MinElts[j] > EltNo)
5108 if (MaxElts[j] < EltNo)
5115 // Or record a new source if not...
5117 SourceVecs.push_back(SourceVec);
5118 MinElts.push_back(EltNo);
5119 MaxElts.push_back(EltNo);
5123 // Currently only do something sane when at most two source vectors
5125 if (SourceVecs.size() > 2)
5128 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5129 int VEXTOffsets[2] = {0, 0};
5131 // This loop extracts the usage patterns of the source vectors
5132 // and prepares appropriate SDValues for a shuffle if possible.
5133 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5134 if (SourceVecs[i].getValueType() == VT) {
5135 // No VEXT necessary
5136 ShuffleSrcs[i] = SourceVecs[i];
5139 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5140 // It probably isn't worth padding out a smaller vector just to
5141 // break it down again in a shuffle.
5145 // Since only 64-bit and 128-bit vectors are legal on ARM and
5146 // we've eliminated the other cases...
5147 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5148 "unexpected vector sizes in ReconstructShuffle");
5150 if (MaxElts[i] - MinElts[i] >= NumElts) {
5151 // Span too large for a VEXT to cope
5155 if (MinElts[i] >= NumElts) {
5156 // The extraction can just take the second half
5157 VEXTOffsets[i] = NumElts;
5158 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5160 DAG.getIntPtrConstant(NumElts));
5161 } else if (MaxElts[i] < NumElts) {
5162 // The extraction can just take the first half
5164 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5166 DAG.getIntPtrConstant(0));
5168 // An actual VEXT is needed
5169 VEXTOffsets[i] = MinElts[i];
5170 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5172 DAG.getIntPtrConstant(0));
5173 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5175 DAG.getIntPtrConstant(NumElts));
5176 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5177 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5181 SmallVector<int, 8> Mask;
5183 for (unsigned i = 0; i < NumElts; ++i) {
5184 SDValue Entry = Op.getOperand(i);
5185 if (Entry.getOpcode() == ISD::UNDEF) {
5190 SDValue ExtractVec = Entry.getOperand(0);
5191 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5192 .getOperand(1))->getSExtValue();
5193 if (ExtractVec == SourceVecs[0]) {
5194 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5196 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5200 // Final check before we try to produce nonsense...
5201 if (isShuffleMaskLegal(Mask, VT))
5202 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5208 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5209 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5210 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5211 /// are assumed to be legal.
5213 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5215 if (VT.getVectorNumElements() == 4 &&
5216 (VT.is128BitVector() || VT.is64BitVector())) {
5217 unsigned PFIndexes[4];
5218 for (unsigned i = 0; i != 4; ++i) {
5222 PFIndexes[i] = M[i];
5225 // Compute the index in the perfect shuffle table.
5226 unsigned PFTableIndex =
5227 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5228 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5229 unsigned Cost = (PFEntry >> 30);
5236 unsigned Imm, WhichResult;
5238 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5239 return (EltSize >= 32 ||
5240 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5241 isVREVMask(M, VT, 64) ||
5242 isVREVMask(M, VT, 32) ||
5243 isVREVMask(M, VT, 16) ||
5244 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5245 isVTBLMask(M, VT) ||
5246 isVTRNMask(M, VT, WhichResult) ||
5247 isVUZPMask(M, VT, WhichResult) ||
5248 isVZIPMask(M, VT, WhichResult) ||
5249 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5250 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5251 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5252 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5255 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5256 /// the specified operations to build the shuffle.
5257 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5258 SDValue RHS, SelectionDAG &DAG,
5260 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5261 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5262 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5265 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5274 OP_VUZPL, // VUZP, left result
5275 OP_VUZPR, // VUZP, right result
5276 OP_VZIPL, // VZIP, left result
5277 OP_VZIPR, // VZIP, right result
5278 OP_VTRNL, // VTRN, left result
5279 OP_VTRNR // VTRN, right result
5282 if (OpNum == OP_COPY) {
5283 if (LHSID == (1*9+2)*9+3) return LHS;
5284 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5288 SDValue OpLHS, OpRHS;
5289 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5290 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5291 EVT VT = OpLHS.getValueType();
5294 default: llvm_unreachable("Unknown shuffle opcode!");
5296 // VREV divides the vector in half and swaps within the half.
5297 if (VT.getVectorElementType() == MVT::i32 ||
5298 VT.getVectorElementType() == MVT::f32)
5299 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5300 // vrev <4 x i16> -> VREV32
5301 if (VT.getVectorElementType() == MVT::i16)
5302 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5303 // vrev <4 x i8> -> VREV16
5304 assert(VT.getVectorElementType() == MVT::i8);
5305 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5310 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5311 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5315 return DAG.getNode(ARMISD::VEXT, dl, VT,
5317 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5320 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5321 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5324 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5325 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5328 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5329 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5333 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5334 ArrayRef<int> ShuffleMask,
5335 SelectionDAG &DAG) {
5336 // Check to see if we can use the VTBL instruction.
5337 SDValue V1 = Op.getOperand(0);
5338 SDValue V2 = Op.getOperand(1);
5341 SmallVector<SDValue, 8> VTBLMask;
5342 for (ArrayRef<int>::iterator
5343 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5344 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5346 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5347 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5348 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5350 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5351 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5354 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5355 SelectionDAG &DAG) {
5357 SDValue OpLHS = Op.getOperand(0);
5358 EVT VT = OpLHS.getValueType();
5360 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5361 "Expect an v8i16/v16i8 type");
5362 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5363 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5364 // extract the first 8 bytes into the top double word and the last 8 bytes
5365 // into the bottom double word. The v8i16 case is similar.
5366 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5367 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5368 DAG.getConstant(ExtractNum, MVT::i32));
5371 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5372 SDValue V1 = Op.getOperand(0);
5373 SDValue V2 = Op.getOperand(1);
5375 EVT VT = Op.getValueType();
5376 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5378 // Convert shuffles that are directly supported on NEON to target-specific
5379 // DAG nodes, instead of keeping them as shuffles and matching them again
5380 // during code selection. This is more efficient and avoids the possibility
5381 // of inconsistencies between legalization and selection.
5382 // FIXME: floating-point vectors should be canonicalized to integer vectors
5383 // of the same time so that they get CSEd properly.
5384 ArrayRef<int> ShuffleMask = SVN->getMask();
5386 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5387 if (EltSize <= 32) {
5388 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5389 int Lane = SVN->getSplatIndex();
5390 // If this is undef splat, generate it via "just" vdup, if possible.
5391 if (Lane == -1) Lane = 0;
5393 // Test if V1 is a SCALAR_TO_VECTOR.
5394 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5395 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5397 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5398 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5400 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5401 !isa<ConstantSDNode>(V1.getOperand(0))) {
5402 bool IsScalarToVector = true;
5403 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5404 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5405 IsScalarToVector = false;
5408 if (IsScalarToVector)
5409 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5411 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5412 DAG.getConstant(Lane, MVT::i32));
5417 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5420 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5421 DAG.getConstant(Imm, MVT::i32));
5424 if (isVREVMask(ShuffleMask, VT, 64))
5425 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5426 if (isVREVMask(ShuffleMask, VT, 32))
5427 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5428 if (isVREVMask(ShuffleMask, VT, 16))
5429 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5431 if (V2->getOpcode() == ISD::UNDEF &&
5432 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5433 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5434 DAG.getConstant(Imm, MVT::i32));
5437 // Check for Neon shuffles that modify both input vectors in place.
5438 // If both results are used, i.e., if there are two shuffles with the same
5439 // source operands and with masks corresponding to both results of one of
5440 // these operations, DAG memoization will ensure that a single node is
5441 // used for both shuffles.
5442 unsigned WhichResult;
5443 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5444 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5445 V1, V2).getValue(WhichResult);
5446 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5447 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5448 V1, V2).getValue(WhichResult);
5449 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5450 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5451 V1, V2).getValue(WhichResult);
5453 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5454 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5455 V1, V1).getValue(WhichResult);
5456 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5457 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5458 V1, V1).getValue(WhichResult);
5459 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5460 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5461 V1, V1).getValue(WhichResult);
5464 // If the shuffle is not directly supported and it has 4 elements, use
5465 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5466 unsigned NumElts = VT.getVectorNumElements();
5468 unsigned PFIndexes[4];
5469 for (unsigned i = 0; i != 4; ++i) {
5470 if (ShuffleMask[i] < 0)
5473 PFIndexes[i] = ShuffleMask[i];
5476 // Compute the index in the perfect shuffle table.
5477 unsigned PFTableIndex =
5478 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5479 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5480 unsigned Cost = (PFEntry >> 30);
5483 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5486 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5487 if (EltSize >= 32) {
5488 // Do the expansion with floating-point types, since that is what the VFP
5489 // registers are defined to use, and since i64 is not legal.
5490 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5491 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5492 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5493 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5494 SmallVector<SDValue, 8> Ops;
5495 for (unsigned i = 0; i < NumElts; ++i) {
5496 if (ShuffleMask[i] < 0)
5497 Ops.push_back(DAG.getUNDEF(EltVT));
5499 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5500 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5501 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5504 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5505 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5508 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5509 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5511 if (VT == MVT::v8i8) {
5512 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5513 if (NewOp.getNode())
5520 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5521 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5522 SDValue Lane = Op.getOperand(2);
5523 if (!isa<ConstantSDNode>(Lane))
5529 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5530 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5531 SDValue Lane = Op.getOperand(1);
5532 if (!isa<ConstantSDNode>(Lane))
5535 SDValue Vec = Op.getOperand(0);
5536 if (Op.getValueType() == MVT::i32 &&
5537 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5539 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5545 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5546 // The only time a CONCAT_VECTORS operation can have legal types is when
5547 // two 64-bit vectors are concatenated to a 128-bit vector.
5548 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5549 "unexpected CONCAT_VECTORS");
5551 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5552 SDValue Op0 = Op.getOperand(0);
5553 SDValue Op1 = Op.getOperand(1);
5554 if (Op0.getOpcode() != ISD::UNDEF)
5555 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5556 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5557 DAG.getIntPtrConstant(0));
5558 if (Op1.getOpcode() != ISD::UNDEF)
5559 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5560 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5561 DAG.getIntPtrConstant(1));
5562 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5565 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5566 /// element has been zero/sign-extended, depending on the isSigned parameter,
5567 /// from an integer type half its size.
5568 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5570 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5571 EVT VT = N->getValueType(0);
5572 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5573 SDNode *BVN = N->getOperand(0).getNode();
5574 if (BVN->getValueType(0) != MVT::v4i32 ||
5575 BVN->getOpcode() != ISD::BUILD_VECTOR)
5577 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5578 unsigned HiElt = 1 - LoElt;
5579 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5580 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5581 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5582 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5583 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5586 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5587 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5590 if (Hi0->isNullValue() && Hi1->isNullValue())
5596 if (N->getOpcode() != ISD::BUILD_VECTOR)
5599 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5600 SDNode *Elt = N->getOperand(i).getNode();
5601 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5602 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5603 unsigned HalfSize = EltSize / 2;
5605 if (!isIntN(HalfSize, C->getSExtValue()))
5608 if (!isUIntN(HalfSize, C->getZExtValue()))
5619 /// isSignExtended - Check if a node is a vector value that is sign-extended
5620 /// or a constant BUILD_VECTOR with sign-extended elements.
5621 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5622 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5624 if (isExtendedBUILD_VECTOR(N, DAG, true))
5629 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5630 /// or a constant BUILD_VECTOR with zero-extended elements.
5631 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5632 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5634 if (isExtendedBUILD_VECTOR(N, DAG, false))
5639 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5640 if (OrigVT.getSizeInBits() >= 64)
5643 assert(OrigVT.isSimple() && "Expecting a simple value type");
5645 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5646 switch (OrigSimpleTy) {
5647 default: llvm_unreachable("Unexpected Vector Type");
5656 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5657 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5658 /// We insert the required extension here to get the vector to fill a D register.
5659 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5662 unsigned ExtOpcode) {
5663 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5664 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5665 // 64-bits we need to insert a new extension so that it will be 64-bits.
5666 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5667 if (OrigTy.getSizeInBits() >= 64)
5670 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5671 EVT NewVT = getExtensionTo64Bits(OrigTy);
5673 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5676 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5677 /// does not do any sign/zero extension. If the original vector is less
5678 /// than 64 bits, an appropriate extension will be added after the load to
5679 /// reach a total size of 64 bits. We have to add the extension separately
5680 /// because ARM does not have a sign/zero extending load for vectors.
5681 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5682 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5684 // The load already has the right type.
5685 if (ExtendedTy == LD->getMemoryVT())
5686 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5687 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5688 LD->isNonTemporal(), LD->isInvariant(),
5689 LD->getAlignment());
5691 // We need to create a zextload/sextload. We cannot just create a load
5692 // followed by a zext/zext node because LowerMUL is also run during normal
5693 // operation legalization where we can't create illegal types.
5694 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5695 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5696 LD->getMemoryVT(), LD->isVolatile(),
5697 LD->isNonTemporal(), LD->getAlignment());
5700 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5701 /// extending load, or BUILD_VECTOR with extended elements, return the
5702 /// unextended value. The unextended vector should be 64 bits so that it can
5703 /// be used as an operand to a VMULL instruction. If the original vector size
5704 /// before extension is less than 64 bits we add a an extension to resize
5705 /// the vector to 64 bits.
5706 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5707 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5708 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5709 N->getOperand(0)->getValueType(0),
5713 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5714 return SkipLoadExtensionForVMULL(LD, DAG);
5716 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5717 // have been legalized as a BITCAST from v4i32.
5718 if (N->getOpcode() == ISD::BITCAST) {
5719 SDNode *BVN = N->getOperand(0).getNode();
5720 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5721 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5722 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5723 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5724 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5726 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5727 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5728 EVT VT = N->getValueType(0);
5729 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5730 unsigned NumElts = VT.getVectorNumElements();
5731 MVT TruncVT = MVT::getIntegerVT(EltSize);
5732 SmallVector<SDValue, 8> Ops;
5733 for (unsigned i = 0; i != NumElts; ++i) {
5734 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5735 const APInt &CInt = C->getAPIntValue();
5736 // Element types smaller than 32 bits are not legal, so use i32 elements.
5737 // The values are implicitly truncated so sext vs. zext doesn't matter.
5738 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5740 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5741 MVT::getVectorVT(TruncVT, NumElts), Ops);
5744 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5745 unsigned Opcode = N->getOpcode();
5746 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5747 SDNode *N0 = N->getOperand(0).getNode();
5748 SDNode *N1 = N->getOperand(1).getNode();
5749 return N0->hasOneUse() && N1->hasOneUse() &&
5750 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5755 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5756 unsigned Opcode = N->getOpcode();
5757 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5758 SDNode *N0 = N->getOperand(0).getNode();
5759 SDNode *N1 = N->getOperand(1).getNode();
5760 return N0->hasOneUse() && N1->hasOneUse() &&
5761 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5766 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5767 // Multiplications are only custom-lowered for 128-bit vectors so that
5768 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5769 EVT VT = Op.getValueType();
5770 assert(VT.is128BitVector() && VT.isInteger() &&
5771 "unexpected type for custom-lowering ISD::MUL");
5772 SDNode *N0 = Op.getOperand(0).getNode();
5773 SDNode *N1 = Op.getOperand(1).getNode();
5774 unsigned NewOpc = 0;
5776 bool isN0SExt = isSignExtended(N0, DAG);
5777 bool isN1SExt = isSignExtended(N1, DAG);
5778 if (isN0SExt && isN1SExt)
5779 NewOpc = ARMISD::VMULLs;
5781 bool isN0ZExt = isZeroExtended(N0, DAG);
5782 bool isN1ZExt = isZeroExtended(N1, DAG);
5783 if (isN0ZExt && isN1ZExt)
5784 NewOpc = ARMISD::VMULLu;
5785 else if (isN1SExt || isN1ZExt) {
5786 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5787 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5788 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5789 NewOpc = ARMISD::VMULLs;
5791 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5792 NewOpc = ARMISD::VMULLu;
5794 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5796 NewOpc = ARMISD::VMULLu;
5802 if (VT == MVT::v2i64)
5803 // Fall through to expand this. It is not legal.
5806 // Other vector multiplications are legal.
5811 // Legalize to a VMULL instruction.
5814 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5816 Op0 = SkipExtensionForVMULL(N0, DAG);
5817 assert(Op0.getValueType().is64BitVector() &&
5818 Op1.getValueType().is64BitVector() &&
5819 "unexpected types for extended operands to VMULL");
5820 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5823 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5824 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5831 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5832 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5833 EVT Op1VT = Op1.getValueType();
5834 return DAG.getNode(N0->getOpcode(), DL, VT,
5835 DAG.getNode(NewOpc, DL, VT,
5836 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5837 DAG.getNode(NewOpc, DL, VT,
5838 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5842 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5844 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5845 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5846 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5847 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5848 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5849 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5850 // Get reciprocal estimate.
5851 // float4 recip = vrecpeq_f32(yf);
5852 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5853 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5854 // Because char has a smaller range than uchar, we can actually get away
5855 // without any newton steps. This requires that we use a weird bias
5856 // of 0xb000, however (again, this has been exhaustively tested).
5857 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5858 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5859 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5860 Y = DAG.getConstant(0xb000, MVT::i32);
5861 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5862 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5863 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5864 // Convert back to short.
5865 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5866 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5871 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5873 // Convert to float.
5874 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5875 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5876 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5877 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5878 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5879 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5881 // Use reciprocal estimate and one refinement step.
5882 // float4 recip = vrecpeq_f32(yf);
5883 // recip *= vrecpsq_f32(yf, recip);
5884 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5885 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5886 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5887 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5889 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5890 // Because short has a smaller range than ushort, we can actually get away
5891 // with only a single newton step. This requires that we use a weird bias
5892 // of 89, however (again, this has been exhaustively tested).
5893 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5894 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5895 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5896 N1 = DAG.getConstant(0x89, MVT::i32);
5897 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5898 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5899 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5900 // Convert back to integer and return.
5901 // return vmovn_s32(vcvt_s32_f32(result));
5902 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5903 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5907 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5908 EVT VT = Op.getValueType();
5909 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5910 "unexpected type for custom-lowering ISD::SDIV");
5913 SDValue N0 = Op.getOperand(0);
5914 SDValue N1 = Op.getOperand(1);
5917 if (VT == MVT::v8i8) {
5918 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5919 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5921 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5922 DAG.getIntPtrConstant(4));
5923 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5924 DAG.getIntPtrConstant(4));
5925 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5926 DAG.getIntPtrConstant(0));
5927 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5928 DAG.getIntPtrConstant(0));
5930 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5931 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5933 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5934 N0 = LowerCONCAT_VECTORS(N0, DAG);
5936 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5939 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5942 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5943 EVT VT = Op.getValueType();
5944 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5945 "unexpected type for custom-lowering ISD::UDIV");
5948 SDValue N0 = Op.getOperand(0);
5949 SDValue N1 = Op.getOperand(1);
5952 if (VT == MVT::v8i8) {
5953 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5954 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5956 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5957 DAG.getIntPtrConstant(4));
5958 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5959 DAG.getIntPtrConstant(4));
5960 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5961 DAG.getIntPtrConstant(0));
5962 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5963 DAG.getIntPtrConstant(0));
5965 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5966 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5968 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5969 N0 = LowerCONCAT_VECTORS(N0, DAG);
5971 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5972 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5977 // v4i16 sdiv ... Convert to float.
5978 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5979 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5980 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5981 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5982 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5983 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5985 // Use reciprocal estimate and two refinement steps.
5986 // float4 recip = vrecpeq_f32(yf);
5987 // recip *= vrecpsq_f32(yf, recip);
5988 // recip *= vrecpsq_f32(yf, recip);
5989 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5990 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5991 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5992 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5994 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5995 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5996 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5998 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5999 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6000 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6001 // and that it will never cause us to return an answer too large).
6002 // float4 result = as_float4(as_int4(xf*recip) + 2);
6003 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6004 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6005 N1 = DAG.getConstant(2, MVT::i32);
6006 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6007 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6008 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6009 // Convert back to integer and return.
6010 // return vmovn_u32(vcvt_s32_f32(result));
6011 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6012 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6016 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6017 EVT VT = Op.getNode()->getValueType(0);
6018 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6021 bool ExtraOp = false;
6022 switch (Op.getOpcode()) {
6023 default: llvm_unreachable("Invalid code");
6024 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6025 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6026 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6027 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6031 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6033 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6034 Op.getOperand(1), Op.getOperand(2));
6037 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6038 assert(Subtarget->isTargetDarwin());
6040 // For iOS, we want to call an alternative entry point: __sincos_stret,
6041 // return values are passed via sret.
6043 SDValue Arg = Op.getOperand(0);
6044 EVT ArgVT = Arg.getValueType();
6045 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6047 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6048 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6050 // Pair of floats / doubles used to pass the result.
6051 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6053 // Create stack object for sret.
6054 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6055 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6056 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6057 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6063 Entry.Ty = RetTy->getPointerTo();
6064 Entry.isSExt = false;
6065 Entry.isZExt = false;
6066 Entry.isSRet = true;
6067 Args.push_back(Entry);
6071 Entry.isSExt = false;
6072 Entry.isZExt = false;
6073 Args.push_back(Entry);
6075 const char *LibcallName = (ArgVT == MVT::f64)
6076 ? "__sincos_stret" : "__sincosf_stret";
6077 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6079 TargetLowering::CallLoweringInfo CLI(DAG);
6080 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6081 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6083 .setDiscardResult();
6085 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6087 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6088 MachinePointerInfo(), false, false, false, 0);
6090 // Address of cos field.
6091 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6092 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6093 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6094 MachinePointerInfo(), false, false, false, 0);
6096 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6097 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6098 LoadSin.getValue(0), LoadCos.getValue(0));
6101 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6102 // Monotonic load/store is legal for all targets
6103 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6106 // Acquire/Release load/store is not legal for targets without a
6107 // dmb or equivalent available.
6111 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6112 SmallVectorImpl<SDValue> &Results,
6114 const ARMSubtarget *Subtarget) {
6116 SDValue Cycles32, OutChain;
6118 if (Subtarget->hasPerfMon()) {
6119 // Under Power Management extensions, the cycle-count is:
6120 // mrc p15, #0, <Rt>, c9, c13, #0
6121 SDValue Ops[] = { N->getOperand(0), // Chain
6122 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6123 DAG.getConstant(15, MVT::i32),
6124 DAG.getConstant(0, MVT::i32),
6125 DAG.getConstant(9, MVT::i32),
6126 DAG.getConstant(13, MVT::i32),
6127 DAG.getConstant(0, MVT::i32)
6130 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6131 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6132 OutChain = Cycles32.getValue(1);
6134 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6135 // there are older ARM CPUs that have implementation-specific ways of
6136 // obtaining this information (FIXME!).
6137 Cycles32 = DAG.getConstant(0, MVT::i32);
6138 OutChain = DAG.getEntryNode();
6142 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6143 Cycles32, DAG.getConstant(0, MVT::i32));
6144 Results.push_back(Cycles64);
6145 Results.push_back(OutChain);
6148 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6149 switch (Op.getOpcode()) {
6150 default: llvm_unreachable("Don't know how to custom lower this!");
6151 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6152 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6153 case ISD::GlobalAddress:
6154 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6155 default: llvm_unreachable("unknown object format");
6157 return LowerGlobalAddressWindows(Op, DAG);
6159 return LowerGlobalAddressELF(Op, DAG);
6161 return LowerGlobalAddressDarwin(Op, DAG);
6163 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6164 case ISD::SELECT: return LowerSELECT(Op, DAG);
6165 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6166 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6167 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6168 case ISD::VASTART: return LowerVASTART(Op, DAG);
6169 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6170 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6171 case ISD::SINT_TO_FP:
6172 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6173 case ISD::FP_TO_SINT:
6174 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6175 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6176 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6177 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6178 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6179 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6180 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6181 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6183 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6186 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6187 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6188 case ISD::SRL_PARTS:
6189 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6190 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6191 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6192 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6193 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6194 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6195 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6196 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6197 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6198 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6199 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6200 case ISD::MUL: return LowerMUL(Op, DAG);
6201 case ISD::SDIV: return LowerSDIV(Op, DAG);
6202 case ISD::UDIV: return LowerUDIV(Op, DAG);
6206 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6211 return LowerXALUO(Op, DAG);
6212 case ISD::ATOMIC_LOAD:
6213 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6214 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6216 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6220 /// ReplaceNodeResults - Replace the results of node with an illegal result
6221 /// type with new values built out of custom code.
6222 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6223 SmallVectorImpl<SDValue>&Results,
6224 SelectionDAG &DAG) const {
6226 switch (N->getOpcode()) {
6228 llvm_unreachable("Don't know how to custom expand this!");
6230 Res = ExpandBITCAST(N, DAG);
6234 Res = Expand64BitShift(N, DAG, Subtarget);
6236 case ISD::READCYCLECOUNTER:
6237 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6241 Results.push_back(Res);
6244 //===----------------------------------------------------------------------===//
6245 // ARM Scheduler Hooks
6246 //===----------------------------------------------------------------------===//
6248 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6249 /// registers the function context.
6250 void ARMTargetLowering::
6251 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6252 MachineBasicBlock *DispatchBB, int FI) const {
6253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6254 DebugLoc dl = MI->getDebugLoc();
6255 MachineFunction *MF = MBB->getParent();
6256 MachineRegisterInfo *MRI = &MF->getRegInfo();
6257 MachineConstantPool *MCP = MF->getConstantPool();
6258 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6259 const Function *F = MF->getFunction();
6261 bool isThumb = Subtarget->isThumb();
6262 bool isThumb2 = Subtarget->isThumb2();
6264 unsigned PCLabelId = AFI->createPICLabelUId();
6265 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6266 ARMConstantPoolValue *CPV =
6267 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6268 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6270 const TargetRegisterClass *TRC = isThumb ?
6271 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6272 (const TargetRegisterClass*)&ARM::GPRRegClass;
6274 // Grab constant pool and fixed stack memory operands.
6275 MachineMemOperand *CPMMO =
6276 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6277 MachineMemOperand::MOLoad, 4, 4);
6279 MachineMemOperand *FIMMOSt =
6280 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6281 MachineMemOperand::MOStore, 4, 4);
6283 // Load the address of the dispatch MBB into the jump buffer.
6285 // Incoming value: jbuf
6286 // ldr.n r5, LCPI1_1
6289 // str r5, [$jbuf, #+4] ; &jbuf[1]
6290 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6291 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6292 .addConstantPoolIndex(CPI)
6293 .addMemOperand(CPMMO));
6294 // Set the low bit because of thumb mode.
6295 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6297 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6298 .addReg(NewVReg1, RegState::Kill)
6300 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6301 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6302 .addReg(NewVReg2, RegState::Kill)
6304 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6305 .addReg(NewVReg3, RegState::Kill)
6307 .addImm(36) // &jbuf[1] :: pc
6308 .addMemOperand(FIMMOSt));
6309 } else if (isThumb) {
6310 // Incoming value: jbuf
6311 // ldr.n r1, LCPI1_4
6315 // add r2, $jbuf, #+4 ; &jbuf[1]
6317 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6318 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6319 .addConstantPoolIndex(CPI)
6320 .addMemOperand(CPMMO));
6321 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6322 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6323 .addReg(NewVReg1, RegState::Kill)
6325 // Set the low bit because of thumb mode.
6326 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6327 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6328 .addReg(ARM::CPSR, RegState::Define)
6330 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6331 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6332 .addReg(ARM::CPSR, RegState::Define)
6333 .addReg(NewVReg2, RegState::Kill)
6334 .addReg(NewVReg3, RegState::Kill));
6335 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6336 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6338 .addImm(36)); // &jbuf[1] :: pc
6339 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6340 .addReg(NewVReg4, RegState::Kill)
6341 .addReg(NewVReg5, RegState::Kill)
6343 .addMemOperand(FIMMOSt));
6345 // Incoming value: jbuf
6348 // str r1, [$jbuf, #+4] ; &jbuf[1]
6349 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6350 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6351 .addConstantPoolIndex(CPI)
6353 .addMemOperand(CPMMO));
6354 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6355 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6356 .addReg(NewVReg1, RegState::Kill)
6357 .addImm(PCLabelId));
6358 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6359 .addReg(NewVReg2, RegState::Kill)
6361 .addImm(36) // &jbuf[1] :: pc
6362 .addMemOperand(FIMMOSt));
6366 MachineBasicBlock *ARMTargetLowering::
6367 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6368 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6369 DebugLoc dl = MI->getDebugLoc();
6370 MachineFunction *MF = MBB->getParent();
6371 MachineRegisterInfo *MRI = &MF->getRegInfo();
6372 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6373 MachineFrameInfo *MFI = MF->getFrameInfo();
6374 int FI = MFI->getFunctionContextIndex();
6376 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6377 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6378 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6380 // Get a mapping of the call site numbers to all of the landing pads they're
6382 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6383 unsigned MaxCSNum = 0;
6384 MachineModuleInfo &MMI = MF->getMMI();
6385 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6387 if (!BB->isLandingPad()) continue;
6389 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6391 for (MachineBasicBlock::iterator
6392 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6393 if (!II->isEHLabel()) continue;
6395 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6396 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6398 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6399 for (SmallVectorImpl<unsigned>::iterator
6400 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6401 CSI != CSE; ++CSI) {
6402 CallSiteNumToLPad[*CSI].push_back(BB);
6403 MaxCSNum = std::max(MaxCSNum, *CSI);
6409 // Get an ordered list of the machine basic blocks for the jump table.
6410 std::vector<MachineBasicBlock*> LPadList;
6411 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6412 LPadList.reserve(CallSiteNumToLPad.size());
6413 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6414 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6415 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6416 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6417 LPadList.push_back(*II);
6418 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6422 assert(!LPadList.empty() &&
6423 "No landing pad destinations for the dispatch jump table!");
6425 // Create the jump table and associated information.
6426 MachineJumpTableInfo *JTI =
6427 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6428 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6429 unsigned UId = AFI->createJumpTableUId();
6430 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6432 // Create the MBBs for the dispatch code.
6434 // Shove the dispatch's address into the return slot in the function context.
6435 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6436 DispatchBB->setIsLandingPad();
6438 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6439 unsigned trap_opcode;
6440 if (Subtarget->isThumb())
6441 trap_opcode = ARM::tTRAP;
6443 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6445 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6446 DispatchBB->addSuccessor(TrapBB);
6448 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6449 DispatchBB->addSuccessor(DispContBB);
6452 MF->insert(MF->end(), DispatchBB);
6453 MF->insert(MF->end(), DispContBB);
6454 MF->insert(MF->end(), TrapBB);
6456 // Insert code into the entry block that creates and registers the function
6458 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6460 MachineMemOperand *FIMMOLd =
6461 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6462 MachineMemOperand::MOLoad |
6463 MachineMemOperand::MOVolatile, 4, 4);
6465 MachineInstrBuilder MIB;
6466 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6468 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6469 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6471 // Add a register mask with no preserved registers. This results in all
6472 // registers being marked as clobbered.
6473 MIB.addRegMask(RI.getNoPreservedMask());
6475 unsigned NumLPads = LPadList.size();
6476 if (Subtarget->isThumb2()) {
6477 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6478 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6481 .addMemOperand(FIMMOLd));
6483 if (NumLPads < 256) {
6484 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6486 .addImm(LPadList.size()));
6488 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6489 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6490 .addImm(NumLPads & 0xFFFF));
6492 unsigned VReg2 = VReg1;
6493 if ((NumLPads & 0xFFFF0000) != 0) {
6494 VReg2 = MRI->createVirtualRegister(TRC);
6495 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6497 .addImm(NumLPads >> 16));
6500 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6505 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6510 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6511 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6512 .addJumpTableIndex(MJTI)
6515 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6518 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6519 .addReg(NewVReg3, RegState::Kill)
6521 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6523 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6524 .addReg(NewVReg4, RegState::Kill)
6526 .addJumpTableIndex(MJTI)
6528 } else if (Subtarget->isThumb()) {
6529 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6530 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6533 .addMemOperand(FIMMOLd));
6535 if (NumLPads < 256) {
6536 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6540 MachineConstantPool *ConstantPool = MF->getConstantPool();
6541 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6542 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6544 // MachineConstantPool wants an explicit alignment.
6545 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6547 Align = getDataLayout()->getTypeAllocSize(C->getType());
6548 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6550 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6551 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6552 .addReg(VReg1, RegState::Define)
6553 .addConstantPoolIndex(Idx));
6554 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6559 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6564 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6565 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6566 .addReg(ARM::CPSR, RegState::Define)
6570 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6571 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6572 .addJumpTableIndex(MJTI)
6575 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6576 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6577 .addReg(ARM::CPSR, RegState::Define)
6578 .addReg(NewVReg2, RegState::Kill)
6581 MachineMemOperand *JTMMOLd =
6582 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6583 MachineMemOperand::MOLoad, 4, 4);
6585 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6586 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6587 .addReg(NewVReg4, RegState::Kill)
6589 .addMemOperand(JTMMOLd));
6591 unsigned NewVReg6 = NewVReg5;
6592 if (RelocM == Reloc::PIC_) {
6593 NewVReg6 = MRI->createVirtualRegister(TRC);
6594 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6595 .addReg(ARM::CPSR, RegState::Define)
6596 .addReg(NewVReg5, RegState::Kill)
6600 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6601 .addReg(NewVReg6, RegState::Kill)
6602 .addJumpTableIndex(MJTI)
6605 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6606 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6609 .addMemOperand(FIMMOLd));
6611 if (NumLPads < 256) {
6612 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6615 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6616 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6617 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6618 .addImm(NumLPads & 0xFFFF));
6620 unsigned VReg2 = VReg1;
6621 if ((NumLPads & 0xFFFF0000) != 0) {
6622 VReg2 = MRI->createVirtualRegister(TRC);
6623 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6625 .addImm(NumLPads >> 16));
6628 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6632 MachineConstantPool *ConstantPool = MF->getConstantPool();
6633 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6634 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6636 // MachineConstantPool wants an explicit alignment.
6637 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6639 Align = getDataLayout()->getTypeAllocSize(C->getType());
6640 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6642 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6643 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6644 .addReg(VReg1, RegState::Define)
6645 .addConstantPoolIndex(Idx)
6647 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6649 .addReg(VReg1, RegState::Kill));
6652 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6657 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6659 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6661 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6662 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6663 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6664 .addJumpTableIndex(MJTI)
6667 MachineMemOperand *JTMMOLd =
6668 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6669 MachineMemOperand::MOLoad, 4, 4);
6670 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6672 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6673 .addReg(NewVReg3, RegState::Kill)
6676 .addMemOperand(JTMMOLd));
6678 if (RelocM == Reloc::PIC_) {
6679 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6680 .addReg(NewVReg5, RegState::Kill)
6682 .addJumpTableIndex(MJTI)
6685 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6686 .addReg(NewVReg5, RegState::Kill)
6687 .addJumpTableIndex(MJTI)
6692 // Add the jump table entries as successors to the MBB.
6693 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6694 for (std::vector<MachineBasicBlock*>::iterator
6695 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6696 MachineBasicBlock *CurMBB = *I;
6697 if (SeenMBBs.insert(CurMBB))
6698 DispContBB->addSuccessor(CurMBB);
6701 // N.B. the order the invoke BBs are processed in doesn't matter here.
6702 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6703 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6704 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6705 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6706 MachineBasicBlock *BB = *I;
6708 // Remove the landing pad successor from the invoke block and replace it
6709 // with the new dispatch block.
6710 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6712 while (!Successors.empty()) {
6713 MachineBasicBlock *SMBB = Successors.pop_back_val();
6714 if (SMBB->isLandingPad()) {
6715 BB->removeSuccessor(SMBB);
6716 MBBLPads.push_back(SMBB);
6720 BB->addSuccessor(DispatchBB);
6722 // Find the invoke call and mark all of the callee-saved registers as
6723 // 'implicit defined' so that they're spilled. This prevents code from
6724 // moving instructions to before the EH block, where they will never be
6726 for (MachineBasicBlock::reverse_iterator
6727 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6728 if (!II->isCall()) continue;
6730 DenseMap<unsigned, bool> DefRegs;
6731 for (MachineInstr::mop_iterator
6732 OI = II->operands_begin(), OE = II->operands_end();
6734 if (!OI->isReg()) continue;
6735 DefRegs[OI->getReg()] = true;
6738 MachineInstrBuilder MIB(*MF, &*II);
6740 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6741 unsigned Reg = SavedRegs[i];
6742 if (Subtarget->isThumb2() &&
6743 !ARM::tGPRRegClass.contains(Reg) &&
6744 !ARM::hGPRRegClass.contains(Reg))
6746 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6748 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6751 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6758 // Mark all former landing pads as non-landing pads. The dispatch is the only
6760 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6761 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6762 (*I)->setIsLandingPad(false);
6764 // The instruction is gone now.
6765 MI->eraseFromParent();
6771 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6772 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6773 E = MBB->succ_end(); I != E; ++I)
6776 llvm_unreachable("Expecting a BB with two successors!");
6779 /// Return the load opcode for a given load size. If load size >= 8,
6780 /// neon opcode will be returned.
6781 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6783 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6784 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6786 return LdSize == 4 ? ARM::tLDRi
6787 : LdSize == 2 ? ARM::tLDRHi
6788 : LdSize == 1 ? ARM::tLDRBi : 0;
6790 return LdSize == 4 ? ARM::t2LDR_POST
6791 : LdSize == 2 ? ARM::t2LDRH_POST
6792 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6793 return LdSize == 4 ? ARM::LDR_POST_IMM
6794 : LdSize == 2 ? ARM::LDRH_POST
6795 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6798 /// Return the store opcode for a given store size. If store size >= 8,
6799 /// neon opcode will be returned.
6800 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6802 return StSize == 16 ? ARM::VST1q32wb_fixed
6803 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6805 return StSize == 4 ? ARM::tSTRi
6806 : StSize == 2 ? ARM::tSTRHi
6807 : StSize == 1 ? ARM::tSTRBi : 0;
6809 return StSize == 4 ? ARM::t2STR_POST
6810 : StSize == 2 ? ARM::t2STRH_POST
6811 : StSize == 1 ? ARM::t2STRB_POST : 0;
6812 return StSize == 4 ? ARM::STR_POST_IMM
6813 : StSize == 2 ? ARM::STRH_POST
6814 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6817 /// Emit a post-increment load operation with given size. The instructions
6818 /// will be added to BB at Pos.
6819 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6820 const TargetInstrInfo *TII, DebugLoc dl,
6821 unsigned LdSize, unsigned Data, unsigned AddrIn,
6822 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6823 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6824 assert(LdOpc != 0 && "Should have a load opcode");
6826 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6827 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6829 } else if (IsThumb1) {
6830 // load + update AddrIn
6831 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6832 .addReg(AddrIn).addImm(0));
6833 MachineInstrBuilder MIB =
6834 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6835 MIB = AddDefaultT1CC(MIB);
6836 MIB.addReg(AddrIn).addImm(LdSize);
6837 AddDefaultPred(MIB);
6838 } else if (IsThumb2) {
6839 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6840 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6843 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6844 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6845 .addReg(0).addImm(LdSize));
6849 /// Emit a post-increment store operation with given size. The instructions
6850 /// will be added to BB at Pos.
6851 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6852 const TargetInstrInfo *TII, DebugLoc dl,
6853 unsigned StSize, unsigned Data, unsigned AddrIn,
6854 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6855 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6856 assert(StOpc != 0 && "Should have a store opcode");
6858 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6859 .addReg(AddrIn).addImm(0).addReg(Data));
6860 } else if (IsThumb1) {
6861 // store + update AddrIn
6862 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6863 .addReg(AddrIn).addImm(0));
6864 MachineInstrBuilder MIB =
6865 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6866 MIB = AddDefaultT1CC(MIB);
6867 MIB.addReg(AddrIn).addImm(StSize);
6868 AddDefaultPred(MIB);
6869 } else if (IsThumb2) {
6870 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6871 .addReg(Data).addReg(AddrIn).addImm(StSize));
6873 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6874 .addReg(Data).addReg(AddrIn).addReg(0)
6880 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6881 MachineBasicBlock *BB) const {
6882 // This pseudo instruction has 3 operands: dst, src, size
6883 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6884 // Otherwise, we will generate unrolled scalar copies.
6885 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6886 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6887 MachineFunction::iterator It = BB;
6890 unsigned dest = MI->getOperand(0).getReg();
6891 unsigned src = MI->getOperand(1).getReg();
6892 unsigned SizeVal = MI->getOperand(2).getImm();
6893 unsigned Align = MI->getOperand(3).getImm();
6894 DebugLoc dl = MI->getDebugLoc();
6896 MachineFunction *MF = BB->getParent();
6897 MachineRegisterInfo &MRI = MF->getRegInfo();
6898 unsigned UnitSize = 0;
6899 const TargetRegisterClass *TRC = nullptr;
6900 const TargetRegisterClass *VecTRC = nullptr;
6902 bool IsThumb1 = Subtarget->isThumb1Only();
6903 bool IsThumb2 = Subtarget->isThumb2();
6907 } else if (Align & 2) {
6910 // Check whether we can use NEON instructions.
6911 if (!MF->getFunction()->getAttributes().
6912 hasAttribute(AttributeSet::FunctionIndex,
6913 Attribute::NoImplicitFloat) &&
6914 Subtarget->hasNEON()) {
6915 if ((Align % 16 == 0) && SizeVal >= 16)
6917 else if ((Align % 8 == 0) && SizeVal >= 8)
6920 // Can't use NEON instructions.
6925 // Select the correct opcode and register class for unit size load/store
6926 bool IsNeon = UnitSize >= 8;
6927 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6928 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6930 VecTRC = UnitSize == 16
6931 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6933 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6936 unsigned BytesLeft = SizeVal % UnitSize;
6937 unsigned LoopSize = SizeVal - BytesLeft;
6939 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6940 // Use LDR and STR to copy.
6941 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6942 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6943 unsigned srcIn = src;
6944 unsigned destIn = dest;
6945 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6946 unsigned srcOut = MRI.createVirtualRegister(TRC);
6947 unsigned destOut = MRI.createVirtualRegister(TRC);
6948 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6949 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6950 IsThumb1, IsThumb2);
6951 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6952 IsThumb1, IsThumb2);
6957 // Handle the leftover bytes with LDRB and STRB.
6958 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6959 // [destOut] = STRB_POST(scratch, destIn, 1)
6960 for (unsigned i = 0; i < BytesLeft; i++) {
6961 unsigned srcOut = MRI.createVirtualRegister(TRC);
6962 unsigned destOut = MRI.createVirtualRegister(TRC);
6963 unsigned scratch = MRI.createVirtualRegister(TRC);
6964 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6965 IsThumb1, IsThumb2);
6966 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6967 IsThumb1, IsThumb2);
6971 MI->eraseFromParent(); // The instruction is gone now.
6975 // Expand the pseudo op to a loop.
6978 // movw varEnd, # --> with thumb2
6980 // ldrcp varEnd, idx --> without thumb2
6981 // fallthrough --> loopMBB
6983 // PHI varPhi, varEnd, varLoop
6984 // PHI srcPhi, src, srcLoop
6985 // PHI destPhi, dst, destLoop
6986 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6987 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6988 // subs varLoop, varPhi, #UnitSize
6990 // fallthrough --> exitMBB
6992 // epilogue to handle left-over bytes
6993 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6994 // [destOut] = STRB_POST(scratch, destLoop, 1)
6995 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6996 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6997 MF->insert(It, loopMBB);
6998 MF->insert(It, exitMBB);
7000 // Transfer the remainder of BB and its successor edges to exitMBB.
7001 exitMBB->splice(exitMBB->begin(), BB,
7002 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7003 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7005 // Load an immediate to varEnd.
7006 unsigned varEnd = MRI.createVirtualRegister(TRC);
7008 unsigned Vtmp = varEnd;
7009 if ((LoopSize & 0xFFFF0000) != 0)
7010 Vtmp = MRI.createVirtualRegister(TRC);
7011 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7012 .addImm(LoopSize & 0xFFFF));
7014 if ((LoopSize & 0xFFFF0000) != 0)
7015 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7016 .addReg(Vtmp).addImm(LoopSize >> 16));
7018 MachineConstantPool *ConstantPool = MF->getConstantPool();
7019 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7020 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7022 // MachineConstantPool wants an explicit alignment.
7023 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7025 Align = getDataLayout()->getTypeAllocSize(C->getType());
7026 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7029 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7030 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7032 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7033 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7035 BB->addSuccessor(loopMBB);
7037 // Generate the loop body:
7038 // varPhi = PHI(varLoop, varEnd)
7039 // srcPhi = PHI(srcLoop, src)
7040 // destPhi = PHI(destLoop, dst)
7041 MachineBasicBlock *entryBB = BB;
7043 unsigned varLoop = MRI.createVirtualRegister(TRC);
7044 unsigned varPhi = MRI.createVirtualRegister(TRC);
7045 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7046 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7047 unsigned destLoop = MRI.createVirtualRegister(TRC);
7048 unsigned destPhi = MRI.createVirtualRegister(TRC);
7050 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7051 .addReg(varLoop).addMBB(loopMBB)
7052 .addReg(varEnd).addMBB(entryBB);
7053 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7054 .addReg(srcLoop).addMBB(loopMBB)
7055 .addReg(src).addMBB(entryBB);
7056 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7057 .addReg(destLoop).addMBB(loopMBB)
7058 .addReg(dest).addMBB(entryBB);
7060 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7061 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7062 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7063 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7064 IsThumb1, IsThumb2);
7065 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7066 IsThumb1, IsThumb2);
7068 // Decrement loop variable by UnitSize.
7070 MachineInstrBuilder MIB =
7071 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7072 MIB = AddDefaultT1CC(MIB);
7073 MIB.addReg(varPhi).addImm(UnitSize);
7074 AddDefaultPred(MIB);
7076 MachineInstrBuilder MIB =
7077 BuildMI(*BB, BB->end(), dl,
7078 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7079 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7080 MIB->getOperand(5).setReg(ARM::CPSR);
7081 MIB->getOperand(5).setIsDef(true);
7083 BuildMI(*BB, BB->end(), dl,
7084 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7085 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7087 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7088 BB->addSuccessor(loopMBB);
7089 BB->addSuccessor(exitMBB);
7091 // Add epilogue to handle BytesLeft.
7093 MachineInstr *StartOfExit = exitMBB->begin();
7095 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7096 // [destOut] = STRB_POST(scratch, destLoop, 1)
7097 unsigned srcIn = srcLoop;
7098 unsigned destIn = destLoop;
7099 for (unsigned i = 0; i < BytesLeft; i++) {
7100 unsigned srcOut = MRI.createVirtualRegister(TRC);
7101 unsigned destOut = MRI.createVirtualRegister(TRC);
7102 unsigned scratch = MRI.createVirtualRegister(TRC);
7103 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7104 IsThumb1, IsThumb2);
7105 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7106 IsThumb1, IsThumb2);
7111 MI->eraseFromParent(); // The instruction is gone now.
7116 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7117 MachineBasicBlock *BB) const {
7118 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7119 DebugLoc dl = MI->getDebugLoc();
7120 bool isThumb2 = Subtarget->isThumb2();
7121 switch (MI->getOpcode()) {
7124 llvm_unreachable("Unexpected instr type to insert");
7126 // The Thumb2 pre-indexed stores have the same MI operands, they just
7127 // define them differently in the .td files from the isel patterns, so
7128 // they need pseudos.
7129 case ARM::t2STR_preidx:
7130 MI->setDesc(TII->get(ARM::t2STR_PRE));
7132 case ARM::t2STRB_preidx:
7133 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7135 case ARM::t2STRH_preidx:
7136 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7139 case ARM::STRi_preidx:
7140 case ARM::STRBi_preidx: {
7141 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7142 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7143 // Decode the offset.
7144 unsigned Offset = MI->getOperand(4).getImm();
7145 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7146 Offset = ARM_AM::getAM2Offset(Offset);
7150 MachineMemOperand *MMO = *MI->memoperands_begin();
7151 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7152 .addOperand(MI->getOperand(0)) // Rn_wb
7153 .addOperand(MI->getOperand(1)) // Rt
7154 .addOperand(MI->getOperand(2)) // Rn
7155 .addImm(Offset) // offset (skip GPR==zero_reg)
7156 .addOperand(MI->getOperand(5)) // pred
7157 .addOperand(MI->getOperand(6))
7158 .addMemOperand(MMO);
7159 MI->eraseFromParent();
7162 case ARM::STRr_preidx:
7163 case ARM::STRBr_preidx:
7164 case ARM::STRH_preidx: {
7166 switch (MI->getOpcode()) {
7167 default: llvm_unreachable("unexpected opcode!");
7168 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7169 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7170 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7172 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7173 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7174 MIB.addOperand(MI->getOperand(i));
7175 MI->eraseFromParent();
7179 case ARM::tMOVCCr_pseudo: {
7180 // To "insert" a SELECT_CC instruction, we actually have to insert the
7181 // diamond control-flow pattern. The incoming instruction knows the
7182 // destination vreg to set, the condition code register to branch on, the
7183 // true/false values to select between, and a branch opcode to use.
7184 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7185 MachineFunction::iterator It = BB;
7191 // cmpTY ccX, r1, r2
7193 // fallthrough --> copy0MBB
7194 MachineBasicBlock *thisMBB = BB;
7195 MachineFunction *F = BB->getParent();
7196 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7197 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7198 F->insert(It, copy0MBB);
7199 F->insert(It, sinkMBB);
7201 // Transfer the remainder of BB and its successor edges to sinkMBB.
7202 sinkMBB->splice(sinkMBB->begin(), BB,
7203 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7204 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7206 BB->addSuccessor(copy0MBB);
7207 BB->addSuccessor(sinkMBB);
7209 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7210 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7213 // %FalseValue = ...
7214 // # fallthrough to sinkMBB
7217 // Update machine-CFG edges
7218 BB->addSuccessor(sinkMBB);
7221 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7224 BuildMI(*BB, BB->begin(), dl,
7225 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7226 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7227 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7229 MI->eraseFromParent(); // The pseudo instruction is gone now.
7234 case ARM::BCCZi64: {
7235 // If there is an unconditional branch to the other successor, remove it.
7236 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7238 // Compare both parts that make up the double comparison separately for
7240 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7242 unsigned LHS1 = MI->getOperand(1).getReg();
7243 unsigned LHS2 = MI->getOperand(2).getReg();
7245 AddDefaultPred(BuildMI(BB, dl,
7246 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7247 .addReg(LHS1).addImm(0));
7248 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7249 .addReg(LHS2).addImm(0)
7250 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7252 unsigned RHS1 = MI->getOperand(3).getReg();
7253 unsigned RHS2 = MI->getOperand(4).getReg();
7254 AddDefaultPred(BuildMI(BB, dl,
7255 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7256 .addReg(LHS1).addReg(RHS1));
7257 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7258 .addReg(LHS2).addReg(RHS2)
7259 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7262 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7263 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7264 if (MI->getOperand(0).getImm() == ARMCC::NE)
7265 std::swap(destMBB, exitMBB);
7267 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7268 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7270 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7272 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7274 MI->eraseFromParent(); // The pseudo instruction is gone now.
7278 case ARM::Int_eh_sjlj_setjmp:
7279 case ARM::Int_eh_sjlj_setjmp_nofp:
7280 case ARM::tInt_eh_sjlj_setjmp:
7281 case ARM::t2Int_eh_sjlj_setjmp:
7282 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7283 EmitSjLjDispatchBlock(MI, BB);
7288 // To insert an ABS instruction, we have to insert the
7289 // diamond control-flow pattern. The incoming instruction knows the
7290 // source vreg to test against 0, the destination vreg to set,
7291 // the condition code register to branch on, the
7292 // true/false values to select between, and a branch opcode to use.
7297 // BCC (branch to SinkBB if V0 >= 0)
7298 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7299 // SinkBB: V1 = PHI(V2, V3)
7300 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7301 MachineFunction::iterator BBI = BB;
7303 MachineFunction *Fn = BB->getParent();
7304 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7305 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7306 Fn->insert(BBI, RSBBB);
7307 Fn->insert(BBI, SinkBB);
7309 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7310 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7311 bool isThumb2 = Subtarget->isThumb2();
7312 MachineRegisterInfo &MRI = Fn->getRegInfo();
7313 // In Thumb mode S must not be specified if source register is the SP or
7314 // PC and if destination register is the SP, so restrict register class
7315 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7316 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7317 (const TargetRegisterClass*)&ARM::GPRRegClass);
7319 // Transfer the remainder of BB and its successor edges to sinkMBB.
7320 SinkBB->splice(SinkBB->begin(), BB,
7321 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7322 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7324 BB->addSuccessor(RSBBB);
7325 BB->addSuccessor(SinkBB);
7327 // fall through to SinkMBB
7328 RSBBB->addSuccessor(SinkBB);
7330 // insert a cmp at the end of BB
7331 AddDefaultPred(BuildMI(BB, dl,
7332 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7333 .addReg(ABSSrcReg).addImm(0));
7335 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7337 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7338 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7340 // insert rsbri in RSBBB
7341 // Note: BCC and rsbri will be converted into predicated rsbmi
7342 // by if-conversion pass
7343 BuildMI(*RSBBB, RSBBB->begin(), dl,
7344 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7345 .addReg(ABSSrcReg, RegState::Kill)
7346 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7348 // insert PHI in SinkBB,
7349 // reuse ABSDstReg to not change uses of ABS instruction
7350 BuildMI(*SinkBB, SinkBB->begin(), dl,
7351 TII->get(ARM::PHI), ABSDstReg)
7352 .addReg(NewRsbDstReg).addMBB(RSBBB)
7353 .addReg(ABSSrcReg).addMBB(BB);
7355 // remove ABS instruction
7356 MI->eraseFromParent();
7358 // return last added BB
7361 case ARM::COPY_STRUCT_BYVAL_I32:
7363 return EmitStructByval(MI, BB);
7367 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7368 SDNode *Node) const {
7369 if (!MI->hasPostISelHook()) {
7370 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7371 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7375 const MCInstrDesc *MCID = &MI->getDesc();
7376 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7377 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7378 // operand is still set to noreg. If needed, set the optional operand's
7379 // register to CPSR, and remove the redundant implicit def.
7381 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7383 // Rename pseudo opcodes.
7384 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7386 const ARMBaseInstrInfo *TII =
7387 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7388 MCID = &TII->get(NewOpc);
7390 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7391 "converted opcode should be the same except for cc_out");
7395 // Add the optional cc_out operand
7396 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7398 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7400 // Any ARM instruction that sets the 's' bit should specify an optional
7401 // "cc_out" operand in the last operand position.
7402 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7403 assert(!NewOpc && "Optional cc_out operand required");
7406 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7407 // since we already have an optional CPSR def.
7408 bool definesCPSR = false;
7409 bool deadCPSR = false;
7410 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7412 const MachineOperand &MO = MI->getOperand(i);
7413 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7417 MI->RemoveOperand(i);
7422 assert(!NewOpc && "Optional cc_out operand required");
7425 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7427 assert(!MI->getOperand(ccOutIdx).getReg() &&
7428 "expect uninitialized optional cc_out operand");
7432 // If this instruction was defined with an optional CPSR def and its dag node
7433 // had a live implicit CPSR def, then activate the optional CPSR def.
7434 MachineOperand &MO = MI->getOperand(ccOutIdx);
7435 MO.setReg(ARM::CPSR);
7439 //===----------------------------------------------------------------------===//
7440 // ARM Optimization Hooks
7441 //===----------------------------------------------------------------------===//
7443 // Helper function that checks if N is a null or all ones constant.
7444 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7445 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7448 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7451 // Return true if N is conditionally 0 or all ones.
7452 // Detects these expressions where cc is an i1 value:
7454 // (select cc 0, y) [AllOnes=0]
7455 // (select cc y, 0) [AllOnes=0]
7456 // (zext cc) [AllOnes=0]
7457 // (sext cc) [AllOnes=0/1]
7458 // (select cc -1, y) [AllOnes=1]
7459 // (select cc y, -1) [AllOnes=1]
7461 // Invert is set when N is the null/all ones constant when CC is false.
7462 // OtherOp is set to the alternative value of N.
7463 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7464 SDValue &CC, bool &Invert,
7466 SelectionDAG &DAG) {
7467 switch (N->getOpcode()) {
7468 default: return false;
7470 CC = N->getOperand(0);
7471 SDValue N1 = N->getOperand(1);
7472 SDValue N2 = N->getOperand(2);
7473 if (isZeroOrAllOnes(N1, AllOnes)) {
7478 if (isZeroOrAllOnes(N2, AllOnes)) {
7485 case ISD::ZERO_EXTEND:
7486 // (zext cc) can never be the all ones value.
7490 case ISD::SIGN_EXTEND: {
7491 EVT VT = N->getValueType(0);
7492 CC = N->getOperand(0);
7493 if (CC.getValueType() != MVT::i1)
7497 // When looking for an AllOnes constant, N is an sext, and the 'other'
7499 OtherOp = DAG.getConstant(0, VT);
7500 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7501 // When looking for a 0 constant, N can be zext or sext.
7502 OtherOp = DAG.getConstant(1, VT);
7504 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7510 // Combine a constant select operand into its use:
7512 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7513 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7514 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7515 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7516 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7518 // The transform is rejected if the select doesn't have a constant operand that
7519 // is null, or all ones when AllOnes is set.
7521 // Also recognize sext/zext from i1:
7523 // (add (zext cc), x) -> (select cc (add x, 1), x)
7524 // (add (sext cc), x) -> (select cc (add x, -1), x)
7526 // These transformations eventually create predicated instructions.
7528 // @param N The node to transform.
7529 // @param Slct The N operand that is a select.
7530 // @param OtherOp The other N operand (x above).
7531 // @param DCI Context.
7532 // @param AllOnes Require the select constant to be all ones instead of null.
7533 // @returns The new node, or SDValue() on failure.
7535 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7536 TargetLowering::DAGCombinerInfo &DCI,
7537 bool AllOnes = false) {
7538 SelectionDAG &DAG = DCI.DAG;
7539 EVT VT = N->getValueType(0);
7540 SDValue NonConstantVal;
7543 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7544 NonConstantVal, DAG))
7547 // Slct is now know to be the desired identity constant when CC is true.
7548 SDValue TrueVal = OtherOp;
7549 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7550 OtherOp, NonConstantVal);
7551 // Unless SwapSelectOps says CC should be false.
7553 std::swap(TrueVal, FalseVal);
7555 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7556 CCOp, TrueVal, FalseVal);
7559 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7561 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7562 TargetLowering::DAGCombinerInfo &DCI) {
7563 SDValue N0 = N->getOperand(0);
7564 SDValue N1 = N->getOperand(1);
7565 if (N0.getNode()->hasOneUse()) {
7566 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7567 if (Result.getNode())
7570 if (N1.getNode()->hasOneUse()) {
7571 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7572 if (Result.getNode())
7578 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7579 // (only after legalization).
7580 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7581 TargetLowering::DAGCombinerInfo &DCI,
7582 const ARMSubtarget *Subtarget) {
7584 // Only perform optimization if after legalize, and if NEON is available. We
7585 // also expected both operands to be BUILD_VECTORs.
7586 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7587 || N0.getOpcode() != ISD::BUILD_VECTOR
7588 || N1.getOpcode() != ISD::BUILD_VECTOR)
7591 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7592 EVT VT = N->getValueType(0);
7593 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7596 // Check that the vector operands are of the right form.
7597 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7598 // operands, where N is the size of the formed vector.
7599 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7600 // index such that we have a pair wise add pattern.
7602 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7603 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7605 SDValue Vec = N0->getOperand(0)->getOperand(0);
7606 SDNode *V = Vec.getNode();
7607 unsigned nextIndex = 0;
7609 // For each operands to the ADD which are BUILD_VECTORs,
7610 // check to see if each of their operands are an EXTRACT_VECTOR with
7611 // the same vector and appropriate index.
7612 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7613 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7614 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7616 SDValue ExtVec0 = N0->getOperand(i);
7617 SDValue ExtVec1 = N1->getOperand(i);
7619 // First operand is the vector, verify its the same.
7620 if (V != ExtVec0->getOperand(0).getNode() ||
7621 V != ExtVec1->getOperand(0).getNode())
7624 // Second is the constant, verify its correct.
7625 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7626 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7628 // For the constant, we want to see all the even or all the odd.
7629 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7630 || C1->getZExtValue() != nextIndex+1)
7639 // Create VPADDL node.
7640 SelectionDAG &DAG = DCI.DAG;
7641 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7643 // Build operand list.
7644 SmallVector<SDValue, 8> Ops;
7645 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7646 TLI.getPointerTy()));
7648 // Input is the vector.
7651 // Get widened type and narrowed type.
7653 unsigned numElem = VT.getVectorNumElements();
7655 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7656 switch (inputLaneType.getSimpleVT().SimpleTy) {
7657 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7658 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7659 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7661 llvm_unreachable("Invalid vector element type for padd optimization.");
7664 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7665 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7666 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7669 static SDValue findMUL_LOHI(SDValue V) {
7670 if (V->getOpcode() == ISD::UMUL_LOHI ||
7671 V->getOpcode() == ISD::SMUL_LOHI)
7676 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7677 TargetLowering::DAGCombinerInfo &DCI,
7678 const ARMSubtarget *Subtarget) {
7680 if (Subtarget->isThumb1Only()) return SDValue();
7682 // Only perform the checks after legalize when the pattern is available.
7683 if (DCI.isBeforeLegalize()) return SDValue();
7685 // Look for multiply add opportunities.
7686 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7687 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7688 // a glue link from the first add to the second add.
7689 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7690 // a S/UMLAL instruction.
7693 // \ / \ [no multiline comment]
7699 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7700 SDValue AddcOp0 = AddcNode->getOperand(0);
7701 SDValue AddcOp1 = AddcNode->getOperand(1);
7703 // Check if the two operands are from the same mul_lohi node.
7704 if (AddcOp0.getNode() == AddcOp1.getNode())
7707 assert(AddcNode->getNumValues() == 2 &&
7708 AddcNode->getValueType(0) == MVT::i32 &&
7709 "Expect ADDC with two result values. First: i32");
7711 // Check that we have a glued ADDC node.
7712 if (AddcNode->getValueType(1) != MVT::Glue)
7715 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7716 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7717 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7718 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7719 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7722 // Look for the glued ADDE.
7723 SDNode* AddeNode = AddcNode->getGluedUser();
7727 // Make sure it is really an ADDE.
7728 if (AddeNode->getOpcode() != ISD::ADDE)
7731 assert(AddeNode->getNumOperands() == 3 &&
7732 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7733 "ADDE node has the wrong inputs");
7735 // Check for the triangle shape.
7736 SDValue AddeOp0 = AddeNode->getOperand(0);
7737 SDValue AddeOp1 = AddeNode->getOperand(1);
7739 // Make sure that the ADDE operands are not coming from the same node.
7740 if (AddeOp0.getNode() == AddeOp1.getNode())
7743 // Find the MUL_LOHI node walking up ADDE's operands.
7744 bool IsLeftOperandMUL = false;
7745 SDValue MULOp = findMUL_LOHI(AddeOp0);
7746 if (MULOp == SDValue())
7747 MULOp = findMUL_LOHI(AddeOp1);
7749 IsLeftOperandMUL = true;
7750 if (MULOp == SDValue())
7753 // Figure out the right opcode.
7754 unsigned Opc = MULOp->getOpcode();
7755 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7757 // Figure out the high and low input values to the MLAL node.
7758 SDValue* HiMul = &MULOp;
7759 SDValue* HiAdd = nullptr;
7760 SDValue* LoMul = nullptr;
7761 SDValue* LowAdd = nullptr;
7763 if (IsLeftOperandMUL)
7769 if (AddcOp0->getOpcode() == Opc) {
7773 if (AddcOp1->getOpcode() == Opc) {
7781 if (LoMul->getNode() != HiMul->getNode())
7784 // Create the merged node.
7785 SelectionDAG &DAG = DCI.DAG;
7787 // Build operand list.
7788 SmallVector<SDValue, 8> Ops;
7789 Ops.push_back(LoMul->getOperand(0));
7790 Ops.push_back(LoMul->getOperand(1));
7791 Ops.push_back(*LowAdd);
7792 Ops.push_back(*HiAdd);
7794 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7795 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7797 // Replace the ADDs' nodes uses by the MLA node's values.
7798 SDValue HiMLALResult(MLALNode.getNode(), 1);
7799 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7801 SDValue LoMLALResult(MLALNode.getNode(), 0);
7802 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7804 // Return original node to notify the driver to stop replacing.
7805 SDValue resNode(AddcNode, 0);
7809 /// PerformADDCCombine - Target-specific dag combine transform from
7810 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7811 static SDValue PerformADDCCombine(SDNode *N,
7812 TargetLowering::DAGCombinerInfo &DCI,
7813 const ARMSubtarget *Subtarget) {
7815 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7819 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7820 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7821 /// called with the default operands, and if that fails, with commuted
7823 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7824 TargetLowering::DAGCombinerInfo &DCI,
7825 const ARMSubtarget *Subtarget){
7827 // Attempt to create vpaddl for this add.
7828 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7829 if (Result.getNode())
7832 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7833 if (N0.getNode()->hasOneUse()) {
7834 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7835 if (Result.getNode()) return Result;
7840 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7842 static SDValue PerformADDCombine(SDNode *N,
7843 TargetLowering::DAGCombinerInfo &DCI,
7844 const ARMSubtarget *Subtarget) {
7845 SDValue N0 = N->getOperand(0);
7846 SDValue N1 = N->getOperand(1);
7848 // First try with the default operand order.
7849 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7850 if (Result.getNode())
7853 // If that didn't work, try again with the operands commuted.
7854 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7857 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7859 static SDValue PerformSUBCombine(SDNode *N,
7860 TargetLowering::DAGCombinerInfo &DCI) {
7861 SDValue N0 = N->getOperand(0);
7862 SDValue N1 = N->getOperand(1);
7864 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7865 if (N1.getNode()->hasOneUse()) {
7866 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7867 if (Result.getNode()) return Result;
7873 /// PerformVMULCombine
7874 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7875 /// special multiplier accumulator forwarding.
7881 // However, for (A + B) * (A + B),
7888 static SDValue PerformVMULCombine(SDNode *N,
7889 TargetLowering::DAGCombinerInfo &DCI,
7890 const ARMSubtarget *Subtarget) {
7891 if (!Subtarget->hasVMLxForwarding())
7894 SelectionDAG &DAG = DCI.DAG;
7895 SDValue N0 = N->getOperand(0);
7896 SDValue N1 = N->getOperand(1);
7897 unsigned Opcode = N0.getOpcode();
7898 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7899 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7900 Opcode = N1.getOpcode();
7901 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7902 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7910 EVT VT = N->getValueType(0);
7912 SDValue N00 = N0->getOperand(0);
7913 SDValue N01 = N0->getOperand(1);
7914 return DAG.getNode(Opcode, DL, VT,
7915 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7916 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7919 static SDValue PerformMULCombine(SDNode *N,
7920 TargetLowering::DAGCombinerInfo &DCI,
7921 const ARMSubtarget *Subtarget) {
7922 SelectionDAG &DAG = DCI.DAG;
7924 if (Subtarget->isThumb1Only())
7927 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7930 EVT VT = N->getValueType(0);
7931 if (VT.is64BitVector() || VT.is128BitVector())
7932 return PerformVMULCombine(N, DCI, Subtarget);
7936 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7940 int64_t MulAmt = C->getSExtValue();
7941 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7943 ShiftAmt = ShiftAmt & (32 - 1);
7944 SDValue V = N->getOperand(0);
7948 MulAmt >>= ShiftAmt;
7951 if (isPowerOf2_32(MulAmt - 1)) {
7952 // (mul x, 2^N + 1) => (add (shl x, N), x)
7953 Res = DAG.getNode(ISD::ADD, DL, VT,
7955 DAG.getNode(ISD::SHL, DL, VT,
7957 DAG.getConstant(Log2_32(MulAmt - 1),
7959 } else if (isPowerOf2_32(MulAmt + 1)) {
7960 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7961 Res = DAG.getNode(ISD::SUB, DL, VT,
7962 DAG.getNode(ISD::SHL, DL, VT,
7964 DAG.getConstant(Log2_32(MulAmt + 1),
7970 uint64_t MulAmtAbs = -MulAmt;
7971 if (isPowerOf2_32(MulAmtAbs + 1)) {
7972 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7973 Res = DAG.getNode(ISD::SUB, DL, VT,
7975 DAG.getNode(ISD::SHL, DL, VT,
7977 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7979 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7980 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7981 Res = DAG.getNode(ISD::ADD, DL, VT,
7983 DAG.getNode(ISD::SHL, DL, VT,
7985 DAG.getConstant(Log2_32(MulAmtAbs-1),
7987 Res = DAG.getNode(ISD::SUB, DL, VT,
7988 DAG.getConstant(0, MVT::i32),Res);
7995 Res = DAG.getNode(ISD::SHL, DL, VT,
7996 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7998 // Do not add new nodes to DAG combiner worklist.
7999 DCI.CombineTo(N, Res, false);
8003 static SDValue PerformANDCombine(SDNode *N,
8004 TargetLowering::DAGCombinerInfo &DCI,
8005 const ARMSubtarget *Subtarget) {
8007 // Attempt to use immediate-form VBIC
8008 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8010 EVT VT = N->getValueType(0);
8011 SelectionDAG &DAG = DCI.DAG;
8013 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8016 APInt SplatBits, SplatUndef;
8017 unsigned SplatBitSize;
8020 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8021 if (SplatBitSize <= 64) {
8023 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8024 SplatUndef.getZExtValue(), SplatBitSize,
8025 DAG, VbicVT, VT.is128BitVector(),
8027 if (Val.getNode()) {
8029 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8030 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8031 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8036 if (!Subtarget->isThumb1Only()) {
8037 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8038 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8039 if (Result.getNode())
8046 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8047 static SDValue PerformORCombine(SDNode *N,
8048 TargetLowering::DAGCombinerInfo &DCI,
8049 const ARMSubtarget *Subtarget) {
8050 // Attempt to use immediate-form VORR
8051 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8053 EVT VT = N->getValueType(0);
8054 SelectionDAG &DAG = DCI.DAG;
8056 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8059 APInt SplatBits, SplatUndef;
8060 unsigned SplatBitSize;
8062 if (BVN && Subtarget->hasNEON() &&
8063 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8064 if (SplatBitSize <= 64) {
8066 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8067 SplatUndef.getZExtValue(), SplatBitSize,
8068 DAG, VorrVT, VT.is128BitVector(),
8070 if (Val.getNode()) {
8072 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8073 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8074 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8079 if (!Subtarget->isThumb1Only()) {
8080 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8081 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8082 if (Result.getNode())
8086 // The code below optimizes (or (and X, Y), Z).
8087 // The AND operand needs to have a single user to make these optimizations
8089 SDValue N0 = N->getOperand(0);
8090 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8092 SDValue N1 = N->getOperand(1);
8094 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8095 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8096 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8098 unsigned SplatBitSize;
8101 APInt SplatBits0, SplatBits1;
8102 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8103 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8104 // Ensure that the second operand of both ands are constants
8105 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8106 HasAnyUndefs) && !HasAnyUndefs) {
8107 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8108 HasAnyUndefs) && !HasAnyUndefs) {
8109 // Ensure that the bit width of the constants are the same and that
8110 // the splat arguments are logical inverses as per the pattern we
8111 // are trying to simplify.
8112 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8113 SplatBits0 == ~SplatBits1) {
8114 // Canonicalize the vector type to make instruction selection
8116 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8117 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8121 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8127 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8130 // BFI is only available on V6T2+
8131 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8135 // 1) or (and A, mask), val => ARMbfi A, val, mask
8136 // iff (val & mask) == val
8138 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8139 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8140 // && mask == ~mask2
8141 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8142 // && ~mask == mask2
8143 // (i.e., copy a bitfield value into another bitfield of the same width)
8148 SDValue N00 = N0.getOperand(0);
8150 // The value and the mask need to be constants so we can verify this is
8151 // actually a bitfield set. If the mask is 0xffff, we can do better
8152 // via a movt instruction, so don't use BFI in that case.
8153 SDValue MaskOp = N0.getOperand(1);
8154 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8157 unsigned Mask = MaskC->getZExtValue();
8161 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8162 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8164 unsigned Val = N1C->getZExtValue();
8165 if ((Val & ~Mask) != Val)
8168 if (ARM::isBitFieldInvertedMask(Mask)) {
8169 Val >>= countTrailingZeros(~Mask);
8171 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8172 DAG.getConstant(Val, MVT::i32),
8173 DAG.getConstant(Mask, MVT::i32));
8175 // Do not add new nodes to DAG combiner worklist.
8176 DCI.CombineTo(N, Res, false);
8179 } else if (N1.getOpcode() == ISD::AND) {
8180 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8181 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8184 unsigned Mask2 = N11C->getZExtValue();
8186 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8188 if (ARM::isBitFieldInvertedMask(Mask) &&
8190 // The pack halfword instruction works better for masks that fit it,
8191 // so use that when it's available.
8192 if (Subtarget->hasT2ExtractPack() &&
8193 (Mask == 0xffff || Mask == 0xffff0000))
8196 unsigned amt = countTrailingZeros(Mask2);
8197 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8198 DAG.getConstant(amt, MVT::i32));
8199 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8200 DAG.getConstant(Mask, MVT::i32));
8201 // Do not add new nodes to DAG combiner worklist.
8202 DCI.CombineTo(N, Res, false);
8204 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8206 // The pack halfword instruction works better for masks that fit it,
8207 // so use that when it's available.
8208 if (Subtarget->hasT2ExtractPack() &&
8209 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8212 unsigned lsb = countTrailingZeros(Mask);
8213 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8214 DAG.getConstant(lsb, MVT::i32));
8215 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8216 DAG.getConstant(Mask2, MVT::i32));
8217 // Do not add new nodes to DAG combiner worklist.
8218 DCI.CombineTo(N, Res, false);
8223 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8224 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8225 ARM::isBitFieldInvertedMask(~Mask)) {
8226 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8227 // where lsb(mask) == #shamt and masked bits of B are known zero.
8228 SDValue ShAmt = N00.getOperand(1);
8229 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8230 unsigned LSB = countTrailingZeros(Mask);
8234 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8235 DAG.getConstant(~Mask, MVT::i32));
8237 // Do not add new nodes to DAG combiner worklist.
8238 DCI.CombineTo(N, Res, false);
8244 static SDValue PerformXORCombine(SDNode *N,
8245 TargetLowering::DAGCombinerInfo &DCI,
8246 const ARMSubtarget *Subtarget) {
8247 EVT VT = N->getValueType(0);
8248 SelectionDAG &DAG = DCI.DAG;
8250 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8253 if (!Subtarget->isThumb1Only()) {
8254 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8255 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8256 if (Result.getNode())
8263 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8264 /// the bits being cleared by the AND are not demanded by the BFI.
8265 static SDValue PerformBFICombine(SDNode *N,
8266 TargetLowering::DAGCombinerInfo &DCI) {
8267 SDValue N1 = N->getOperand(1);
8268 if (N1.getOpcode() == ISD::AND) {
8269 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8272 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8273 unsigned LSB = countTrailingZeros(~InvMask);
8274 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8275 unsigned Mask = (1 << Width)-1;
8276 unsigned Mask2 = N11C->getZExtValue();
8277 if ((Mask & (~Mask2)) == 0)
8278 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8279 N->getOperand(0), N1.getOperand(0),
8285 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8286 /// ARMISD::VMOVRRD.
8287 static SDValue PerformVMOVRRDCombine(SDNode *N,
8288 TargetLowering::DAGCombinerInfo &DCI) {
8289 // vmovrrd(vmovdrr x, y) -> x,y
8290 SDValue InDouble = N->getOperand(0);
8291 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8292 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8294 // vmovrrd(load f64) -> (load i32), (load i32)
8295 SDNode *InNode = InDouble.getNode();
8296 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8297 InNode->getValueType(0) == MVT::f64 &&
8298 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8299 !cast<LoadSDNode>(InNode)->isVolatile()) {
8300 // TODO: Should this be done for non-FrameIndex operands?
8301 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8303 SelectionDAG &DAG = DCI.DAG;
8305 SDValue BasePtr = LD->getBasePtr();
8306 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8307 LD->getPointerInfo(), LD->isVolatile(),
8308 LD->isNonTemporal(), LD->isInvariant(),
8309 LD->getAlignment());
8311 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8312 DAG.getConstant(4, MVT::i32));
8313 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8314 LD->getPointerInfo(), LD->isVolatile(),
8315 LD->isNonTemporal(), LD->isInvariant(),
8316 std::min(4U, LD->getAlignment() / 2));
8318 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8319 if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8320 std::swap (NewLD1, NewLD2);
8321 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8322 DCI.RemoveFromWorklist(LD);
8330 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8331 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8332 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8333 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8334 SDValue Op0 = N->getOperand(0);
8335 SDValue Op1 = N->getOperand(1);
8336 if (Op0.getOpcode() == ISD::BITCAST)
8337 Op0 = Op0.getOperand(0);
8338 if (Op1.getOpcode() == ISD::BITCAST)
8339 Op1 = Op1.getOperand(0);
8340 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8341 Op0.getNode() == Op1.getNode() &&
8342 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8343 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8344 N->getValueType(0), Op0.getOperand(0));
8348 /// PerformSTORECombine - Target-specific dag combine xforms for
8350 static SDValue PerformSTORECombine(SDNode *N,
8351 TargetLowering::DAGCombinerInfo &DCI) {
8352 StoreSDNode *St = cast<StoreSDNode>(N);
8353 if (St->isVolatile())
8356 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8357 // pack all of the elements in one place. Next, store to memory in fewer
8359 SDValue StVal = St->getValue();
8360 EVT VT = StVal.getValueType();
8361 if (St->isTruncatingStore() && VT.isVector()) {
8362 SelectionDAG &DAG = DCI.DAG;
8363 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8364 EVT StVT = St->getMemoryVT();
8365 unsigned NumElems = VT.getVectorNumElements();
8366 assert(StVT != VT && "Cannot truncate to the same type");
8367 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8368 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8370 // From, To sizes and ElemCount must be pow of two
8371 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8373 // We are going to use the original vector elt for storing.
8374 // Accumulated smaller vector elements must be a multiple of the store size.
8375 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8377 unsigned SizeRatio = FromEltSz / ToEltSz;
8378 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8380 // Create a type on which we perform the shuffle.
8381 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8382 NumElems*SizeRatio);
8383 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8386 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8387 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8388 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8390 // Can't shuffle using an illegal type.
8391 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8393 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8394 DAG.getUNDEF(WideVec.getValueType()),
8396 // At this point all of the data is stored at the bottom of the
8397 // register. We now need to save it to mem.
8399 // Find the largest store unit
8400 MVT StoreType = MVT::i8;
8401 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8402 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8403 MVT Tp = (MVT::SimpleValueType)tp;
8404 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8407 // Didn't find a legal store type.
8408 if (!TLI.isTypeLegal(StoreType))
8411 // Bitcast the original vector into a vector of store-size units
8412 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8413 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8414 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8415 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8416 SmallVector<SDValue, 8> Chains;
8417 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8418 TLI.getPointerTy());
8419 SDValue BasePtr = St->getBasePtr();
8421 // Perform one or more big stores into memory.
8422 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8423 for (unsigned I = 0; I < E; I++) {
8424 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8425 StoreType, ShuffWide,
8426 DAG.getIntPtrConstant(I));
8427 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8428 St->getPointerInfo(), St->isVolatile(),
8429 St->isNonTemporal(), St->getAlignment());
8430 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8432 Chains.push_back(Ch);
8434 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8437 if (!ISD::isNormalStore(St))
8440 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8441 // ARM stores of arguments in the same cache line.
8442 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8443 StVal.getNode()->hasOneUse()) {
8444 SelectionDAG &DAG = DCI.DAG;
8445 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8447 SDValue BasePtr = St->getBasePtr();
8448 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8449 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8450 BasePtr, St->getPointerInfo(), St->isVolatile(),
8451 St->isNonTemporal(), St->getAlignment());
8453 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8454 DAG.getConstant(4, MVT::i32));
8455 return DAG.getStore(NewST1.getValue(0), DL,
8456 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8457 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8458 St->isNonTemporal(),
8459 std::min(4U, St->getAlignment() / 2));
8462 if (StVal.getValueType() != MVT::i64 ||
8463 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8466 // Bitcast an i64 store extracted from a vector to f64.
8467 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8468 SelectionDAG &DAG = DCI.DAG;
8470 SDValue IntVec = StVal.getOperand(0);
8471 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8472 IntVec.getValueType().getVectorNumElements());
8473 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8474 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8475 Vec, StVal.getOperand(1));
8477 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8478 // Make the DAGCombiner fold the bitcasts.
8479 DCI.AddToWorklist(Vec.getNode());
8480 DCI.AddToWorklist(ExtElt.getNode());
8481 DCI.AddToWorklist(V.getNode());
8482 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8483 St->getPointerInfo(), St->isVolatile(),
8484 St->isNonTemporal(), St->getAlignment(),
8488 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8489 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8490 /// i64 vector to have f64 elements, since the value can then be loaded
8491 /// directly into a VFP register.
8492 static bool hasNormalLoadOperand(SDNode *N) {
8493 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8494 for (unsigned i = 0; i < NumElts; ++i) {
8495 SDNode *Elt = N->getOperand(i).getNode();
8496 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8502 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8503 /// ISD::BUILD_VECTOR.
8504 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8505 TargetLowering::DAGCombinerInfo &DCI){
8506 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8507 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8508 // into a pair of GPRs, which is fine when the value is used as a scalar,
8509 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8510 SelectionDAG &DAG = DCI.DAG;
8511 if (N->getNumOperands() == 2) {
8512 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8517 // Load i64 elements as f64 values so that type legalization does not split
8518 // them up into i32 values.
8519 EVT VT = N->getValueType(0);
8520 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8523 SmallVector<SDValue, 8> Ops;
8524 unsigned NumElts = VT.getVectorNumElements();
8525 for (unsigned i = 0; i < NumElts; ++i) {
8526 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8528 // Make the DAGCombiner fold the bitcast.
8529 DCI.AddToWorklist(V.getNode());
8531 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8532 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8533 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8536 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8538 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8539 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8540 // At that time, we may have inserted bitcasts from integer to float.
8541 // If these bitcasts have survived DAGCombine, change the lowering of this
8542 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8543 // force to use floating point types.
8545 // Make sure we can change the type of the vector.
8546 // This is possible iff:
8547 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8548 // 1.1. Vector is used only once.
8549 // 1.2. Use is a bit convert to an integer type.
8550 // 2. The size of its operands are 32-bits (64-bits are not legal).
8551 EVT VT = N->getValueType(0);
8552 EVT EltVT = VT.getVectorElementType();
8554 // Check 1.1. and 2.
8555 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8558 // By construction, the input type must be float.
8559 assert(EltVT == MVT::f32 && "Unexpected type!");
8562 SDNode *Use = *N->use_begin();
8563 if (Use->getOpcode() != ISD::BITCAST ||
8564 Use->getValueType(0).isFloatingPoint())
8567 // Check profitability.
8568 // Model is, if more than half of the relevant operands are bitcast from
8569 // i32, turn the build_vector into a sequence of insert_vector_elt.
8570 // Relevant operands are everything that is not statically
8571 // (i.e., at compile time) bitcasted.
8572 unsigned NumOfBitCastedElts = 0;
8573 unsigned NumElts = VT.getVectorNumElements();
8574 unsigned NumOfRelevantElts = NumElts;
8575 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8576 SDValue Elt = N->getOperand(Idx);
8577 if (Elt->getOpcode() == ISD::BITCAST) {
8578 // Assume only bit cast to i32 will go away.
8579 if (Elt->getOperand(0).getValueType() == MVT::i32)
8580 ++NumOfBitCastedElts;
8581 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8582 // Constants are statically casted, thus do not count them as
8583 // relevant operands.
8584 --NumOfRelevantElts;
8587 // Check if more than half of the elements require a non-free bitcast.
8588 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8591 SelectionDAG &DAG = DCI.DAG;
8592 // Create the new vector type.
8593 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8594 // Check if the type is legal.
8595 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8596 if (!TLI.isTypeLegal(VecVT))
8600 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8601 // => BITCAST INSERT_VECTOR_ELT
8602 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8604 SDValue Vec = DAG.getUNDEF(VecVT);
8606 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8607 SDValue V = N->getOperand(Idx);
8608 if (V.getOpcode() == ISD::UNDEF)
8610 if (V.getOpcode() == ISD::BITCAST &&
8611 V->getOperand(0).getValueType() == MVT::i32)
8612 // Fold obvious case.
8613 V = V.getOperand(0);
8615 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8616 // Make the DAGCombiner fold the bitcasts.
8617 DCI.AddToWorklist(V.getNode());
8619 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8620 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8622 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8623 // Make the DAGCombiner fold the bitcasts.
8624 DCI.AddToWorklist(Vec.getNode());
8628 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8629 /// ISD::INSERT_VECTOR_ELT.
8630 static SDValue PerformInsertEltCombine(SDNode *N,
8631 TargetLowering::DAGCombinerInfo &DCI) {
8632 // Bitcast an i64 load inserted into a vector to f64.
8633 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8634 EVT VT = N->getValueType(0);
8635 SDNode *Elt = N->getOperand(1).getNode();
8636 if (VT.getVectorElementType() != MVT::i64 ||
8637 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8640 SelectionDAG &DAG = DCI.DAG;
8642 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8643 VT.getVectorNumElements());
8644 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8645 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8646 // Make the DAGCombiner fold the bitcasts.
8647 DCI.AddToWorklist(Vec.getNode());
8648 DCI.AddToWorklist(V.getNode());
8649 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8650 Vec, V, N->getOperand(2));
8651 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8654 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8655 /// ISD::VECTOR_SHUFFLE.
8656 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8657 // The LLVM shufflevector instruction does not require the shuffle mask
8658 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8659 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8660 // operands do not match the mask length, they are extended by concatenating
8661 // them with undef vectors. That is probably the right thing for other
8662 // targets, but for NEON it is better to concatenate two double-register
8663 // size vector operands into a single quad-register size vector. Do that
8664 // transformation here:
8665 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8666 // shuffle(concat(v1, v2), undef)
8667 SDValue Op0 = N->getOperand(0);
8668 SDValue Op1 = N->getOperand(1);
8669 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8670 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8671 Op0.getNumOperands() != 2 ||
8672 Op1.getNumOperands() != 2)
8674 SDValue Concat0Op1 = Op0.getOperand(1);
8675 SDValue Concat1Op1 = Op1.getOperand(1);
8676 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8677 Concat1Op1.getOpcode() != ISD::UNDEF)
8679 // Skip the transformation if any of the types are illegal.
8680 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8681 EVT VT = N->getValueType(0);
8682 if (!TLI.isTypeLegal(VT) ||
8683 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8684 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8687 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8688 Op0.getOperand(0), Op1.getOperand(0));
8689 // Translate the shuffle mask.
8690 SmallVector<int, 16> NewMask;
8691 unsigned NumElts = VT.getVectorNumElements();
8692 unsigned HalfElts = NumElts/2;
8693 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8694 for (unsigned n = 0; n < NumElts; ++n) {
8695 int MaskElt = SVN->getMaskElt(n);
8697 if (MaskElt < (int)HalfElts)
8699 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8700 NewElt = HalfElts + MaskElt - NumElts;
8701 NewMask.push_back(NewElt);
8703 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8704 DAG.getUNDEF(VT), NewMask.data());
8707 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8708 /// NEON load/store intrinsics to merge base address updates.
8709 static SDValue CombineBaseUpdate(SDNode *N,
8710 TargetLowering::DAGCombinerInfo &DCI) {
8711 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8714 SelectionDAG &DAG = DCI.DAG;
8715 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8716 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8717 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8718 SDValue Addr = N->getOperand(AddrOpIdx);
8720 // Search for a use of the address operand that is an increment.
8721 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8722 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8724 if (User->getOpcode() != ISD::ADD ||
8725 UI.getUse().getResNo() != Addr.getResNo())
8728 // Check that the add is independent of the load/store. Otherwise, folding
8729 // it would create a cycle.
8730 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8733 // Find the new opcode for the updating load/store.
8735 bool isLaneOp = false;
8736 unsigned NewOpc = 0;
8737 unsigned NumVecs = 0;
8739 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8741 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8742 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8744 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8746 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8748 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8750 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8751 NumVecs = 2; isLaneOp = true; break;
8752 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8753 NumVecs = 3; isLaneOp = true; break;
8754 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8755 NumVecs = 4; isLaneOp = true; break;
8756 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8757 NumVecs = 1; isLoad = false; break;
8758 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8759 NumVecs = 2; isLoad = false; break;
8760 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8761 NumVecs = 3; isLoad = false; break;
8762 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8763 NumVecs = 4; isLoad = false; break;
8764 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8765 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8766 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8767 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8768 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8769 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8773 switch (N->getOpcode()) {
8774 default: llvm_unreachable("unexpected opcode for Neon base update");
8775 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8776 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8777 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8781 // Find the size of memory referenced by the load/store.
8784 VecTy = N->getValueType(0);
8786 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8787 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8789 NumBytes /= VecTy.getVectorNumElements();
8791 // If the increment is a constant, it must match the memory ref size.
8792 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8793 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8794 uint64_t IncVal = CInc->getZExtValue();
8795 if (IncVal != NumBytes)
8797 } else if (NumBytes >= 3 * 16) {
8798 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8799 // separate instructions that make it harder to use a non-constant update.
8803 // Create the new updating load/store node.
8805 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8807 for (n = 0; n < NumResultVecs; ++n)
8809 Tys[n++] = MVT::i32;
8810 Tys[n] = MVT::Other;
8811 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8812 SmallVector<SDValue, 8> Ops;
8813 Ops.push_back(N->getOperand(0)); // incoming chain
8814 Ops.push_back(N->getOperand(AddrOpIdx));
8816 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8817 Ops.push_back(N->getOperand(i));
8819 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8820 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8821 Ops, MemInt->getMemoryVT(),
8822 MemInt->getMemOperand());
8825 std::vector<SDValue> NewResults;
8826 for (unsigned i = 0; i < NumResultVecs; ++i) {
8827 NewResults.push_back(SDValue(UpdN.getNode(), i));
8829 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8830 DCI.CombineTo(N, NewResults);
8831 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8838 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8839 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8840 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8842 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8843 SelectionDAG &DAG = DCI.DAG;
8844 EVT VT = N->getValueType(0);
8845 // vldN-dup instructions only support 64-bit vectors for N > 1.
8846 if (!VT.is64BitVector())
8849 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8850 SDNode *VLD = N->getOperand(0).getNode();
8851 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8853 unsigned NumVecs = 0;
8854 unsigned NewOpc = 0;
8855 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8856 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8858 NewOpc = ARMISD::VLD2DUP;
8859 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8861 NewOpc = ARMISD::VLD3DUP;
8862 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8864 NewOpc = ARMISD::VLD4DUP;
8869 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8870 // numbers match the load.
8871 unsigned VLDLaneNo =
8872 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8873 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8875 // Ignore uses of the chain result.
8876 if (UI.getUse().getResNo() == NumVecs)
8879 if (User->getOpcode() != ARMISD::VDUPLANE ||
8880 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8884 // Create the vldN-dup node.
8887 for (n = 0; n < NumVecs; ++n)
8889 Tys[n] = MVT::Other;
8890 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8891 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8892 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8893 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8894 Ops, VLDMemInt->getMemoryVT(),
8895 VLDMemInt->getMemOperand());
8898 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8900 unsigned ResNo = UI.getUse().getResNo();
8901 // Ignore uses of the chain result.
8902 if (ResNo == NumVecs)
8905 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8908 // Now the vldN-lane intrinsic is dead except for its chain result.
8909 // Update uses of the chain.
8910 std::vector<SDValue> VLDDupResults;
8911 for (unsigned n = 0; n < NumVecs; ++n)
8912 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8913 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8914 DCI.CombineTo(VLD, VLDDupResults);
8919 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8920 /// ARMISD::VDUPLANE.
8921 static SDValue PerformVDUPLANECombine(SDNode *N,
8922 TargetLowering::DAGCombinerInfo &DCI) {
8923 SDValue Op = N->getOperand(0);
8925 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8926 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8927 if (CombineVLDDUP(N, DCI))
8928 return SDValue(N, 0);
8930 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8931 // redundant. Ignore bit_converts for now; element sizes are checked below.
8932 while (Op.getOpcode() == ISD::BITCAST)
8933 Op = Op.getOperand(0);
8934 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8937 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8938 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8939 // The canonical VMOV for a zero vector uses a 32-bit element size.
8940 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8942 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8944 EVT VT = N->getValueType(0);
8945 if (EltSize > VT.getVectorElementType().getSizeInBits())
8948 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8951 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8952 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8953 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8957 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8959 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8964 APFloat APF = C->getValueAPF();
8965 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8966 != APFloat::opOK || !isExact)
8969 c0 = (I == 0) ? cN : c0;
8970 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8977 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8978 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8979 /// when the VMUL has a constant operand that is a power of 2.
8981 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8982 /// vmul.f32 d16, d17, d16
8983 /// vcvt.s32.f32 d16, d16
8985 /// vcvt.s32.f32 d16, d16, #3
8986 static SDValue PerformVCVTCombine(SDNode *N,
8987 TargetLowering::DAGCombinerInfo &DCI,
8988 const ARMSubtarget *Subtarget) {
8989 SelectionDAG &DAG = DCI.DAG;
8990 SDValue Op = N->getOperand(0);
8992 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8993 Op.getOpcode() != ISD::FMUL)
8997 SDValue N0 = Op->getOperand(0);
8998 SDValue ConstVec = Op->getOperand(1);
8999 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9001 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9002 !isConstVecPow2(ConstVec, isSigned, C))
9005 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9006 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9007 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9008 // These instructions only exist converting from f32 to i32. We can handle
9009 // smaller integers by generating an extra truncate, but larger ones would
9014 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9015 Intrinsic::arm_neon_vcvtfp2fxu;
9016 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9017 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9018 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9019 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9020 DAG.getConstant(Log2_64(C), MVT::i32));
9022 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9023 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9028 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9029 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9030 /// when the VDIV has a constant operand that is a power of 2.
9032 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9033 /// vcvt.f32.s32 d16, d16
9034 /// vdiv.f32 d16, d17, d16
9036 /// vcvt.f32.s32 d16, d16, #3
9037 static SDValue PerformVDIVCombine(SDNode *N,
9038 TargetLowering::DAGCombinerInfo &DCI,
9039 const ARMSubtarget *Subtarget) {
9040 SelectionDAG &DAG = DCI.DAG;
9041 SDValue Op = N->getOperand(0);
9042 unsigned OpOpcode = Op.getNode()->getOpcode();
9044 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9045 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9049 SDValue ConstVec = N->getOperand(1);
9050 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9052 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9053 !isConstVecPow2(ConstVec, isSigned, C))
9056 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9057 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9058 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9059 // These instructions only exist converting from i32 to f32. We can handle
9060 // smaller integers by generating an extra extend, but larger ones would
9065 SDValue ConvInput = Op.getOperand(0);
9066 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9067 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9068 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9069 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9072 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9073 Intrinsic::arm_neon_vcvtfxu2fp;
9074 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9076 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9077 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9080 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9081 /// operand of a vector shift operation, where all the elements of the
9082 /// build_vector must have the same constant integer value.
9083 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9084 // Ignore bit_converts.
9085 while (Op.getOpcode() == ISD::BITCAST)
9086 Op = Op.getOperand(0);
9087 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9088 APInt SplatBits, SplatUndef;
9089 unsigned SplatBitSize;
9091 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9092 HasAnyUndefs, ElementBits) ||
9093 SplatBitSize > ElementBits)
9095 Cnt = SplatBits.getSExtValue();
9099 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9100 /// operand of a vector shift left operation. That value must be in the range:
9101 /// 0 <= Value < ElementBits for a left shift; or
9102 /// 0 <= Value <= ElementBits for a long left shift.
9103 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9104 assert(VT.isVector() && "vector shift count is not a vector type");
9105 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9106 if (! getVShiftImm(Op, ElementBits, Cnt))
9108 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9111 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9112 /// operand of a vector shift right operation. For a shift opcode, the value
9113 /// is positive, but for an intrinsic the value count must be negative. The
9114 /// absolute value must be in the range:
9115 /// 1 <= |Value| <= ElementBits for a right shift; or
9116 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9117 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9119 assert(VT.isVector() && "vector shift count is not a vector type");
9120 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9121 if (! getVShiftImm(Op, ElementBits, Cnt))
9125 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9128 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9129 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9130 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9133 // Don't do anything for most intrinsics.
9136 // Vector shifts: check for immediate versions and lower them.
9137 // Note: This is done during DAG combining instead of DAG legalizing because
9138 // the build_vectors for 64-bit vector element shift counts are generally
9139 // not legal, and it is hard to see their values after they get legalized to
9140 // loads from a constant pool.
9141 case Intrinsic::arm_neon_vshifts:
9142 case Intrinsic::arm_neon_vshiftu:
9143 case Intrinsic::arm_neon_vrshifts:
9144 case Intrinsic::arm_neon_vrshiftu:
9145 case Intrinsic::arm_neon_vrshiftn:
9146 case Intrinsic::arm_neon_vqshifts:
9147 case Intrinsic::arm_neon_vqshiftu:
9148 case Intrinsic::arm_neon_vqshiftsu:
9149 case Intrinsic::arm_neon_vqshiftns:
9150 case Intrinsic::arm_neon_vqshiftnu:
9151 case Intrinsic::arm_neon_vqshiftnsu:
9152 case Intrinsic::arm_neon_vqrshiftns:
9153 case Intrinsic::arm_neon_vqrshiftnu:
9154 case Intrinsic::arm_neon_vqrshiftnsu: {
9155 EVT VT = N->getOperand(1).getValueType();
9157 unsigned VShiftOpc = 0;
9160 case Intrinsic::arm_neon_vshifts:
9161 case Intrinsic::arm_neon_vshiftu:
9162 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9163 VShiftOpc = ARMISD::VSHL;
9166 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9167 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9168 ARMISD::VSHRs : ARMISD::VSHRu);
9173 case Intrinsic::arm_neon_vrshifts:
9174 case Intrinsic::arm_neon_vrshiftu:
9175 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9179 case Intrinsic::arm_neon_vqshifts:
9180 case Intrinsic::arm_neon_vqshiftu:
9181 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9185 case Intrinsic::arm_neon_vqshiftsu:
9186 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9188 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9190 case Intrinsic::arm_neon_vrshiftn:
9191 case Intrinsic::arm_neon_vqshiftns:
9192 case Intrinsic::arm_neon_vqshiftnu:
9193 case Intrinsic::arm_neon_vqshiftnsu:
9194 case Intrinsic::arm_neon_vqrshiftns:
9195 case Intrinsic::arm_neon_vqrshiftnu:
9196 case Intrinsic::arm_neon_vqrshiftnsu:
9197 // Narrowing shifts require an immediate right shift.
9198 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9200 llvm_unreachable("invalid shift count for narrowing vector shift "
9204 llvm_unreachable("unhandled vector shift");
9208 case Intrinsic::arm_neon_vshifts:
9209 case Intrinsic::arm_neon_vshiftu:
9210 // Opcode already set above.
9212 case Intrinsic::arm_neon_vrshifts:
9213 VShiftOpc = ARMISD::VRSHRs; break;
9214 case Intrinsic::arm_neon_vrshiftu:
9215 VShiftOpc = ARMISD::VRSHRu; break;
9216 case Intrinsic::arm_neon_vrshiftn:
9217 VShiftOpc = ARMISD::VRSHRN; break;
9218 case Intrinsic::arm_neon_vqshifts:
9219 VShiftOpc = ARMISD::VQSHLs; break;
9220 case Intrinsic::arm_neon_vqshiftu:
9221 VShiftOpc = ARMISD::VQSHLu; break;
9222 case Intrinsic::arm_neon_vqshiftsu:
9223 VShiftOpc = ARMISD::VQSHLsu; break;
9224 case Intrinsic::arm_neon_vqshiftns:
9225 VShiftOpc = ARMISD::VQSHRNs; break;
9226 case Intrinsic::arm_neon_vqshiftnu:
9227 VShiftOpc = ARMISD::VQSHRNu; break;
9228 case Intrinsic::arm_neon_vqshiftnsu:
9229 VShiftOpc = ARMISD::VQSHRNsu; break;
9230 case Intrinsic::arm_neon_vqrshiftns:
9231 VShiftOpc = ARMISD::VQRSHRNs; break;
9232 case Intrinsic::arm_neon_vqrshiftnu:
9233 VShiftOpc = ARMISD::VQRSHRNu; break;
9234 case Intrinsic::arm_neon_vqrshiftnsu:
9235 VShiftOpc = ARMISD::VQRSHRNsu; break;
9238 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9239 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9242 case Intrinsic::arm_neon_vshiftins: {
9243 EVT VT = N->getOperand(1).getValueType();
9245 unsigned VShiftOpc = 0;
9247 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9248 VShiftOpc = ARMISD::VSLI;
9249 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9250 VShiftOpc = ARMISD::VSRI;
9252 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9255 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9256 N->getOperand(1), N->getOperand(2),
9257 DAG.getConstant(Cnt, MVT::i32));
9260 case Intrinsic::arm_neon_vqrshifts:
9261 case Intrinsic::arm_neon_vqrshiftu:
9262 // No immediate versions of these to check for.
9269 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9270 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9271 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9272 /// vector element shift counts are generally not legal, and it is hard to see
9273 /// their values after they get legalized to loads from a constant pool.
9274 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9275 const ARMSubtarget *ST) {
9276 EVT VT = N->getValueType(0);
9277 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9278 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9279 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9280 SDValue N1 = N->getOperand(1);
9281 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9282 SDValue N0 = N->getOperand(0);
9283 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9284 DAG.MaskedValueIsZero(N0.getOperand(0),
9285 APInt::getHighBitsSet(32, 16)))
9286 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9290 // Nothing to be done for scalar shifts.
9291 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9292 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9295 assert(ST->hasNEON() && "unexpected vector shift");
9298 switch (N->getOpcode()) {
9299 default: llvm_unreachable("unexpected shift opcode");
9302 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9303 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9304 DAG.getConstant(Cnt, MVT::i32));
9309 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9310 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9311 ARMISD::VSHRs : ARMISD::VSHRu);
9312 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9313 DAG.getConstant(Cnt, MVT::i32));
9319 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9320 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9321 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9322 const ARMSubtarget *ST) {
9323 SDValue N0 = N->getOperand(0);
9325 // Check for sign- and zero-extensions of vector extract operations of 8-
9326 // and 16-bit vector elements. NEON supports these directly. They are
9327 // handled during DAG combining because type legalization will promote them
9328 // to 32-bit types and it is messy to recognize the operations after that.
9329 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9330 SDValue Vec = N0.getOperand(0);
9331 SDValue Lane = N0.getOperand(1);
9332 EVT VT = N->getValueType(0);
9333 EVT EltVT = N0.getValueType();
9334 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9336 if (VT == MVT::i32 &&
9337 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9338 TLI.isTypeLegal(Vec.getValueType()) &&
9339 isa<ConstantSDNode>(Lane)) {
9342 switch (N->getOpcode()) {
9343 default: llvm_unreachable("unexpected opcode");
9344 case ISD::SIGN_EXTEND:
9345 Opc = ARMISD::VGETLANEs;
9347 case ISD::ZERO_EXTEND:
9348 case ISD::ANY_EXTEND:
9349 Opc = ARMISD::VGETLANEu;
9352 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9359 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9360 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9361 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9362 const ARMSubtarget *ST) {
9363 // If the target supports NEON, try to use vmax/vmin instructions for f32
9364 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9365 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9366 // a NaN; only do the transformation when it matches that behavior.
9368 // For now only do this when using NEON for FP operations; if using VFP, it
9369 // is not obvious that the benefit outweighs the cost of switching to the
9371 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9372 N->getValueType(0) != MVT::f32)
9375 SDValue CondLHS = N->getOperand(0);
9376 SDValue CondRHS = N->getOperand(1);
9377 SDValue LHS = N->getOperand(2);
9378 SDValue RHS = N->getOperand(3);
9379 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9381 unsigned Opcode = 0;
9383 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9384 IsReversed = false; // x CC y ? x : y
9385 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9386 IsReversed = true ; // x CC y ? y : x
9400 // If LHS is NaN, an ordered comparison will be false and the result will
9401 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9402 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9403 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9404 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9406 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9407 // will return -0, so vmin can only be used for unsafe math or if one of
9408 // the operands is known to be nonzero.
9409 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9410 !DAG.getTarget().Options.UnsafeFPMath &&
9411 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9413 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9422 // If LHS is NaN, an ordered comparison will be false and the result will
9423 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9424 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9425 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9426 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9428 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9429 // will return +0, so vmax can only be used for unsafe math or if one of
9430 // the operands is known to be nonzero.
9431 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9432 !DAG.getTarget().Options.UnsafeFPMath &&
9433 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9435 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9441 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9444 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9446 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9447 SDValue Cmp = N->getOperand(4);
9448 if (Cmp.getOpcode() != ARMISD::CMPZ)
9449 // Only looking at EQ and NE cases.
9452 EVT VT = N->getValueType(0);
9454 SDValue LHS = Cmp.getOperand(0);
9455 SDValue RHS = Cmp.getOperand(1);
9456 SDValue FalseVal = N->getOperand(0);
9457 SDValue TrueVal = N->getOperand(1);
9458 SDValue ARMcc = N->getOperand(2);
9459 ARMCC::CondCodes CC =
9460 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9478 /// FIXME: Turn this into a target neutral optimization?
9480 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9481 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9482 N->getOperand(3), Cmp);
9483 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9485 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9486 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9487 N->getOperand(3), NewCmp);
9490 if (Res.getNode()) {
9491 APInt KnownZero, KnownOne;
9492 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9493 // Capture demanded bits information that would be otherwise lost.
9494 if (KnownZero == 0xfffffffe)
9495 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9496 DAG.getValueType(MVT::i1));
9497 else if (KnownZero == 0xffffff00)
9498 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9499 DAG.getValueType(MVT::i8));
9500 else if (KnownZero == 0xffff0000)
9501 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9502 DAG.getValueType(MVT::i16));
9508 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9509 DAGCombinerInfo &DCI) const {
9510 switch (N->getOpcode()) {
9512 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9513 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9514 case ISD::SUB: return PerformSUBCombine(N, DCI);
9515 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9516 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9517 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9518 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9519 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9520 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9521 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9522 case ISD::STORE: return PerformSTORECombine(N, DCI);
9523 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9524 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9525 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9526 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9527 case ISD::FP_TO_SINT:
9528 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9529 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9530 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9533 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9534 case ISD::SIGN_EXTEND:
9535 case ISD::ZERO_EXTEND:
9536 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9537 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9538 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9539 case ARMISD::VLD2DUP:
9540 case ARMISD::VLD3DUP:
9541 case ARMISD::VLD4DUP:
9542 return CombineBaseUpdate(N, DCI);
9543 case ARMISD::BUILD_VECTOR:
9544 return PerformARMBUILD_VECTORCombine(N, DCI);
9545 case ISD::INTRINSIC_VOID:
9546 case ISD::INTRINSIC_W_CHAIN:
9547 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9548 case Intrinsic::arm_neon_vld1:
9549 case Intrinsic::arm_neon_vld2:
9550 case Intrinsic::arm_neon_vld3:
9551 case Intrinsic::arm_neon_vld4:
9552 case Intrinsic::arm_neon_vld2lane:
9553 case Intrinsic::arm_neon_vld3lane:
9554 case Intrinsic::arm_neon_vld4lane:
9555 case Intrinsic::arm_neon_vst1:
9556 case Intrinsic::arm_neon_vst2:
9557 case Intrinsic::arm_neon_vst3:
9558 case Intrinsic::arm_neon_vst4:
9559 case Intrinsic::arm_neon_vst2lane:
9560 case Intrinsic::arm_neon_vst3lane:
9561 case Intrinsic::arm_neon_vst4lane:
9562 return CombineBaseUpdate(N, DCI);
9570 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9572 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9575 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9577 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9578 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9580 switch (VT.getSimpleVT().SimpleTy) {
9586 // Unaligned access can use (for example) LRDB, LRDH, LDR
9587 if (AllowsUnaligned) {
9589 *Fast = Subtarget->hasV7Ops();
9596 // For any little-endian targets with neon, we can support unaligned ld/st
9597 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9598 // A big-endian target may also explicitly support unaligned accesses
9599 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9609 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9610 unsigned AlignCheck) {
9611 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9612 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9615 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9616 unsigned DstAlign, unsigned SrcAlign,
9617 bool IsMemset, bool ZeroMemset,
9619 MachineFunction &MF) const {
9620 const Function *F = MF.getFunction();
9622 // See if we can use NEON instructions for this...
9623 if ((!IsMemset || ZeroMemset) &&
9624 Subtarget->hasNEON() &&
9625 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9626 Attribute::NoImplicitFloat)) {
9629 (memOpAlign(SrcAlign, DstAlign, 16) ||
9630 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9632 } else if (Size >= 8 &&
9633 (memOpAlign(SrcAlign, DstAlign, 8) ||
9634 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9639 // Lowering to i32/i16 if the size permits.
9645 // Let the target-independent logic figure it out.
9649 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9650 if (Val.getOpcode() != ISD::LOAD)
9653 EVT VT1 = Val.getValueType();
9654 if (!VT1.isSimple() || !VT1.isInteger() ||
9655 !VT2.isSimple() || !VT2.isInteger())
9658 switch (VT1.getSimpleVT().SimpleTy) {
9663 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9670 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9671 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9674 if (!isTypeLegal(EVT::getEVT(Ty1)))
9677 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9679 // Assuming the caller doesn't have a zeroext or signext return parameter,
9680 // truncation all the way down to i1 is valid.
9685 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9690 switch (VT.getSimpleVT().SimpleTy) {
9691 default: return false;
9706 if ((V & (Scale - 1)) != 0)
9709 return V == (V & ((1LL << 5) - 1));
9712 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9713 const ARMSubtarget *Subtarget) {
9720 switch (VT.getSimpleVT().SimpleTy) {
9721 default: return false;
9726 // + imm12 or - imm8
9728 return V == (V & ((1LL << 8) - 1));
9729 return V == (V & ((1LL << 12) - 1));
9732 // Same as ARM mode. FIXME: NEON?
9733 if (!Subtarget->hasVFP2())
9738 return V == (V & ((1LL << 8) - 1));
9742 /// isLegalAddressImmediate - Return true if the integer value can be used
9743 /// as the offset of the target addressing mode for load / store of the
9745 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9746 const ARMSubtarget *Subtarget) {
9753 if (Subtarget->isThumb1Only())
9754 return isLegalT1AddressImmediate(V, VT);
9755 else if (Subtarget->isThumb2())
9756 return isLegalT2AddressImmediate(V, VT, Subtarget);
9761 switch (VT.getSimpleVT().SimpleTy) {
9762 default: return false;
9767 return V == (V & ((1LL << 12) - 1));
9770 return V == (V & ((1LL << 8) - 1));
9773 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9778 return V == (V & ((1LL << 8) - 1));
9782 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9784 int Scale = AM.Scale;
9788 switch (VT.getSimpleVT().SimpleTy) {
9789 default: return false;
9798 return Scale == 2 || Scale == 4 || Scale == 8;
9801 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9805 // Note, we allow "void" uses (basically, uses that aren't loads or
9806 // stores), because arm allows folding a scale into many arithmetic
9807 // operations. This should be made more precise and revisited later.
9809 // Allow r << imm, but the imm has to be a multiple of two.
9810 if (Scale & 1) return false;
9811 return isPowerOf2_32(Scale);
9815 /// isLegalAddressingMode - Return true if the addressing mode represented
9816 /// by AM is legal for this target, for a load/store of the specified type.
9817 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9819 EVT VT = getValueType(Ty, true);
9820 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9823 // Can never fold addr of global into load/store.
9828 case 0: // no scale reg, must be "r+i" or "r", or "i".
9831 if (Subtarget->isThumb1Only())
9835 // ARM doesn't support any R+R*scale+imm addr modes.
9842 if (Subtarget->isThumb2())
9843 return isLegalT2ScaledAddressingMode(AM, VT);
9845 int Scale = AM.Scale;
9846 switch (VT.getSimpleVT().SimpleTy) {
9847 default: return false;
9851 if (Scale < 0) Scale = -Scale;
9855 return isPowerOf2_32(Scale & ~1);
9859 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9864 // Note, we allow "void" uses (basically, uses that aren't loads or
9865 // stores), because arm allows folding a scale into many arithmetic
9866 // operations. This should be made more precise and revisited later.
9868 // Allow r << imm, but the imm has to be a multiple of two.
9869 if (Scale & 1) return false;
9870 return isPowerOf2_32(Scale);
9876 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9877 /// icmp immediate, that is the target has icmp instructions which can compare
9878 /// a register against the immediate without having to materialize the
9879 /// immediate into a register.
9880 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9881 // Thumb2 and ARM modes can use cmn for negative immediates.
9882 if (!Subtarget->isThumb())
9883 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9884 if (Subtarget->isThumb2())
9885 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9886 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9887 return Imm >= 0 && Imm <= 255;
9890 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9891 /// *or sub* immediate, that is the target has add or sub instructions which can
9892 /// add a register with the immediate without having to materialize the
9893 /// immediate into a register.
9894 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9895 // Same encoding for add/sub, just flip the sign.
9896 int64_t AbsImm = llvm::abs64(Imm);
9897 if (!Subtarget->isThumb())
9898 return ARM_AM::getSOImmVal(AbsImm) != -1;
9899 if (Subtarget->isThumb2())
9900 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9901 // Thumb1 only has 8-bit unsigned immediate.
9902 return AbsImm >= 0 && AbsImm <= 255;
9905 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9906 bool isSEXTLoad, SDValue &Base,
9907 SDValue &Offset, bool &isInc,
9908 SelectionDAG &DAG) {
9909 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9912 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9914 Base = Ptr->getOperand(0);
9915 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9916 int RHSC = (int)RHS->getZExtValue();
9917 if (RHSC < 0 && RHSC > -256) {
9918 assert(Ptr->getOpcode() == ISD::ADD);
9920 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9924 isInc = (Ptr->getOpcode() == ISD::ADD);
9925 Offset = Ptr->getOperand(1);
9927 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9929 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9930 int RHSC = (int)RHS->getZExtValue();
9931 if (RHSC < 0 && RHSC > -0x1000) {
9932 assert(Ptr->getOpcode() == ISD::ADD);
9934 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9935 Base = Ptr->getOperand(0);
9940 if (Ptr->getOpcode() == ISD::ADD) {
9942 ARM_AM::ShiftOpc ShOpcVal=
9943 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9944 if (ShOpcVal != ARM_AM::no_shift) {
9945 Base = Ptr->getOperand(1);
9946 Offset = Ptr->getOperand(0);
9948 Base = Ptr->getOperand(0);
9949 Offset = Ptr->getOperand(1);
9954 isInc = (Ptr->getOpcode() == ISD::ADD);
9955 Base = Ptr->getOperand(0);
9956 Offset = Ptr->getOperand(1);
9960 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9964 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9965 bool isSEXTLoad, SDValue &Base,
9966 SDValue &Offset, bool &isInc,
9967 SelectionDAG &DAG) {
9968 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9971 Base = Ptr->getOperand(0);
9972 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9973 int RHSC = (int)RHS->getZExtValue();
9974 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9975 assert(Ptr->getOpcode() == ISD::ADD);
9977 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9979 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9980 isInc = Ptr->getOpcode() == ISD::ADD;
9981 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9989 /// getPreIndexedAddressParts - returns true by value, base pointer and
9990 /// offset pointer and addressing mode by reference if the node's address
9991 /// can be legally represented as pre-indexed load / store address.
9993 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9995 ISD::MemIndexedMode &AM,
9996 SelectionDAG &DAG) const {
9997 if (Subtarget->isThumb1Only())
10002 bool isSEXTLoad = false;
10003 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10004 Ptr = LD->getBasePtr();
10005 VT = LD->getMemoryVT();
10006 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10007 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10008 Ptr = ST->getBasePtr();
10009 VT = ST->getMemoryVT();
10014 bool isLegal = false;
10015 if (Subtarget->isThumb2())
10016 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10017 Offset, isInc, DAG);
10019 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10020 Offset, isInc, DAG);
10024 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10028 /// getPostIndexedAddressParts - returns true by value, base pointer and
10029 /// offset pointer and addressing mode by reference if this node can be
10030 /// combined with a load / store to form a post-indexed load / store.
10031 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10034 ISD::MemIndexedMode &AM,
10035 SelectionDAG &DAG) const {
10036 if (Subtarget->isThumb1Only())
10041 bool isSEXTLoad = false;
10042 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10043 VT = LD->getMemoryVT();
10044 Ptr = LD->getBasePtr();
10045 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10046 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10047 VT = ST->getMemoryVT();
10048 Ptr = ST->getBasePtr();
10053 bool isLegal = false;
10054 if (Subtarget->isThumb2())
10055 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10058 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10064 // Swap base ptr and offset to catch more post-index load / store when
10065 // it's legal. In Thumb2 mode, offset must be an immediate.
10066 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10067 !Subtarget->isThumb2())
10068 std::swap(Base, Offset);
10070 // Post-indexed load / store update the base pointer.
10075 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10079 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10082 const SelectionDAG &DAG,
10083 unsigned Depth) const {
10084 unsigned BitWidth = KnownOne.getBitWidth();
10085 KnownZero = KnownOne = APInt(BitWidth, 0);
10086 switch (Op.getOpcode()) {
10092 // These nodes' second result is a boolean
10093 if (Op.getResNo() == 0)
10095 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10097 case ARMISD::CMOV: {
10098 // Bits are known zero/one if known on the LHS and RHS.
10099 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10100 if (KnownZero == 0 && KnownOne == 0) return;
10102 APInt KnownZeroRHS, KnownOneRHS;
10103 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10104 KnownZero &= KnownZeroRHS;
10105 KnownOne &= KnownOneRHS;
10108 case ISD::INTRINSIC_W_CHAIN: {
10109 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10110 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10113 case Intrinsic::arm_ldaex:
10114 case Intrinsic::arm_ldrex: {
10115 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10116 unsigned MemBits = VT.getScalarType().getSizeInBits();
10117 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10125 //===----------------------------------------------------------------------===//
10126 // ARM Inline Assembly Support
10127 //===----------------------------------------------------------------------===//
10129 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10130 // Looking for "rev" which is V6+.
10131 if (!Subtarget->hasV6Ops())
10134 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10135 std::string AsmStr = IA->getAsmString();
10136 SmallVector<StringRef, 4> AsmPieces;
10137 SplitString(AsmStr, AsmPieces, ";\n");
10139 switch (AsmPieces.size()) {
10140 default: return false;
10142 AsmStr = AsmPieces[0];
10144 SplitString(AsmStr, AsmPieces, " \t,");
10147 if (AsmPieces.size() == 3 &&
10148 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10149 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10150 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10151 if (Ty && Ty->getBitWidth() == 32)
10152 return IntrinsicLowering::LowerToByteSwap(CI);
10160 /// getConstraintType - Given a constraint letter, return the type of
10161 /// constraint it is for this target.
10162 ARMTargetLowering::ConstraintType
10163 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10164 if (Constraint.size() == 1) {
10165 switch (Constraint[0]) {
10167 case 'l': return C_RegisterClass;
10168 case 'w': return C_RegisterClass;
10169 case 'h': return C_RegisterClass;
10170 case 'x': return C_RegisterClass;
10171 case 't': return C_RegisterClass;
10172 case 'j': return C_Other; // Constant for movw.
10173 // An address with a single base register. Due to the way we
10174 // currently handle addresses it is the same as an 'r' memory constraint.
10175 case 'Q': return C_Memory;
10177 } else if (Constraint.size() == 2) {
10178 switch (Constraint[0]) {
10180 // All 'U+' constraints are addresses.
10181 case 'U': return C_Memory;
10184 return TargetLowering::getConstraintType(Constraint);
10187 /// Examine constraint type and operand type and determine a weight value.
10188 /// This object must already have been set up with the operand type
10189 /// and the current alternative constraint selected.
10190 TargetLowering::ConstraintWeight
10191 ARMTargetLowering::getSingleConstraintMatchWeight(
10192 AsmOperandInfo &info, const char *constraint) const {
10193 ConstraintWeight weight = CW_Invalid;
10194 Value *CallOperandVal = info.CallOperandVal;
10195 // If we don't have a value, we can't do a match,
10196 // but allow it at the lowest weight.
10197 if (!CallOperandVal)
10199 Type *type = CallOperandVal->getType();
10200 // Look at the constraint type.
10201 switch (*constraint) {
10203 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10206 if (type->isIntegerTy()) {
10207 if (Subtarget->isThumb())
10208 weight = CW_SpecificReg;
10210 weight = CW_Register;
10214 if (type->isFloatingPointTy())
10215 weight = CW_Register;
10221 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10223 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10225 if (Constraint.size() == 1) {
10226 // GCC ARM Constraint Letters
10227 switch (Constraint[0]) {
10228 case 'l': // Low regs or general regs.
10229 if (Subtarget->isThumb())
10230 return RCPair(0U, &ARM::tGPRRegClass);
10231 return RCPair(0U, &ARM::GPRRegClass);
10232 case 'h': // High regs or no regs.
10233 if (Subtarget->isThumb())
10234 return RCPair(0U, &ARM::hGPRRegClass);
10237 return RCPair(0U, &ARM::GPRRegClass);
10239 if (VT == MVT::Other)
10241 if (VT == MVT::f32)
10242 return RCPair(0U, &ARM::SPRRegClass);
10243 if (VT.getSizeInBits() == 64)
10244 return RCPair(0U, &ARM::DPRRegClass);
10245 if (VT.getSizeInBits() == 128)
10246 return RCPair(0U, &ARM::QPRRegClass);
10249 if (VT == MVT::Other)
10251 if (VT == MVT::f32)
10252 return RCPair(0U, &ARM::SPR_8RegClass);
10253 if (VT.getSizeInBits() == 64)
10254 return RCPair(0U, &ARM::DPR_8RegClass);
10255 if (VT.getSizeInBits() == 128)
10256 return RCPair(0U, &ARM::QPR_8RegClass);
10259 if (VT == MVT::f32)
10260 return RCPair(0U, &ARM::SPRRegClass);
10264 if (StringRef("{cc}").equals_lower(Constraint))
10265 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10267 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10270 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10271 /// vector. If it is invalid, don't add anything to Ops.
10272 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10273 std::string &Constraint,
10274 std::vector<SDValue>&Ops,
10275 SelectionDAG &DAG) const {
10278 // Currently only support length 1 constraints.
10279 if (Constraint.length() != 1) return;
10281 char ConstraintLetter = Constraint[0];
10282 switch (ConstraintLetter) {
10285 case 'I': case 'J': case 'K': case 'L':
10286 case 'M': case 'N': case 'O':
10287 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10291 int64_t CVal64 = C->getSExtValue();
10292 int CVal = (int) CVal64;
10293 // None of these constraints allow values larger than 32 bits. Check
10294 // that the value fits in an int.
10295 if (CVal != CVal64)
10298 switch (ConstraintLetter) {
10300 // Constant suitable for movw, must be between 0 and
10302 if (Subtarget->hasV6T2Ops())
10303 if (CVal >= 0 && CVal <= 65535)
10307 if (Subtarget->isThumb1Only()) {
10308 // This must be a constant between 0 and 255, for ADD
10310 if (CVal >= 0 && CVal <= 255)
10312 } else if (Subtarget->isThumb2()) {
10313 // A constant that can be used as an immediate value in a
10314 // data-processing instruction.
10315 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10318 // A constant that can be used as an immediate value in a
10319 // data-processing instruction.
10320 if (ARM_AM::getSOImmVal(CVal) != -1)
10326 if (Subtarget->isThumb()) { // FIXME thumb2
10327 // This must be a constant between -255 and -1, for negated ADD
10328 // immediates. This can be used in GCC with an "n" modifier that
10329 // prints the negated value, for use with SUB instructions. It is
10330 // not useful otherwise but is implemented for compatibility.
10331 if (CVal >= -255 && CVal <= -1)
10334 // This must be a constant between -4095 and 4095. It is not clear
10335 // what this constraint is intended for. Implemented for
10336 // compatibility with GCC.
10337 if (CVal >= -4095 && CVal <= 4095)
10343 if (Subtarget->isThumb1Only()) {
10344 // A 32-bit value where only one byte has a nonzero value. Exclude
10345 // zero to match GCC. This constraint is used by GCC internally for
10346 // constants that can be loaded with a move/shift combination.
10347 // It is not useful otherwise but is implemented for compatibility.
10348 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10350 } else if (Subtarget->isThumb2()) {
10351 // A constant whose bitwise inverse can be used as an immediate
10352 // value in a data-processing instruction. This can be used in GCC
10353 // with a "B" modifier that prints the inverted value, for use with
10354 // BIC and MVN instructions. It is not useful otherwise but is
10355 // implemented for compatibility.
10356 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10359 // A constant whose bitwise inverse can be used as an immediate
10360 // value in a data-processing instruction. This can be used in GCC
10361 // with a "B" modifier that prints the inverted value, for use with
10362 // BIC and MVN instructions. It is not useful otherwise but is
10363 // implemented for compatibility.
10364 if (ARM_AM::getSOImmVal(~CVal) != -1)
10370 if (Subtarget->isThumb1Only()) {
10371 // This must be a constant between -7 and 7,
10372 // for 3-operand ADD/SUB immediate instructions.
10373 if (CVal >= -7 && CVal < 7)
10375 } else if (Subtarget->isThumb2()) {
10376 // A constant whose negation can be used as an immediate value in a
10377 // data-processing instruction. This can be used in GCC with an "n"
10378 // modifier that prints the negated value, for use with SUB
10379 // instructions. It is not useful otherwise but is implemented for
10381 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10384 // A constant whose negation can be used as an immediate value in a
10385 // data-processing instruction. This can be used in GCC with an "n"
10386 // modifier that prints the negated value, for use with SUB
10387 // instructions. It is not useful otherwise but is implemented for
10389 if (ARM_AM::getSOImmVal(-CVal) != -1)
10395 if (Subtarget->isThumb()) { // FIXME thumb2
10396 // This must be a multiple of 4 between 0 and 1020, for
10397 // ADD sp + immediate.
10398 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10401 // A power of two or a constant between 0 and 32. This is used in
10402 // GCC for the shift amount on shifted register operands, but it is
10403 // useful in general for any shift amounts.
10404 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10410 if (Subtarget->isThumb()) { // FIXME thumb2
10411 // This must be a constant between 0 and 31, for shift amounts.
10412 if (CVal >= 0 && CVal <= 31)
10418 if (Subtarget->isThumb()) { // FIXME thumb2
10419 // This must be a multiple of 4 between -508 and 508, for
10420 // ADD/SUB sp = sp + immediate.
10421 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10426 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10430 if (Result.getNode()) {
10431 Ops.push_back(Result);
10434 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10437 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10438 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10439 unsigned Opcode = Op->getOpcode();
10440 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10441 "Invalid opcode for Div/Rem lowering");
10442 bool isSigned = (Opcode == ISD::SDIVREM);
10443 EVT VT = Op->getValueType(0);
10444 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10447 switch (VT.getSimpleVT().SimpleTy) {
10448 default: llvm_unreachable("Unexpected request for libcall!");
10449 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10450 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10451 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10452 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10455 SDValue InChain = DAG.getEntryNode();
10457 TargetLowering::ArgListTy Args;
10458 TargetLowering::ArgListEntry Entry;
10459 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10460 EVT ArgVT = Op->getOperand(i).getValueType();
10461 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10462 Entry.Node = Op->getOperand(i);
10464 Entry.isSExt = isSigned;
10465 Entry.isZExt = !isSigned;
10466 Args.push_back(Entry);
10469 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10472 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10475 TargetLowering::CallLoweringInfo CLI(DAG);
10476 CLI.setDebugLoc(dl).setChain(InChain)
10477 .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10478 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10480 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10481 return CallInfo.first;
10485 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10486 // The ARM target isn't yet aware of offsets.
10490 bool ARM::isBitFieldInvertedMask(unsigned v) {
10491 if (v == 0xffffffff)
10494 // there can be 1's on either or both "outsides", all the "inside"
10495 // bits must be 0's
10496 unsigned TO = CountTrailingOnes_32(v);
10497 unsigned LO = CountLeadingOnes_32(v);
10498 v = (v >> TO) << TO;
10499 v = (v << LO) >> LO;
10503 /// isFPImmLegal - Returns true if the target can instruction select the
10504 /// specified FP immediate natively. If false, the legalizer will
10505 /// materialize the FP immediate as a load from a constant pool.
10506 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10507 if (!Subtarget->hasVFP3())
10509 if (VT == MVT::f32)
10510 return ARM_AM::getFP32Imm(Imm) != -1;
10511 if (VT == MVT::f64)
10512 return ARM_AM::getFP64Imm(Imm) != -1;
10516 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10517 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10518 /// specified in the intrinsic calls.
10519 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10521 unsigned Intrinsic) const {
10522 switch (Intrinsic) {
10523 case Intrinsic::arm_neon_vld1:
10524 case Intrinsic::arm_neon_vld2:
10525 case Intrinsic::arm_neon_vld3:
10526 case Intrinsic::arm_neon_vld4:
10527 case Intrinsic::arm_neon_vld2lane:
10528 case Intrinsic::arm_neon_vld3lane:
10529 case Intrinsic::arm_neon_vld4lane: {
10530 Info.opc = ISD::INTRINSIC_W_CHAIN;
10531 // Conservatively set memVT to the entire set of vectors loaded.
10532 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10533 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10534 Info.ptrVal = I.getArgOperand(0);
10536 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10537 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10538 Info.vol = false; // volatile loads with NEON intrinsics not supported
10539 Info.readMem = true;
10540 Info.writeMem = false;
10543 case Intrinsic::arm_neon_vst1:
10544 case Intrinsic::arm_neon_vst2:
10545 case Intrinsic::arm_neon_vst3:
10546 case Intrinsic::arm_neon_vst4:
10547 case Intrinsic::arm_neon_vst2lane:
10548 case Intrinsic::arm_neon_vst3lane:
10549 case Intrinsic::arm_neon_vst4lane: {
10550 Info.opc = ISD::INTRINSIC_VOID;
10551 // Conservatively set memVT to the entire set of vectors stored.
10552 unsigned NumElts = 0;
10553 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10554 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10555 if (!ArgTy->isVectorTy())
10557 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10559 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10560 Info.ptrVal = I.getArgOperand(0);
10562 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10563 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10564 Info.vol = false; // volatile stores with NEON intrinsics not supported
10565 Info.readMem = false;
10566 Info.writeMem = true;
10569 case Intrinsic::arm_ldaex:
10570 case Intrinsic::arm_ldrex: {
10571 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10572 Info.opc = ISD::INTRINSIC_W_CHAIN;
10573 Info.memVT = MVT::getVT(PtrTy->getElementType());
10574 Info.ptrVal = I.getArgOperand(0);
10576 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10578 Info.readMem = true;
10579 Info.writeMem = false;
10582 case Intrinsic::arm_stlex:
10583 case Intrinsic::arm_strex: {
10584 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10585 Info.opc = ISD::INTRINSIC_W_CHAIN;
10586 Info.memVT = MVT::getVT(PtrTy->getElementType());
10587 Info.ptrVal = I.getArgOperand(1);
10589 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10591 Info.readMem = false;
10592 Info.writeMem = true;
10595 case Intrinsic::arm_stlexd:
10596 case Intrinsic::arm_strexd: {
10597 Info.opc = ISD::INTRINSIC_W_CHAIN;
10598 Info.memVT = MVT::i64;
10599 Info.ptrVal = I.getArgOperand(2);
10603 Info.readMem = false;
10604 Info.writeMem = true;
10607 case Intrinsic::arm_ldaexd:
10608 case Intrinsic::arm_ldrexd: {
10609 Info.opc = ISD::INTRINSIC_W_CHAIN;
10610 Info.memVT = MVT::i64;
10611 Info.ptrVal = I.getArgOperand(0);
10615 Info.readMem = true;
10616 Info.writeMem = false;
10626 /// \brief Returns true if it is beneficial to convert a load of a constant
10627 /// to just the constant itself.
10628 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10630 assert(Ty->isIntegerTy());
10632 unsigned Bits = Ty->getPrimitiveSizeInBits();
10633 if (Bits == 0 || Bits > 32)
10638 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10639 // Loads and stores less than 64-bits are already atomic; ones above that
10640 // are doomed anyway, so defer to the default libcall and blame the OS when
10641 // things go wrong:
10642 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10643 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10644 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10645 return LI->getType()->getPrimitiveSizeInBits() == 64;
10647 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10648 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10651 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10652 AtomicOrdering Ord) const {
10653 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10654 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10656 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10658 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10659 // intrinsic must return {i32, i32} and we have to recombine them into a
10660 // single i64 here.
10661 if (ValTy->getPrimitiveSizeInBits() == 64) {
10662 Intrinsic::ID Int =
10663 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10664 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10666 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10667 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10669 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10670 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10671 if (!Subtarget->isLittle())
10672 std::swap (Lo, Hi);
10673 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10674 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10675 return Builder.CreateOr(
10676 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10679 Type *Tys[] = { Addr->getType() };
10680 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10681 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10683 return Builder.CreateTruncOrBitCast(
10684 Builder.CreateCall(Ldrex, Addr),
10685 cast<PointerType>(Addr->getType())->getElementType());
10688 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10690 AtomicOrdering Ord) const {
10691 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10693 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10695 // Since the intrinsics must have legal type, the i64 intrinsics take two
10696 // parameters: "i32, i32". We must marshal Val into the appropriate form
10697 // before the call.
10698 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10699 Intrinsic::ID Int =
10700 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10701 Function *Strex = Intrinsic::getDeclaration(M, Int);
10702 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10704 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10705 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10706 if (!Subtarget->isLittle())
10707 std::swap (Lo, Hi);
10708 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10709 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10712 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10713 Type *Tys[] = { Addr->getType() };
10714 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10716 return Builder.CreateCall2(
10717 Strex, Builder.CreateZExtOrBitCast(
10718 Val, Strex->getFunctionType()->getParamType(0)),
10730 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10731 uint64_t &Members) {
10732 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10733 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10734 uint64_t SubMembers = 0;
10735 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10737 Members += SubMembers;
10739 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10740 uint64_t SubMembers = 0;
10741 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10743 Members += SubMembers * AT->getNumElements();
10744 } else if (Ty->isFloatTy()) {
10745 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10749 } else if (Ty->isDoubleTy()) {
10750 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10754 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10761 return VT->getBitWidth() == 64;
10763 return VT->getBitWidth() == 128;
10765 switch (VT->getBitWidth()) {
10778 return (Members > 0 && Members <= 4);
10781 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10782 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10783 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10784 if (getEffectiveCallingConv(CallConv, isVarArg) !=
10785 CallingConv::ARM_AAPCS_VFP)
10788 HABaseType Base = HA_UNKNOWN;
10789 uint64_t Members = 0;
10790 bool result = isHomogeneousAggregate(Ty, Base, Members);
10791 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");