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(TargetMachine &TM) {
159 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
160 return new TargetLoweringObjectFileMachO();
161 if (TM.getSubtarget<ARMSubtarget>().isTargetWindows())
162 return new TargetLoweringObjectFileCOFF();
163 return new ARMElfTargetObjectFile();
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167 : TargetLowering(TM, createTLOF(TM)) {
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 // Double-precision floating-point arithmetic helper functions
260 // RTABI chapter 4.1.2, Table 2
261 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
262 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
263 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
264 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
265 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
267 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
270 // Double-precision floating-point comparison helper functions
271 // RTABI chapter 4.1.2, Table 3
272 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
274 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
275 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
276 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
277 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
279 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
281 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
283 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
284 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
286 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
287 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
288 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
297 // Single-precision floating-point arithmetic helper functions
298 // RTABI chapter 4.1.2, Table 4
299 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
300 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
301 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
302 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
303 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
305 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
308 // Single-precision floating-point comparison helper functions
309 // RTABI chapter 4.1.2, Table 5
310 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
312 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
313 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
314 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
315 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
317 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
319 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
321 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
322 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
324 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
325 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
326 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
335 // Floating-point to integer conversions.
336 // RTABI chapter 4.1.2, Table 6
337 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
339 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
340 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
343 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
344 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
354 // Conversions between floating types.
355 // RTABI chapter 4.1.2, Table 7
356 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
357 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
358 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
359 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
361 // Integer to floating-point conversions.
362 // RTABI chapter 4.1.2, Table 8
363 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
364 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
365 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
366 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
367 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
368 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
369 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
370 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
371 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380 // Long long helper functions
381 // RTABI chapter 4.2, Table 9
382 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
383 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
384 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
385 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
386 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
393 // Integer division functions
394 // RTABI chapter 4.3.1
395 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
397 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
399 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
401 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
403 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
413 // RTABI chapter 4.3.4
414 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
415 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
416 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
417 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
418 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
419 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
422 if (Subtarget->isTargetWindows()) {
423 static const struct {
424 const RTLIB::Libcall Op;
425 const char * const Name;
426 const CallingConv::ID CC;
428 { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
429 { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
430 { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
431 { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
432 { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
433 { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
434 { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
435 { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
438 for (const auto &LC : LibraryCalls) {
439 setLibcallName(LC.Op, LC.Name);
440 setLibcallCallingConv(LC.Op, LC.CC);
444 // Use divmod compiler-rt calls for iOS 5.0 and later.
445 if (Subtarget->getTargetTriple().isiOS() &&
446 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
447 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
448 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
451 if (Subtarget->isThumb1Only())
452 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
454 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
455 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
456 !Subtarget->isThumb1Only()) {
457 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
458 if (!Subtarget->isFPOnlySP())
459 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
461 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
464 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
465 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
466 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
467 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
468 setTruncStoreAction((MVT::SimpleValueType)VT,
469 (MVT::SimpleValueType)InnerVT, Expand);
470 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
471 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
472 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
474 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
475 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
476 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
477 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
480 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
481 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
483 if (Subtarget->hasNEON()) {
484 addDRTypeForNEON(MVT::v2f32);
485 addDRTypeForNEON(MVT::v8i8);
486 addDRTypeForNEON(MVT::v4i16);
487 addDRTypeForNEON(MVT::v2i32);
488 addDRTypeForNEON(MVT::v1i64);
490 addQRTypeForNEON(MVT::v4f32);
491 addQRTypeForNEON(MVT::v2f64);
492 addQRTypeForNEON(MVT::v16i8);
493 addQRTypeForNEON(MVT::v8i16);
494 addQRTypeForNEON(MVT::v4i32);
495 addQRTypeForNEON(MVT::v2i64);
497 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
498 // neither Neon nor VFP support any arithmetic operations on it.
499 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
500 // supported for v4f32.
501 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
502 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
503 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
504 // FIXME: Code duplication: FDIV and FREM are expanded always, see
505 // ARMTargetLowering::addTypeForNEON method for details.
506 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
507 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
508 // FIXME: Create unittest.
509 // In another words, find a way when "copysign" appears in DAG with vector
511 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
512 // FIXME: Code duplication: SETCC has custom operation action, see
513 // ARMTargetLowering::addTypeForNEON method for details.
514 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
515 // FIXME: Create unittest for FNEG and for FABS.
516 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
517 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
518 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
519 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
520 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
521 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
522 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
523 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
524 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
525 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
526 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
527 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
528 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
529 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
530 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
531 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
532 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
533 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
534 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
536 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
537 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
538 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
539 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
540 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
541 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
542 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
543 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
544 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
545 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
546 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
547 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
548 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
549 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
550 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
552 // Mark v2f32 intrinsics.
553 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
554 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
555 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
556 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
557 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
558 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
559 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
560 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
561 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
562 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
563 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
564 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
565 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
566 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
567 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
569 // Neon does not support some operations on v1i64 and v2i64 types.
570 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
571 // Custom handling for some quad-vector types to detect VMULL.
572 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
573 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
574 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
575 // Custom handling for some vector types to avoid expensive expansions
576 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
577 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
578 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
579 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
580 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
581 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
582 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
583 // a destination type that is wider than the source, and nor does
584 // it have a FP_TO_[SU]INT instruction with a narrower destination than
586 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
587 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
588 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
589 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
591 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
592 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
594 // NEON does not have single instruction CTPOP for vectors with element
595 // types wider than 8-bits. However, custom lowering can leverage the
596 // v8i8/v16i8 vcnt instruction.
597 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
598 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
599 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
600 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
602 // NEON only has FMA instructions as of VFP4.
603 if (!Subtarget->hasVFP4()) {
604 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
605 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
608 setTargetDAGCombine(ISD::INTRINSIC_VOID);
609 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
610 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
611 setTargetDAGCombine(ISD::SHL);
612 setTargetDAGCombine(ISD::SRL);
613 setTargetDAGCombine(ISD::SRA);
614 setTargetDAGCombine(ISD::SIGN_EXTEND);
615 setTargetDAGCombine(ISD::ZERO_EXTEND);
616 setTargetDAGCombine(ISD::ANY_EXTEND);
617 setTargetDAGCombine(ISD::SELECT_CC);
618 setTargetDAGCombine(ISD::BUILD_VECTOR);
619 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
620 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
621 setTargetDAGCombine(ISD::STORE);
622 setTargetDAGCombine(ISD::FP_TO_SINT);
623 setTargetDAGCombine(ISD::FP_TO_UINT);
624 setTargetDAGCombine(ISD::FDIV);
626 // It is legal to extload from v4i8 to v4i16 or v4i32.
627 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
628 MVT::v4i16, MVT::v2i16,
630 for (unsigned i = 0; i < 6; ++i) {
631 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
632 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
633 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
637 // ARM and Thumb2 support UMLAL/SMLAL.
638 if (!Subtarget->isThumb1Only())
639 setTargetDAGCombine(ISD::ADDC);
642 computeRegisterProperties();
644 // ARM does not have f32 extending load.
645 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
647 // ARM does not have i1 sign extending load.
648 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
650 // ARM supports all 4 flavors of integer indexed load / store.
651 if (!Subtarget->isThumb1Only()) {
652 for (unsigned im = (unsigned)ISD::PRE_INC;
653 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
654 setIndexedLoadAction(im, MVT::i1, Legal);
655 setIndexedLoadAction(im, MVT::i8, Legal);
656 setIndexedLoadAction(im, MVT::i16, Legal);
657 setIndexedLoadAction(im, MVT::i32, Legal);
658 setIndexedStoreAction(im, MVT::i1, Legal);
659 setIndexedStoreAction(im, MVT::i8, Legal);
660 setIndexedStoreAction(im, MVT::i16, Legal);
661 setIndexedStoreAction(im, MVT::i32, Legal);
665 setOperationAction(ISD::SADDO, MVT::i32, Custom);
666 setOperationAction(ISD::UADDO, MVT::i32, Custom);
667 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
668 setOperationAction(ISD::USUBO, MVT::i32, Custom);
670 // i64 operation support.
671 setOperationAction(ISD::MUL, MVT::i64, Expand);
672 setOperationAction(ISD::MULHU, MVT::i32, Expand);
673 if (Subtarget->isThumb1Only()) {
674 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
675 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
677 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
678 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
679 setOperationAction(ISD::MULHS, MVT::i32, Expand);
681 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
682 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
683 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
684 setOperationAction(ISD::SRL, MVT::i64, Custom);
685 setOperationAction(ISD::SRA, MVT::i64, Custom);
687 if (!Subtarget->isThumb1Only()) {
688 // FIXME: We should do this for Thumb1 as well.
689 setOperationAction(ISD::ADDC, MVT::i32, Custom);
690 setOperationAction(ISD::ADDE, MVT::i32, Custom);
691 setOperationAction(ISD::SUBC, MVT::i32, Custom);
692 setOperationAction(ISD::SUBE, MVT::i32, Custom);
695 // ARM does not have ROTL.
696 setOperationAction(ISD::ROTL, MVT::i32, Expand);
697 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
698 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
699 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
700 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
702 // These just redirect to CTTZ and CTLZ on ARM.
703 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
704 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
706 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
708 // Only ARMv6 has BSWAP.
709 if (!Subtarget->hasV6Ops())
710 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
712 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
713 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
714 // These are expanded into libcalls if the cpu doesn't have HW divider.
715 setOperationAction(ISD::SDIV, MVT::i32, Expand);
716 setOperationAction(ISD::UDIV, MVT::i32, Expand);
719 // FIXME: Also set divmod for SREM on EABI
720 setOperationAction(ISD::SREM, MVT::i32, Expand);
721 setOperationAction(ISD::UREM, MVT::i32, Expand);
722 // Register based DivRem for AEABI (RTABI 4.2)
723 if (Subtarget->isTargetAEABI()) {
724 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
725 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
726 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
727 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
728 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
729 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
730 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
731 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
733 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
734 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
735 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
736 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
737 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
738 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
739 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
740 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
742 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
743 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
745 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
746 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
749 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
750 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
751 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
752 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
753 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
755 setOperationAction(ISD::TRAP, MVT::Other, Legal);
757 // Use the default implementation.
758 setOperationAction(ISD::VASTART, MVT::Other, Custom);
759 setOperationAction(ISD::VAARG, MVT::Other, Expand);
760 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
761 setOperationAction(ISD::VAEND, MVT::Other, Expand);
762 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
763 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
765 if (!Subtarget->isTargetMachO()) {
766 // Non-MachO platforms may return values in these registers via the
767 // personality function.
768 setExceptionPointerRegister(ARM::R0);
769 setExceptionSelectorRegister(ARM::R1);
772 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
773 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
774 // the default expansion.
775 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777 // to ldrex/strex loops already.
778 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
780 // On v8, we have particularly efficient implementations of atomic fences
781 // if they can be combined with nearby atomic loads and stores.
782 if (!Subtarget->hasV8Ops()) {
783 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
784 setInsertFencesForAtomic(true);
787 // If there's anything we can use as a barrier, go through custom lowering
789 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
790 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
792 // Set them all for expansion, which will force libcalls.
793 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
796 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
797 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
798 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
799 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
800 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806 // Unordered/Monotonic case.
807 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
811 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
813 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814 if (!Subtarget->hasV6Ops()) {
815 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
818 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
820 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821 !Subtarget->isThumb1Only()) {
822 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823 // iff target supports vfp2.
824 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
828 // We want to custom lower some of our intrinsics.
829 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830 if (Subtarget->isTargetDarwin()) {
831 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
836 setOperationAction(ISD::SETCC, MVT::i32, Expand);
837 setOperationAction(ISD::SETCC, MVT::f32, Expand);
838 setOperationAction(ISD::SETCC, MVT::f64, Expand);
839 setOperationAction(ISD::SELECT, MVT::i32, Custom);
840 setOperationAction(ISD::SELECT, MVT::f32, Custom);
841 setOperationAction(ISD::SELECT, MVT::f64, Custom);
842 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
846 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
847 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
848 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
849 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
850 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
852 // We don't support sin/cos/fmod/copysign/pow
853 setOperationAction(ISD::FSIN, MVT::f64, Expand);
854 setOperationAction(ISD::FSIN, MVT::f32, Expand);
855 setOperationAction(ISD::FCOS, MVT::f32, Expand);
856 setOperationAction(ISD::FCOS, MVT::f64, Expand);
857 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
858 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
859 setOperationAction(ISD::FREM, MVT::f64, Expand);
860 setOperationAction(ISD::FREM, MVT::f32, Expand);
861 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862 !Subtarget->isThumb1Only()) {
863 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
866 setOperationAction(ISD::FPOW, MVT::f64, Expand);
867 setOperationAction(ISD::FPOW, MVT::f32, Expand);
869 if (!Subtarget->hasVFP4()) {
870 setOperationAction(ISD::FMA, MVT::f64, Expand);
871 setOperationAction(ISD::FMA, MVT::f32, Expand);
874 // Various VFP goodness
875 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877 if (Subtarget->hasVFP2()) {
878 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
883 // Special handling for half-precision FP.
884 if (!Subtarget->hasFP16()) {
885 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
886 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
890 // Combine sin / cos into one node or libcall if possible.
891 if (Subtarget->hasSinCos()) {
892 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
893 setLibcallName(RTLIB::SINCOS_F64, "sincos");
894 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
895 // For iOS, we don't want to the normal expansion of a libcall to
896 // sincos. We want to issue a libcall to __sincos_stret.
897 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
898 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
902 // We have target-specific dag combine patterns for the following nodes:
903 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
904 setTargetDAGCombine(ISD::ADD);
905 setTargetDAGCombine(ISD::SUB);
906 setTargetDAGCombine(ISD::MUL);
907 setTargetDAGCombine(ISD::AND);
908 setTargetDAGCombine(ISD::OR);
909 setTargetDAGCombine(ISD::XOR);
911 if (Subtarget->hasV6Ops())
912 setTargetDAGCombine(ISD::SRL);
914 setStackPointerRegisterToSaveRestore(ARM::SP);
916 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
917 !Subtarget->hasVFP2())
918 setSchedulingPreference(Sched::RegPressure);
920 setSchedulingPreference(Sched::Hybrid);
922 //// temporary - rewrite interface to use type
923 MaxStoresPerMemset = 8;
924 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
925 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
926 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
927 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
928 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
930 // On ARM arguments smaller than 4 bytes are extended, so all arguments
931 // are at least 4 bytes aligned.
932 setMinStackArgumentAlignment(4);
934 // Prefer likely predicted branches to selects on out-of-order cores.
935 PredictableSelectIsExpensive = Subtarget->isLikeA9();
937 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
940 // FIXME: It might make sense to define the representative register class as the
941 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
942 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
943 // SPR's representative would be DPR_VFP2. This should work well if register
944 // pressure tracking were modified such that a register use would increment the
945 // pressure of the register class's representative and all of it's super
946 // classes' representatives transitively. We have not implemented this because
947 // of the difficulty prior to coalescing of modeling operand register classes
948 // due to the common occurrence of cross class copies and subregister insertions
950 std::pair<const TargetRegisterClass*, uint8_t>
951 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
952 const TargetRegisterClass *RRC = nullptr;
954 switch (VT.SimpleTy) {
956 return TargetLowering::findRepresentativeClass(VT);
957 // Use DPR as representative register class for all floating point
958 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
959 // the cost is 1 for both f32 and f64.
960 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
961 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
962 RRC = &ARM::DPRRegClass;
963 // When NEON is used for SP, only half of the register file is available
964 // because operations that define both SP and DP results will be constrained
965 // to the VFP2 class (D0-D15). We currently model this constraint prior to
966 // coalescing by double-counting the SP regs. See the FIXME above.
967 if (Subtarget->useNEONForSinglePrecisionFP())
970 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
971 case MVT::v4f32: case MVT::v2f64:
972 RRC = &ARM::DPRRegClass;
976 RRC = &ARM::DPRRegClass;
980 RRC = &ARM::DPRRegClass;
984 return std::make_pair(RRC, Cost);
987 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
989 default: return nullptr;
990 case ARMISD::Wrapper: return "ARMISD::Wrapper";
991 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
992 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
993 case ARMISD::CALL: return "ARMISD::CALL";
994 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
995 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
996 case ARMISD::tCALL: return "ARMISD::tCALL";
997 case ARMISD::BRCOND: return "ARMISD::BRCOND";
998 case ARMISD::BR_JT: return "ARMISD::BR_JT";
999 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1000 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1001 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1002 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1003 case ARMISD::CMP: return "ARMISD::CMP";
1004 case ARMISD::CMN: return "ARMISD::CMN";
1005 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1006 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1007 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1008 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1009 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1011 case ARMISD::CMOV: return "ARMISD::CMOV";
1013 case ARMISD::RBIT: return "ARMISD::RBIT";
1015 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1016 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1017 case ARMISD::SITOF: return "ARMISD::SITOF";
1018 case ARMISD::UITOF: return "ARMISD::UITOF";
1020 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1021 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1022 case ARMISD::RRX: return "ARMISD::RRX";
1024 case ARMISD::ADDC: return "ARMISD::ADDC";
1025 case ARMISD::ADDE: return "ARMISD::ADDE";
1026 case ARMISD::SUBC: return "ARMISD::SUBC";
1027 case ARMISD::SUBE: return "ARMISD::SUBE";
1029 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1030 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1032 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1033 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1035 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1037 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1039 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1041 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1043 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1045 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1046 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1047 case ARMISD::VCGE: return "ARMISD::VCGE";
1048 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1049 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1050 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1051 case ARMISD::VCGT: return "ARMISD::VCGT";
1052 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1053 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1054 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1055 case ARMISD::VTST: return "ARMISD::VTST";
1057 case ARMISD::VSHL: return "ARMISD::VSHL";
1058 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1059 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1060 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1061 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1062 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1063 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1064 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1065 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1066 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1067 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1068 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1069 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1070 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1071 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1072 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1073 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1074 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1075 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1076 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1077 case ARMISD::VDUP: return "ARMISD::VDUP";
1078 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1079 case ARMISD::VEXT: return "ARMISD::VEXT";
1080 case ARMISD::VREV64: return "ARMISD::VREV64";
1081 case ARMISD::VREV32: return "ARMISD::VREV32";
1082 case ARMISD::VREV16: return "ARMISD::VREV16";
1083 case ARMISD::VZIP: return "ARMISD::VZIP";
1084 case ARMISD::VUZP: return "ARMISD::VUZP";
1085 case ARMISD::VTRN: return "ARMISD::VTRN";
1086 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1087 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1088 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1089 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1090 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1091 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1092 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1093 case ARMISD::FMAX: return "ARMISD::FMAX";
1094 case ARMISD::FMIN: return "ARMISD::FMIN";
1095 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1096 case ARMISD::VMINNM: return "ARMISD::VMIN";
1097 case ARMISD::BFI: return "ARMISD::BFI";
1098 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1099 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1100 case ARMISD::VBSL: return "ARMISD::VBSL";
1101 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1102 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1103 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1104 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1105 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1106 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1107 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1108 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1109 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1110 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1111 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1112 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1113 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1114 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1115 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1116 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1117 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1118 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1119 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1120 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1124 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1125 if (!VT.isVector()) return getPointerTy();
1126 return VT.changeVectorElementTypeToInteger();
1129 /// getRegClassFor - Return the register class that should be used for the
1130 /// specified value type.
1131 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1132 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1133 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1134 // load / store 4 to 8 consecutive D registers.
1135 if (Subtarget->hasNEON()) {
1136 if (VT == MVT::v4i64)
1137 return &ARM::QQPRRegClass;
1138 if (VT == MVT::v8i64)
1139 return &ARM::QQQQPRRegClass;
1141 return TargetLowering::getRegClassFor(VT);
1144 // Create a fast isel object.
1146 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1147 const TargetLibraryInfo *libInfo) const {
1148 return ARM::createFastISel(funcInfo, libInfo);
1151 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1152 /// be used for loads / stores from the global.
1153 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1154 return (Subtarget->isThumb1Only() ? 127 : 4095);
1157 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1158 unsigned NumVals = N->getNumValues();
1160 return Sched::RegPressure;
1162 for (unsigned i = 0; i != NumVals; ++i) {
1163 EVT VT = N->getValueType(i);
1164 if (VT == MVT::Glue || VT == MVT::Other)
1166 if (VT.isFloatingPoint() || VT.isVector())
1170 if (!N->isMachineOpcode())
1171 return Sched::RegPressure;
1173 // Load are scheduled for latency even if there instruction itinerary
1174 // is not available.
1175 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1176 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1178 if (MCID.getNumDefs() == 0)
1179 return Sched::RegPressure;
1180 if (!Itins->isEmpty() &&
1181 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1184 return Sched::RegPressure;
1187 //===----------------------------------------------------------------------===//
1189 //===----------------------------------------------------------------------===//
1191 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1192 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1194 default: llvm_unreachable("Unknown condition code!");
1195 case ISD::SETNE: return ARMCC::NE;
1196 case ISD::SETEQ: return ARMCC::EQ;
1197 case ISD::SETGT: return ARMCC::GT;
1198 case ISD::SETGE: return ARMCC::GE;
1199 case ISD::SETLT: return ARMCC::LT;
1200 case ISD::SETLE: return ARMCC::LE;
1201 case ISD::SETUGT: return ARMCC::HI;
1202 case ISD::SETUGE: return ARMCC::HS;
1203 case ISD::SETULT: return ARMCC::LO;
1204 case ISD::SETULE: return ARMCC::LS;
1208 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1209 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1210 ARMCC::CondCodes &CondCode2) {
1211 CondCode2 = ARMCC::AL;
1213 default: llvm_unreachable("Unknown FP condition!");
1215 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1217 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1219 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1220 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1221 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1222 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1223 case ISD::SETO: CondCode = ARMCC::VC; break;
1224 case ISD::SETUO: CondCode = ARMCC::VS; break;
1225 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1226 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1227 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1229 case ISD::SETULT: CondCode = ARMCC::LT; break;
1231 case ISD::SETULE: CondCode = ARMCC::LE; break;
1233 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1237 //===----------------------------------------------------------------------===//
1238 // Calling Convention Implementation
1239 //===----------------------------------------------------------------------===//
1241 #include "ARMGenCallingConv.inc"
1243 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1244 /// account presence of floating point hardware and calling convention
1245 /// limitations, such as support for variadic functions.
1247 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1248 bool isVarArg) const {
1251 llvm_unreachable("Unsupported calling convention");
1252 case CallingConv::ARM_AAPCS:
1253 case CallingConv::ARM_APCS:
1254 case CallingConv::GHC:
1256 case CallingConv::ARM_AAPCS_VFP:
1257 return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1258 case CallingConv::C:
1259 if (!Subtarget->isAAPCS_ABI())
1260 return CallingConv::ARM_APCS;
1261 else if (Subtarget->hasVFP2() &&
1262 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1264 return CallingConv::ARM_AAPCS_VFP;
1266 return CallingConv::ARM_AAPCS;
1267 case CallingConv::Fast:
1268 if (!Subtarget->isAAPCS_ABI()) {
1269 if (Subtarget->hasVFP2() && !isVarArg)
1270 return CallingConv::Fast;
1271 return CallingConv::ARM_APCS;
1272 } else if (Subtarget->hasVFP2() && !isVarArg)
1273 return CallingConv::ARM_AAPCS_VFP;
1275 return CallingConv::ARM_AAPCS;
1279 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1280 /// CallingConvention.
1281 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1283 bool isVarArg) const {
1284 switch (getEffectiveCallingConv(CC, isVarArg)) {
1286 llvm_unreachable("Unsupported calling convention");
1287 case CallingConv::ARM_APCS:
1288 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1289 case CallingConv::ARM_AAPCS:
1290 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291 case CallingConv::ARM_AAPCS_VFP:
1292 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1293 case CallingConv::Fast:
1294 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1295 case CallingConv::GHC:
1296 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1300 /// LowerCallResult - Lower the result values of a call into the
1301 /// appropriate copies out of appropriate physical registers.
1303 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1304 CallingConv::ID CallConv, bool isVarArg,
1305 const SmallVectorImpl<ISD::InputArg> &Ins,
1306 SDLoc dl, SelectionDAG &DAG,
1307 SmallVectorImpl<SDValue> &InVals,
1308 bool isThisReturn, SDValue ThisVal) const {
1310 // Assign locations to each value returned by this call.
1311 SmallVector<CCValAssign, 16> RVLocs;
1312 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1313 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1314 CCInfo.AnalyzeCallResult(Ins,
1315 CCAssignFnForNode(CallConv, /* Return*/ true,
1318 // Copy all of the result registers out of their specified physreg.
1319 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1320 CCValAssign VA = RVLocs[i];
1322 // Pass 'this' value directly from the argument to return value, to avoid
1323 // reg unit interference
1324 if (i == 0 && isThisReturn) {
1325 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1326 "unexpected return calling convention register assignment");
1327 InVals.push_back(ThisVal);
1332 if (VA.needsCustom()) {
1333 // Handle f64 or half of a v2f64.
1334 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1336 Chain = Lo.getValue(1);
1337 InFlag = Lo.getValue(2);
1338 VA = RVLocs[++i]; // skip ahead to next loc
1339 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1341 Chain = Hi.getValue(1);
1342 InFlag = Hi.getValue(2);
1343 if (!Subtarget->isLittle())
1345 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1347 if (VA.getLocVT() == MVT::v2f64) {
1348 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1349 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1350 DAG.getConstant(0, MVT::i32));
1352 VA = RVLocs[++i]; // skip ahead to next loc
1353 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1354 Chain = Lo.getValue(1);
1355 InFlag = Lo.getValue(2);
1356 VA = RVLocs[++i]; // skip ahead to next loc
1357 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1358 Chain = Hi.getValue(1);
1359 InFlag = Hi.getValue(2);
1360 if (!Subtarget->isLittle())
1362 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364 DAG.getConstant(1, MVT::i32));
1367 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1369 Chain = Val.getValue(1);
1370 InFlag = Val.getValue(2);
1373 switch (VA.getLocInfo()) {
1374 default: llvm_unreachable("Unknown loc info!");
1375 case CCValAssign::Full: break;
1376 case CCValAssign::BCvt:
1377 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1381 InVals.push_back(Val);
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390 SDValue StackPtr, SDValue Arg,
1391 SDLoc dl, SelectionDAG &DAG,
1392 const CCValAssign &VA,
1393 ISD::ArgFlagsTy Flags) const {
1394 unsigned LocMemOffset = VA.getLocMemOffset();
1395 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397 return DAG.getStore(Chain, dl, Arg, PtrOff,
1398 MachinePointerInfo::getStack(LocMemOffset),
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403 SDValue Chain, SDValue &Arg,
1404 RegsToPassVector &RegsToPass,
1405 CCValAssign &VA, CCValAssign &NextVA,
1407 SmallVectorImpl<SDValue> &MemOpChains,
1408 ISD::ArgFlagsTy Flags) const {
1410 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412 unsigned id = Subtarget->isLittle() ? 0 : 1;
1413 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1415 if (NextVA.isRegLoc())
1416 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1418 assert(NextVA.isMemLoc());
1419 if (!StackPtr.getNode())
1420 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1422 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1428 /// LowerCall - Lowering a call into a callseq_start <-
1429 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1432 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1433 SmallVectorImpl<SDValue> &InVals) const {
1434 SelectionDAG &DAG = CLI.DAG;
1436 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1437 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1438 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1439 SDValue Chain = CLI.Chain;
1440 SDValue Callee = CLI.Callee;
1441 bool &isTailCall = CLI.IsTailCall;
1442 CallingConv::ID CallConv = CLI.CallConv;
1443 bool doesNotRet = CLI.DoesNotReturn;
1444 bool isVarArg = CLI.IsVarArg;
1446 MachineFunction &MF = DAG.getMachineFunction();
1447 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1448 bool isThisReturn = false;
1449 bool isSibCall = false;
1451 // Disable tail calls if they're not supported.
1452 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1456 // Check if it's really possible to do a tail call.
1457 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1458 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1459 Outs, OutVals, Ins, DAG);
1460 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1461 report_fatal_error("failed to perform tail call elimination on a call "
1462 "site marked musttail");
1463 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1464 // detected sibcalls.
1471 // Analyze operands of the call, assigning locations to each operand.
1472 SmallVector<CCValAssign, 16> ArgLocs;
1473 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1474 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1475 CCInfo.AnalyzeCallOperands(Outs,
1476 CCAssignFnForNode(CallConv, /* Return*/ false,
1479 // Get a count of how many bytes are to be pushed on the stack.
1480 unsigned NumBytes = CCInfo.getNextStackOffset();
1482 // For tail calls, memory operands are available in our caller's stack.
1486 // Adjust the stack pointer for the new arguments...
1487 // These operations are automatically eliminated by the prolog/epilog pass
1489 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1492 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1494 RegsToPassVector RegsToPass;
1495 SmallVector<SDValue, 8> MemOpChains;
1497 // Walk the register/memloc assignments, inserting copies/loads. In the case
1498 // of tail call optimization, arguments are handled later.
1499 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1501 ++i, ++realArgIdx) {
1502 CCValAssign &VA = ArgLocs[i];
1503 SDValue Arg = OutVals[realArgIdx];
1504 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1505 bool isByVal = Flags.isByVal();
1507 // Promote the value if needed.
1508 switch (VA.getLocInfo()) {
1509 default: llvm_unreachable("Unknown loc info!");
1510 case CCValAssign::Full: break;
1511 case CCValAssign::SExt:
1512 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1514 case CCValAssign::ZExt:
1515 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1517 case CCValAssign::AExt:
1518 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1520 case CCValAssign::BCvt:
1521 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1525 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1526 if (VA.needsCustom()) {
1527 if (VA.getLocVT() == MVT::v2f64) {
1528 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1529 DAG.getConstant(0, MVT::i32));
1530 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1531 DAG.getConstant(1, MVT::i32));
1533 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1534 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1536 VA = ArgLocs[++i]; // skip ahead to next loc
1537 if (VA.isRegLoc()) {
1538 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1539 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1541 assert(VA.isMemLoc());
1543 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1544 dl, DAG, VA, Flags));
1547 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1548 StackPtr, MemOpChains, Flags);
1550 } else if (VA.isRegLoc()) {
1551 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1552 assert(VA.getLocVT() == MVT::i32 &&
1553 "unexpected calling convention register assignment");
1554 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1555 "unexpected use of 'returned'");
1556 isThisReturn = true;
1558 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1559 } else if (isByVal) {
1560 assert(VA.isMemLoc());
1561 unsigned offset = 0;
1563 // True if this byval aggregate will be split between registers
1565 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1566 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1568 if (CurByValIdx < ByValArgsCount) {
1570 unsigned RegBegin, RegEnd;
1571 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1573 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1575 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1576 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1577 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1578 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1579 MachinePointerInfo(),
1580 false, false, false,
1581 DAG.InferPtrAlignment(AddArg));
1582 MemOpChains.push_back(Load.getValue(1));
1583 RegsToPass.push_back(std::make_pair(j, Load));
1586 // If parameter size outsides register area, "offset" value
1587 // helps us to calculate stack slot for remained part properly.
1588 offset = RegEnd - RegBegin;
1590 CCInfo.nextInRegsParam();
1593 if (Flags.getByValSize() > 4*offset) {
1594 unsigned LocMemOffset = VA.getLocMemOffset();
1595 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1596 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1598 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1599 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1600 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1602 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1604 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1605 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1606 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1609 } else if (!isSibCall) {
1610 assert(VA.isMemLoc());
1612 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1613 dl, DAG, VA, Flags));
1617 if (!MemOpChains.empty())
1618 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1620 // Build a sequence of copy-to-reg nodes chained together with token chain
1621 // and flag operands which copy the outgoing args into the appropriate regs.
1623 // Tail call byval lowering might overwrite argument registers so in case of
1624 // tail call optimization the copies to registers are lowered later.
1626 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1628 RegsToPass[i].second, InFlag);
1629 InFlag = Chain.getValue(1);
1632 // For tail calls lower the arguments to the 'real' stack slot.
1634 // Force all the incoming stack arguments to be loaded from the stack
1635 // before any new outgoing arguments are stored to the stack, because the
1636 // outgoing stack slots may alias the incoming argument stack slots, and
1637 // the alias isn't otherwise explicit. This is slightly more conservative
1638 // than necessary, because it means that each store effectively depends
1639 // on every argument instead of just those arguments it would clobber.
1641 // Do not flag preceding copytoreg stuff together with the following stuff.
1643 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1644 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1645 RegsToPass[i].second, InFlag);
1646 InFlag = Chain.getValue(1);
1651 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1652 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1653 // node so that legalize doesn't hack it.
1654 bool isDirect = false;
1655 bool isARMFunc = false;
1656 bool isLocalARMFunc = false;
1657 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1659 if (EnableARMLongCalls) {
1660 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1661 && "long-calls with non-static relocation model!");
1662 // Handle a global address or an external symbol. If it's not one of
1663 // those, the target's already in a register, so we don't need to do
1665 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1666 const GlobalValue *GV = G->getGlobal();
1667 // Create a constant pool entry for the callee address
1668 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1669 ARMConstantPoolValue *CPV =
1670 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1672 // Get the address of the callee into a register
1673 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1674 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1675 Callee = DAG.getLoad(getPointerTy(), dl,
1676 DAG.getEntryNode(), CPAddr,
1677 MachinePointerInfo::getConstantPool(),
1678 false, false, false, 0);
1679 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1680 const char *Sym = S->getSymbol();
1682 // Create a constant pool entry for the callee address
1683 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1684 ARMConstantPoolValue *CPV =
1685 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1686 ARMPCLabelIndex, 0);
1687 // Get the address of the callee into a register
1688 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1689 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1690 Callee = DAG.getLoad(getPointerTy(), dl,
1691 DAG.getEntryNode(), CPAddr,
1692 MachinePointerInfo::getConstantPool(),
1693 false, false, false, 0);
1695 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1696 const GlobalValue *GV = G->getGlobal();
1698 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1699 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1700 getTargetMachine().getRelocationModel() != Reloc::Static;
1701 isARMFunc = !Subtarget->isThumb() || isStub;
1702 // ARM call to a local ARM function is predicable.
1703 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1704 // tBX takes a register source operand.
1705 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1706 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1707 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1708 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1710 // On ELF targets for PIC code, direct calls should go through the PLT
1711 unsigned OpFlags = 0;
1712 if (Subtarget->isTargetELF() &&
1713 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1714 OpFlags = ARMII::MO_PLT;
1715 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1717 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1719 bool isStub = Subtarget->isTargetMachO() &&
1720 getTargetMachine().getRelocationModel() != Reloc::Static;
1721 isARMFunc = !Subtarget->isThumb() || isStub;
1722 // tBX takes a register source operand.
1723 const char *Sym = S->getSymbol();
1724 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1725 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1726 ARMConstantPoolValue *CPV =
1727 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1728 ARMPCLabelIndex, 4);
1729 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1730 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1731 Callee = DAG.getLoad(getPointerTy(), dl,
1732 DAG.getEntryNode(), CPAddr,
1733 MachinePointerInfo::getConstantPool(),
1734 false, false, false, 0);
1735 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1736 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1737 getPointerTy(), Callee, PICLabel);
1739 unsigned OpFlags = 0;
1740 // On ELF targets for PIC code, direct calls should go through the PLT
1741 if (Subtarget->isTargetELF() &&
1742 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1743 OpFlags = ARMII::MO_PLT;
1744 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1748 // FIXME: handle tail calls differently.
1750 bool HasMinSizeAttr = Subtarget->isMinSize();
1751 if (Subtarget->isThumb()) {
1752 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1753 CallOpc = ARMISD::CALL_NOLINK;
1755 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1757 if (!isDirect && !Subtarget->hasV5TOps())
1758 CallOpc = ARMISD::CALL_NOLINK;
1759 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1760 // Emit regular call when code size is the priority
1762 // "mov lr, pc; b _foo" to avoid confusing the RSP
1763 CallOpc = ARMISD::CALL_NOLINK;
1765 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1768 std::vector<SDValue> Ops;
1769 Ops.push_back(Chain);
1770 Ops.push_back(Callee);
1772 // Add argument registers to the end of the list so that they are known live
1774 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1775 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1776 RegsToPass[i].second.getValueType()));
1778 // Add a register mask operand representing the call-preserved registers.
1780 const uint32_t *Mask;
1781 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1782 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1784 // For 'this' returns, use the R0-preserving mask if applicable
1785 Mask = ARI->getThisReturnPreservedMask(CallConv);
1787 // Set isThisReturn to false if the calling convention is not one that
1788 // allows 'returned' to be modeled in this way, so LowerCallResult does
1789 // not try to pass 'this' straight through
1790 isThisReturn = false;
1791 Mask = ARI->getCallPreservedMask(CallConv);
1794 Mask = ARI->getCallPreservedMask(CallConv);
1796 assert(Mask && "Missing call preserved mask for calling convention");
1797 Ops.push_back(DAG.getRegisterMask(Mask));
1800 if (InFlag.getNode())
1801 Ops.push_back(InFlag);
1803 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1805 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1807 // Returns a chain and a flag for retval copy to use.
1808 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1809 InFlag = Chain.getValue(1);
1811 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1812 DAG.getIntPtrConstant(0, true), InFlag, dl);
1814 InFlag = Chain.getValue(1);
1816 // Handle result values, copying them out of physregs into vregs that we
1818 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1819 InVals, isThisReturn,
1820 isThisReturn ? OutVals[0] : SDValue());
1823 /// HandleByVal - Every parameter *after* a byval parameter is passed
1824 /// on the stack. Remember the next parameter register to allocate,
1825 /// and then confiscate the rest of the parameter registers to insure
1828 ARMTargetLowering::HandleByVal(
1829 CCState *State, unsigned &size, unsigned Align) const {
1830 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1831 assert((State->getCallOrPrologue() == Prologue ||
1832 State->getCallOrPrologue() == Call) &&
1833 "unhandled ParmContext");
1835 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1836 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1837 unsigned AlignInRegs = Align / 4;
1838 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1839 for (unsigned i = 0; i < Waste; ++i)
1840 reg = State->AllocateReg(GPRArgRegs, 4);
1843 unsigned excess = 4 * (ARM::R4 - reg);
1845 // Special case when NSAA != SP and parameter size greater than size of
1846 // all remained GPR regs. In that case we can't split parameter, we must
1847 // send it to stack. We also must set NCRN to R4, so waste all
1848 // remained registers.
1849 const unsigned NSAAOffset = State->getNextStackOffset();
1850 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1851 while (State->AllocateReg(GPRArgRegs, 4))
1856 // First register for byval parameter is the first register that wasn't
1857 // allocated before this method call, so it would be "reg".
1858 // If parameter is small enough to be saved in range [reg, r4), then
1859 // the end (first after last) register would be reg + param-size-in-regs,
1860 // else parameter would be splitted between registers and stack,
1861 // end register would be r4 in this case.
1862 unsigned ByValRegBegin = reg;
1863 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1864 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1865 // Note, first register is allocated in the beginning of function already,
1866 // allocate remained amount of registers we need.
1867 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1868 State->AllocateReg(GPRArgRegs, 4);
1869 // A byval parameter that is split between registers and memory needs its
1870 // size truncated here.
1871 // In the case where the entire structure fits in registers, we set the
1872 // size in memory to zero.
1881 /// MatchingStackOffset - Return true if the given stack call argument is
1882 /// already available in the same position (relatively) of the caller's
1883 /// incoming argument stack.
1885 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1886 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1887 const TargetInstrInfo *TII) {
1888 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1890 if (Arg.getOpcode() == ISD::CopyFromReg) {
1891 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1892 if (!TargetRegisterInfo::isVirtualRegister(VR))
1894 MachineInstr *Def = MRI->getVRegDef(VR);
1897 if (!Flags.isByVal()) {
1898 if (!TII->isLoadFromStackSlot(Def, FI))
1903 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1904 if (Flags.isByVal())
1905 // ByVal argument is passed in as a pointer but it's now being
1906 // dereferenced. e.g.
1907 // define @foo(%struct.X* %A) {
1908 // tail call @bar(%struct.X* byval %A)
1911 SDValue Ptr = Ld->getBasePtr();
1912 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1915 FI = FINode->getIndex();
1919 assert(FI != INT_MAX);
1920 if (!MFI->isFixedObjectIndex(FI))
1922 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1925 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1926 /// for tail call optimization. Targets which want to do tail call
1927 /// optimization should implement this function.
1929 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1930 CallingConv::ID CalleeCC,
1932 bool isCalleeStructRet,
1933 bool isCallerStructRet,
1934 const SmallVectorImpl<ISD::OutputArg> &Outs,
1935 const SmallVectorImpl<SDValue> &OutVals,
1936 const SmallVectorImpl<ISD::InputArg> &Ins,
1937 SelectionDAG& DAG) const {
1938 const Function *CallerF = DAG.getMachineFunction().getFunction();
1939 CallingConv::ID CallerCC = CallerF->getCallingConv();
1940 bool CCMatch = CallerCC == CalleeCC;
1942 // Look for obvious safe cases to perform tail call optimization that do not
1943 // require ABI changes. This is what gcc calls sibcall.
1945 // Do not sibcall optimize vararg calls unless the call site is not passing
1947 if (isVarArg && !Outs.empty())
1950 // Exception-handling functions need a special set of instructions to indicate
1951 // a return to the hardware. Tail-calling another function would probably
1953 if (CallerF->hasFnAttribute("interrupt"))
1956 // Also avoid sibcall optimization if either caller or callee uses struct
1957 // return semantics.
1958 if (isCalleeStructRet || isCallerStructRet)
1961 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1962 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1963 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1964 // support in the assembler and linker to be used. This would need to be
1965 // fixed to fully support tail calls in Thumb1.
1967 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1968 // LR. This means if we need to reload LR, it takes an extra instructions,
1969 // which outweighs the value of the tail call; but here we don't know yet
1970 // whether LR is going to be used. Probably the right approach is to
1971 // generate the tail call here and turn it back into CALL/RET in
1972 // emitEpilogue if LR is used.
1974 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1975 // but we need to make sure there are enough registers; the only valid
1976 // registers are the 4 used for parameters. We don't currently do this
1978 if (Subtarget->isThumb1Only())
1981 // If the calling conventions do not match, then we'd better make sure the
1982 // results are returned in the same way as what the caller expects.
1984 SmallVector<CCValAssign, 16> RVLocs1;
1985 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1986 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1987 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1989 SmallVector<CCValAssign, 16> RVLocs2;
1990 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1991 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1992 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1994 if (RVLocs1.size() != RVLocs2.size())
1996 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1997 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1999 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2001 if (RVLocs1[i].isRegLoc()) {
2002 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2005 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2011 // If Caller's vararg or byval argument has been split between registers and
2012 // stack, do not perform tail call, since part of the argument is in caller's
2014 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2015 getInfo<ARMFunctionInfo>();
2016 if (AFI_Caller->getArgRegsSaveSize())
2019 // If the callee takes no arguments then go on to check the results of the
2021 if (!Outs.empty()) {
2022 // Check if stack adjustment is needed. For now, do not do this if any
2023 // argument is passed on the stack.
2024 SmallVector<CCValAssign, 16> ArgLocs;
2025 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2026 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2027 CCInfo.AnalyzeCallOperands(Outs,
2028 CCAssignFnForNode(CalleeCC, false, isVarArg));
2029 if (CCInfo.getNextStackOffset()) {
2030 MachineFunction &MF = DAG.getMachineFunction();
2032 // Check if the arguments are already laid out in the right way as
2033 // the caller's fixed stack objects.
2034 MachineFrameInfo *MFI = MF.getFrameInfo();
2035 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2036 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2037 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2039 ++i, ++realArgIdx) {
2040 CCValAssign &VA = ArgLocs[i];
2041 EVT RegVT = VA.getLocVT();
2042 SDValue Arg = OutVals[realArgIdx];
2043 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2044 if (VA.getLocInfo() == CCValAssign::Indirect)
2046 if (VA.needsCustom()) {
2047 // f64 and vector types are split into multiple registers or
2048 // register/stack-slot combinations. The types will not match
2049 // the registers; give up on memory f64 refs until we figure
2050 // out what to do about this.
2053 if (!ArgLocs[++i].isRegLoc())
2055 if (RegVT == MVT::v2f64) {
2056 if (!ArgLocs[++i].isRegLoc())
2058 if (!ArgLocs[++i].isRegLoc())
2061 } else if (!VA.isRegLoc()) {
2062 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2074 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2075 MachineFunction &MF, bool isVarArg,
2076 const SmallVectorImpl<ISD::OutputArg> &Outs,
2077 LLVMContext &Context) const {
2078 SmallVector<CCValAssign, 16> RVLocs;
2079 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2080 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2084 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2085 SDLoc DL, SelectionDAG &DAG) {
2086 const MachineFunction &MF = DAG.getMachineFunction();
2087 const Function *F = MF.getFunction();
2089 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2091 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2092 // version of the "preferred return address". These offsets affect the return
2093 // instruction if this is a return from PL1 without hypervisor extensions.
2094 // IRQ/FIQ: +4 "subs pc, lr, #4"
2095 // SWI: 0 "subs pc, lr, #0"
2096 // ABORT: +4 "subs pc, lr, #4"
2097 // UNDEF: +4/+2 "subs pc, lr, #0"
2098 // UNDEF varies depending on where the exception came from ARM or Thumb
2099 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2102 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2105 else if (IntKind == "SWI" || IntKind == "UNDEF")
2108 report_fatal_error("Unsupported interrupt attribute. If present, value "
2109 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2111 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2113 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2117 ARMTargetLowering::LowerReturn(SDValue Chain,
2118 CallingConv::ID CallConv, bool isVarArg,
2119 const SmallVectorImpl<ISD::OutputArg> &Outs,
2120 const SmallVectorImpl<SDValue> &OutVals,
2121 SDLoc dl, SelectionDAG &DAG) const {
2123 // CCValAssign - represent the assignment of the return value to a location.
2124 SmallVector<CCValAssign, 16> RVLocs;
2126 // CCState - Info about the registers and stack slots.
2127 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2128 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2130 // Analyze outgoing return values.
2131 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2135 SmallVector<SDValue, 4> RetOps;
2136 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2137 bool isLittleEndian = Subtarget->isLittle();
2139 // Copy the result values into the output registers.
2140 for (unsigned i = 0, realRVLocIdx = 0;
2142 ++i, ++realRVLocIdx) {
2143 CCValAssign &VA = RVLocs[i];
2144 assert(VA.isRegLoc() && "Can only return in registers!");
2146 SDValue Arg = OutVals[realRVLocIdx];
2148 switch (VA.getLocInfo()) {
2149 default: llvm_unreachable("Unknown loc info!");
2150 case CCValAssign::Full: break;
2151 case CCValAssign::BCvt:
2152 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2156 if (VA.needsCustom()) {
2157 if (VA.getLocVT() == MVT::v2f64) {
2158 // Extract the first half and return it in two registers.
2159 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2160 DAG.getConstant(0, MVT::i32));
2161 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2162 DAG.getVTList(MVT::i32, MVT::i32), Half);
2164 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2165 HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2167 Flag = Chain.getValue(1);
2168 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2169 VA = RVLocs[++i]; // skip ahead to next loc
2170 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2171 HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2173 Flag = Chain.getValue(1);
2174 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175 VA = RVLocs[++i]; // skip ahead to next loc
2177 // Extract the 2nd half and fall through to handle it as an f64 value.
2178 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2179 DAG.getConstant(1, MVT::i32));
2181 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2183 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2184 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2185 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2186 fmrrd.getValue(isLittleEndian ? 0 : 1),
2188 Flag = Chain.getValue(1);
2189 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2190 VA = RVLocs[++i]; // skip ahead to next loc
2191 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2192 fmrrd.getValue(isLittleEndian ? 1 : 0),
2195 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2197 // Guarantee that all emitted copies are
2198 // stuck together, avoiding something bad.
2199 Flag = Chain.getValue(1);
2200 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2203 // Update chain and glue.
2206 RetOps.push_back(Flag);
2208 // CPUs which aren't M-class use a special sequence to return from
2209 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2210 // though we use "subs pc, lr, #N").
2212 // M-class CPUs actually use a normal return sequence with a special
2213 // (hardware-provided) value in LR, so the normal code path works.
2214 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2215 !Subtarget->isMClass()) {
2216 if (Subtarget->isThumb1Only())
2217 report_fatal_error("interrupt attribute is not supported in Thumb1");
2218 return LowerInterruptReturn(RetOps, dl, DAG);
2221 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2224 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2225 if (N->getNumValues() != 1)
2227 if (!N->hasNUsesOfValue(1, 0))
2230 SDValue TCChain = Chain;
2231 SDNode *Copy = *N->use_begin();
2232 if (Copy->getOpcode() == ISD::CopyToReg) {
2233 // If the copy has a glue operand, we conservatively assume it isn't safe to
2234 // perform a tail call.
2235 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2237 TCChain = Copy->getOperand(0);
2238 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2239 SDNode *VMov = Copy;
2240 // f64 returned in a pair of GPRs.
2241 SmallPtrSet<SDNode*, 2> Copies;
2242 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2244 if (UI->getOpcode() != ISD::CopyToReg)
2248 if (Copies.size() > 2)
2251 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2253 SDValue UseChain = UI->getOperand(0);
2254 if (Copies.count(UseChain.getNode()))
2261 } else if (Copy->getOpcode() == ISD::BITCAST) {
2262 // f32 returned in a single GPR.
2263 if (!Copy->hasOneUse())
2265 Copy = *Copy->use_begin();
2266 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2268 TCChain = Copy->getOperand(0);
2273 bool HasRet = false;
2274 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2276 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2277 UI->getOpcode() != ARMISD::INTRET_FLAG)
2289 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2290 if (!Subtarget->supportsTailCall())
2293 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2296 return !Subtarget->isThumb1Only();
2299 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2300 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2301 // one of the above mentioned nodes. It has to be wrapped because otherwise
2302 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2303 // be used to form addressing mode. These wrapped nodes will be selected
2305 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2306 EVT PtrVT = Op.getValueType();
2307 // FIXME there is no actual debug info here
2309 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2311 if (CP->isMachineConstantPoolEntry())
2312 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2313 CP->getAlignment());
2315 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2316 CP->getAlignment());
2317 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2320 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2321 return MachineJumpTableInfo::EK_Inline;
2324 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2325 SelectionDAG &DAG) const {
2326 MachineFunction &MF = DAG.getMachineFunction();
2327 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2328 unsigned ARMPCLabelIndex = 0;
2330 EVT PtrVT = getPointerTy();
2331 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2332 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2334 if (RelocM == Reloc::Static) {
2335 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2337 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2338 ARMPCLabelIndex = AFI->createPICLabelUId();
2339 ARMConstantPoolValue *CPV =
2340 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2341 ARMCP::CPBlockAddress, PCAdj);
2342 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2344 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2345 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2346 MachinePointerInfo::getConstantPool(),
2347 false, false, false, 0);
2348 if (RelocM == Reloc::Static)
2350 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2351 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2354 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2356 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2357 SelectionDAG &DAG) const {
2359 EVT PtrVT = getPointerTy();
2360 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2361 MachineFunction &MF = DAG.getMachineFunction();
2362 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2363 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2364 ARMConstantPoolValue *CPV =
2365 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2366 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2367 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2368 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2369 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2372 SDValue Chain = Argument.getValue(1);
2374 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2375 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2377 // call __tls_get_addr.
2380 Entry.Node = Argument;
2381 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2382 Args.push_back(Entry);
2383 // FIXME: is there useful debug info available here?
2384 TargetLowering::CallLoweringInfo CLI(Chain,
2385 (Type *) Type::getInt32Ty(*DAG.getContext()),
2386 false, false, false, false,
2387 0, CallingConv::C, /*isTailCall=*/false,
2388 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2389 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2390 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2391 return CallResult.first;
2394 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2395 // "local exec" model.
2397 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2399 TLSModel::Model model) const {
2400 const GlobalValue *GV = GA->getGlobal();
2403 SDValue Chain = DAG.getEntryNode();
2404 EVT PtrVT = getPointerTy();
2405 // Get the Thread Pointer
2406 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2408 if (model == TLSModel::InitialExec) {
2409 MachineFunction &MF = DAG.getMachineFunction();
2410 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2411 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2412 // Initial exec model.
2413 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2414 ARMConstantPoolValue *CPV =
2415 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2416 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2418 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2419 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2420 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2421 MachinePointerInfo::getConstantPool(),
2422 false, false, false, 0);
2423 Chain = Offset.getValue(1);
2425 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2426 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2428 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2429 MachinePointerInfo::getConstantPool(),
2430 false, false, false, 0);
2433 assert(model == TLSModel::LocalExec);
2434 ARMConstantPoolValue *CPV =
2435 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2436 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2437 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2438 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2439 MachinePointerInfo::getConstantPool(),
2440 false, false, false, 0);
2443 // The address of the thread local variable is the add of the thread
2444 // pointer with the offset of the variable.
2445 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2449 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2450 // TODO: implement the "local dynamic" model
2451 assert(Subtarget->isTargetELF() &&
2452 "TLS not implemented for non-ELF targets");
2453 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2455 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2458 case TLSModel::GeneralDynamic:
2459 case TLSModel::LocalDynamic:
2460 return LowerToTLSGeneralDynamicModel(GA, DAG);
2461 case TLSModel::InitialExec:
2462 case TLSModel::LocalExec:
2463 return LowerToTLSExecModels(GA, DAG, model);
2465 llvm_unreachable("bogus TLS model");
2468 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2469 SelectionDAG &DAG) const {
2470 EVT PtrVT = getPointerTy();
2472 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2473 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2474 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2475 ARMConstantPoolValue *CPV =
2476 ARMConstantPoolConstant::Create(GV,
2477 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2478 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2479 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2480 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2482 MachinePointerInfo::getConstantPool(),
2483 false, false, false, 0);
2484 SDValue Chain = Result.getValue(1);
2485 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2486 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2488 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2489 MachinePointerInfo::getGOT(),
2490 false, false, false, 0);
2494 // If we have T2 ops, we can materialize the address directly via movt/movw
2495 // pair. This is always cheaper.
2496 if (Subtarget->useMovt()) {
2498 // FIXME: Once remat is capable of dealing with instructions with register
2499 // operands, expand this into two nodes.
2500 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2501 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2503 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2504 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2505 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2506 MachinePointerInfo::getConstantPool(),
2507 false, false, false, 0);
2511 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2512 SelectionDAG &DAG) const {
2513 EVT PtrVT = getPointerTy();
2515 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2516 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2518 if (Subtarget->useMovt())
2521 // FIXME: Once remat is capable of dealing with instructions with register
2522 // operands, expand this into multiple nodes
2524 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2526 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2527 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2529 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2530 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2531 MachinePointerInfo::getGOT(), false, false, false, 0);
2535 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2536 SelectionDAG &DAG) const {
2537 assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2538 assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2540 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2541 EVT PtrVT = getPointerTy();
2546 // FIXME: Once remat is capable of dealing with instructions with register
2547 // operands, expand this into two nodes.
2548 return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2549 DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2552 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2553 SelectionDAG &DAG) const {
2554 assert(Subtarget->isTargetELF() &&
2555 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2556 MachineFunction &MF = DAG.getMachineFunction();
2557 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2558 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2559 EVT PtrVT = getPointerTy();
2561 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2562 ARMConstantPoolValue *CPV =
2563 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2564 ARMPCLabelIndex, PCAdj);
2565 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2566 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2567 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2568 MachinePointerInfo::getConstantPool(),
2569 false, false, false, 0);
2570 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2571 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2575 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2577 SDValue Val = DAG.getConstant(0, MVT::i32);
2578 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2579 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2580 Op.getOperand(1), Val);
2584 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2586 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2587 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2591 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2592 const ARMSubtarget *Subtarget) const {
2593 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2596 default: return SDValue(); // Don't custom lower most intrinsics.
2597 case Intrinsic::arm_thread_pointer: {
2598 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2599 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2601 case Intrinsic::eh_sjlj_lsda: {
2602 MachineFunction &MF = DAG.getMachineFunction();
2603 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2604 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2605 EVT PtrVT = getPointerTy();
2606 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2608 unsigned PCAdj = (RelocM != Reloc::PIC_)
2609 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2610 ARMConstantPoolValue *CPV =
2611 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2612 ARMCP::CPLSDA, PCAdj);
2613 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2614 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2616 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2617 MachinePointerInfo::getConstantPool(),
2618 false, false, false, 0);
2620 if (RelocM == Reloc::PIC_) {
2621 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2622 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2626 case Intrinsic::arm_neon_vmulls:
2627 case Intrinsic::arm_neon_vmullu: {
2628 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2629 ? ARMISD::VMULLs : ARMISD::VMULLu;
2630 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2631 Op.getOperand(1), Op.getOperand(2));
2636 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2637 const ARMSubtarget *Subtarget) {
2638 // FIXME: handle "fence singlethread" more efficiently.
2640 if (!Subtarget->hasDataBarrier()) {
2641 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2642 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2644 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2645 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2646 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2647 DAG.getConstant(0, MVT::i32));
2650 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2651 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2652 unsigned Domain = ARM_MB::ISH;
2653 if (Subtarget->isMClass()) {
2654 // Only a full system barrier exists in the M-class architectures.
2655 Domain = ARM_MB::SY;
2656 } else if (Subtarget->isSwift() && Ord == Release) {
2657 // Swift happens to implement ISHST barriers in a way that's compatible with
2658 // Release semantics but weaker than ISH so we'd be fools not to use
2659 // it. Beware: other processors probably don't!
2660 Domain = ARM_MB::ISHST;
2663 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2664 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2665 DAG.getConstant(Domain, MVT::i32));
2668 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2669 const ARMSubtarget *Subtarget) {
2670 // ARM pre v5TE and Thumb1 does not have preload instructions.
2671 if (!(Subtarget->isThumb2() ||
2672 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2673 // Just preserve the chain.
2674 return Op.getOperand(0);
2677 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2679 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2680 // ARMv7 with MP extension has PLDW.
2681 return Op.getOperand(0);
2683 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2684 if (Subtarget->isThumb()) {
2686 isRead = ~isRead & 1;
2687 isData = ~isData & 1;
2690 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2691 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2692 DAG.getConstant(isData, MVT::i32));
2695 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2696 MachineFunction &MF = DAG.getMachineFunction();
2697 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2699 // vastart just stores the address of the VarArgsFrameIndex slot into the
2700 // memory location argument.
2702 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2703 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2704 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2705 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2706 MachinePointerInfo(SV), false, false, 0);
2710 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2711 SDValue &Root, SelectionDAG &DAG,
2713 MachineFunction &MF = DAG.getMachineFunction();
2714 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2716 const TargetRegisterClass *RC;
2717 if (AFI->isThumb1OnlyFunction())
2718 RC = &ARM::tGPRRegClass;
2720 RC = &ARM::GPRRegClass;
2722 // Transform the arguments stored in physical registers into virtual ones.
2723 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2724 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2727 if (NextVA.isMemLoc()) {
2728 MachineFrameInfo *MFI = MF.getFrameInfo();
2729 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2731 // Create load node to retrieve arguments from the stack.
2732 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2733 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2734 MachinePointerInfo::getFixedStack(FI),
2735 false, false, false, 0);
2737 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2738 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2740 if (!Subtarget->isLittle())
2741 std::swap (ArgValue, ArgValue2);
2742 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2746 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2747 unsigned InRegsParamRecordIdx,
2749 unsigned &ArgRegsSize,
2750 unsigned &ArgRegsSaveSize)
2753 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2754 unsigned RBegin, REnd;
2755 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2756 NumGPRs = REnd - RBegin;
2758 unsigned int firstUnalloced;
2759 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2760 sizeof(GPRArgRegs) /
2761 sizeof(GPRArgRegs[0]));
2762 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2765 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2766 ArgRegsSize = NumGPRs * 4;
2768 // If parameter is split between stack and GPRs...
2769 if (NumGPRs && Align > 4 &&
2770 (ArgRegsSize < ArgSize ||
2771 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2772 // Add padding for part of param recovered from GPRs. For example,
2773 // if Align == 8, its last byte must be at address K*8 - 1.
2774 // We need to do it, since remained (stack) part of parameter has
2775 // stack alignment, and we need to "attach" "GPRs head" without gaps
2778 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2779 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2781 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2783 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2784 ArgRegsSaveSize = ArgRegsSize + Padding;
2786 // We don't need to extend regs save size for byval parameters if they
2787 // are passed via GPRs only.
2788 ArgRegsSaveSize = ArgRegsSize;
2791 // The remaining GPRs hold either the beginning of variable-argument
2792 // data, or the beginning of an aggregate passed by value (usually
2793 // byval). Either way, we allocate stack slots adjacent to the data
2794 // provided by our caller, and store the unallocated registers there.
2795 // If this is a variadic function, the va_list pointer will begin with
2796 // these values; otherwise, this reassembles a (byval) structure that
2797 // was split between registers and memory.
2798 // Return: The frame index registers were stored into.
2800 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2801 SDLoc dl, SDValue &Chain,
2802 const Value *OrigArg,
2803 unsigned InRegsParamRecordIdx,
2804 unsigned OffsetFromOrigArg,
2808 unsigned ByValStoreOffset,
2809 unsigned TotalArgRegsSaveSize) const {
2811 // Currently, two use-cases possible:
2812 // Case #1. Non-var-args function, and we meet first byval parameter.
2813 // Setup first unallocated register as first byval register;
2814 // eat all remained registers
2815 // (these two actions are performed by HandleByVal method).
2816 // Then, here, we initialize stack frame with
2817 // "store-reg" instructions.
2818 // Case #2. Var-args function, that doesn't contain byval parameters.
2819 // The same: eat all remained unallocated registers,
2820 // initialize stack frame.
2822 MachineFunction &MF = DAG.getMachineFunction();
2823 MachineFrameInfo *MFI = MF.getFrameInfo();
2824 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2825 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2826 unsigned RBegin, REnd;
2827 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2828 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2829 firstRegToSaveIndex = RBegin - ARM::R0;
2830 lastRegToSaveIndex = REnd - ARM::R0;
2832 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2833 (GPRArgRegs, array_lengthof(GPRArgRegs));
2834 lastRegToSaveIndex = 4;
2837 unsigned ArgRegsSize, ArgRegsSaveSize;
2838 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2839 ArgRegsSize, ArgRegsSaveSize);
2841 // Store any by-val regs to their spots on the stack so that they may be
2842 // loaded by deferencing the result of formal parameter pointer or va_next.
2843 // Note: once stack area for byval/varargs registers
2844 // was initialized, it can't be initialized again.
2845 if (ArgRegsSaveSize) {
2846 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2849 assert(AFI->getStoredByValParamsPadding() == 0 &&
2850 "The only parameter may be padded.");
2851 AFI->setStoredByValParamsPadding(Padding);
2854 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2857 (int64_t)TotalArgRegsSaveSize,
2859 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2861 MFI->CreateFixedObject(Padding,
2862 ArgOffset + ByValStoreOffset -
2863 (int64_t)ArgRegsSaveSize,
2867 SmallVector<SDValue, 4> MemOps;
2868 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2869 ++firstRegToSaveIndex, ++i) {
2870 const TargetRegisterClass *RC;
2871 if (AFI->isThumb1OnlyFunction())
2872 RC = &ARM::tGPRRegClass;
2874 RC = &ARM::GPRRegClass;
2876 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2877 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2879 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2880 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2882 MemOps.push_back(Store);
2883 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2884 DAG.getConstant(4, getPointerTy()));
2887 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2889 if (!MemOps.empty())
2890 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2894 // We cannot allocate a zero-byte object for the first variadic argument,
2895 // so just make up a size.
2898 // This will point to the next argument passed via stack.
2899 return MFI->CreateFixedObject(
2900 ArgSize, ArgOffset, !ForceMutable);
2904 // Setup stack frame, the va_list pointer will start from.
2906 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2907 SDLoc dl, SDValue &Chain,
2909 unsigned TotalArgRegsSaveSize,
2910 bool ForceMutable) const {
2911 MachineFunction &MF = DAG.getMachineFunction();
2912 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2914 // Try to store any remaining integer argument regs
2915 // to their spots on the stack so that they may be loaded by deferencing
2916 // the result of va_next.
2917 // If there is no regs to be stored, just point address after last
2918 // argument passed via stack.
2920 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2921 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2922 0, TotalArgRegsSaveSize);
2924 AFI->setVarArgsFrameIndex(FrameIndex);
2928 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2929 CallingConv::ID CallConv, bool isVarArg,
2930 const SmallVectorImpl<ISD::InputArg>
2932 SDLoc dl, SelectionDAG &DAG,
2933 SmallVectorImpl<SDValue> &InVals)
2935 MachineFunction &MF = DAG.getMachineFunction();
2936 MachineFrameInfo *MFI = MF.getFrameInfo();
2938 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2940 // Assign locations to all of the incoming arguments.
2941 SmallVector<CCValAssign, 16> ArgLocs;
2942 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2943 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2944 CCInfo.AnalyzeFormalArguments(Ins,
2945 CCAssignFnForNode(CallConv, /* Return*/ false,
2948 SmallVector<SDValue, 16> ArgValues;
2949 int lastInsIndex = -1;
2951 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2952 unsigned CurArgIdx = 0;
2954 // Initially ArgRegsSaveSize is zero.
2955 // Then we increase this value each time we meet byval parameter.
2956 // We also increase this value in case of varargs function.
2957 AFI->setArgRegsSaveSize(0);
2959 unsigned ByValStoreOffset = 0;
2960 unsigned TotalArgRegsSaveSize = 0;
2961 unsigned ArgRegsSaveSizeMaxAlign = 4;
2963 // Calculate the amount of stack space that we need to allocate to store
2964 // byval and variadic arguments that are passed in registers.
2965 // We need to know this before we allocate the first byval or variadic
2966 // argument, as they will be allocated a stack slot below the CFA (Canonical
2967 // Frame Address, the stack pointer at entry to the function).
2968 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2969 CCValAssign &VA = ArgLocs[i];
2970 if (VA.isMemLoc()) {
2971 int index = VA.getValNo();
2972 if (index != lastInsIndex) {
2973 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2974 if (Flags.isByVal()) {
2975 unsigned ExtraArgRegsSize;
2976 unsigned ExtraArgRegsSaveSize;
2977 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2978 Flags.getByValSize(),
2979 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2981 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2982 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2983 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2984 CCInfo.nextInRegsParam();
2986 lastInsIndex = index;
2990 CCInfo.rewindByValRegsInfo();
2993 unsigned ExtraArgRegsSize;
2994 unsigned ExtraArgRegsSaveSize;
2995 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2996 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2997 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2999 // If the arg regs save area contains N-byte aligned values, the
3000 // bottom of it must be at least N-byte aligned.
3001 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3002 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3004 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3005 CCValAssign &VA = ArgLocs[i];
3006 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3007 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3008 // Arguments stored in registers.
3009 if (VA.isRegLoc()) {
3010 EVT RegVT = VA.getLocVT();
3012 if (VA.needsCustom()) {
3013 // f64 and vector types are split up into multiple registers or
3014 // combinations of registers and stack slots.
3015 if (VA.getLocVT() == MVT::v2f64) {
3016 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3018 VA = ArgLocs[++i]; // skip ahead to next loc
3020 if (VA.isMemLoc()) {
3021 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3022 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3023 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3024 MachinePointerInfo::getFixedStack(FI),
3025 false, false, false, 0);
3027 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3030 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3031 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3032 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3033 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3034 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3036 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3039 const TargetRegisterClass *RC;
3041 if (RegVT == MVT::f32)
3042 RC = &ARM::SPRRegClass;
3043 else if (RegVT == MVT::f64)
3044 RC = &ARM::DPRRegClass;
3045 else if (RegVT == MVT::v2f64)
3046 RC = &ARM::QPRRegClass;
3047 else if (RegVT == MVT::i32)
3048 RC = AFI->isThumb1OnlyFunction() ?
3049 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3050 (const TargetRegisterClass*)&ARM::GPRRegClass;
3052 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3054 // Transform the arguments in physical registers into virtual ones.
3055 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3056 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3059 // If this is an 8 or 16-bit value, it is really passed promoted
3060 // to 32 bits. Insert an assert[sz]ext to capture this, then
3061 // truncate to the right size.
3062 switch (VA.getLocInfo()) {
3063 default: llvm_unreachable("Unknown loc info!");
3064 case CCValAssign::Full: break;
3065 case CCValAssign::BCvt:
3066 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3068 case CCValAssign::SExt:
3069 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3070 DAG.getValueType(VA.getValVT()));
3071 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3073 case CCValAssign::ZExt:
3074 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3075 DAG.getValueType(VA.getValVT()));
3076 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3080 InVals.push_back(ArgValue);
3082 } else { // VA.isRegLoc()
3085 assert(VA.isMemLoc());
3086 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3088 int index = ArgLocs[i].getValNo();
3090 // Some Ins[] entries become multiple ArgLoc[] entries.
3091 // Process them only once.
3092 if (index != lastInsIndex)
3094 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3095 // FIXME: For now, all byval parameter objects are marked mutable.
3096 // This can be changed with more analysis.
3097 // In case of tail call optimization mark all arguments mutable.
3098 // Since they could be overwritten by lowering of arguments in case of
3100 if (Flags.isByVal()) {
3101 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3103 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3104 int FrameIndex = StoreByValRegs(
3105 CCInfo, DAG, dl, Chain, CurOrigArg,
3107 Ins[VA.getValNo()].PartOffset,
3108 VA.getLocMemOffset(),
3109 Flags.getByValSize(),
3110 true /*force mutable frames*/,
3112 TotalArgRegsSaveSize);
3113 ByValStoreOffset += Flags.getByValSize();
3114 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3115 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3116 CCInfo.nextInRegsParam();
3118 unsigned FIOffset = VA.getLocMemOffset();
3119 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3122 // Create load nodes to retrieve arguments from the stack.
3123 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3124 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3125 MachinePointerInfo::getFixedStack(FI),
3126 false, false, false, 0));
3128 lastInsIndex = index;
3135 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3136 CCInfo.getNextStackOffset(),
3137 TotalArgRegsSaveSize);
3139 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3144 /// isFloatingPointZero - Return true if this is +0.0.
3145 static bool isFloatingPointZero(SDValue Op) {
3146 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3147 return CFP->getValueAPF().isPosZero();
3148 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3149 // Maybe this has already been legalized into the constant pool?
3150 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3151 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3152 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3153 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3154 return CFP->getValueAPF().isPosZero();
3160 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3161 /// the given operands.
3163 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3164 SDValue &ARMcc, SelectionDAG &DAG,
3166 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3167 unsigned C = RHSC->getZExtValue();
3168 if (!isLegalICmpImmediate(C)) {
3169 // Constant does not fit, try adjusting it by one?
3174 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3175 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3176 RHS = DAG.getConstant(C-1, MVT::i32);
3181 if (C != 0 && isLegalICmpImmediate(C-1)) {
3182 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3183 RHS = DAG.getConstant(C-1, MVT::i32);
3188 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3189 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3190 RHS = DAG.getConstant(C+1, MVT::i32);
3195 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3196 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3197 RHS = DAG.getConstant(C+1, MVT::i32);
3204 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3205 ARMISD::NodeType CompareType;
3208 CompareType = ARMISD::CMP;
3213 CompareType = ARMISD::CMPZ;
3216 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3217 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3220 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3222 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3225 if (!isFloatingPointZero(RHS))
3226 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3228 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3229 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3232 /// duplicateCmp - Glue values can have only one use, so this function
3233 /// duplicates a comparison node.
3235 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3236 unsigned Opc = Cmp.getOpcode();
3238 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3239 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3241 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3242 Cmp = Cmp.getOperand(0);
3243 Opc = Cmp.getOpcode();
3244 if (Opc == ARMISD::CMPFP)
3245 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3247 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3248 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3250 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3253 std::pair<SDValue, SDValue>
3254 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3255 SDValue &ARMcc) const {
3256 assert(Op.getValueType() == MVT::i32 && "Unsupported value type");
3258 SDValue Value, OverflowCmp;
3259 SDValue LHS = Op.getOperand(0);
3260 SDValue RHS = Op.getOperand(1);
3263 // FIXME: We are currently always generating CMPs because we don't support
3264 // generating CMN through the backend. This is not as good as the natural
3265 // CMP case because it causes a register dependency and cannot be folded
3268 switch (Op.getOpcode()) {
3270 llvm_unreachable("Unknown overflow instruction!");
3272 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3273 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3274 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3277 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3278 Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3279 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3282 ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3283 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3284 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3287 ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3288 Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3289 OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3293 return std::make_pair(Value, OverflowCmp);
3298 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3299 // Let legalize expand this if it isn't a legal type yet.
3300 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3303 SDValue Value, OverflowCmp;
3305 std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3306 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3307 // We use 0 and 1 as false and true values.
3308 SDValue TVal = DAG.getConstant(1, MVT::i32);
3309 SDValue FVal = DAG.getConstant(0, MVT::i32);
3310 EVT VT = Op.getValueType();
3312 SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3313 ARMcc, CCR, OverflowCmp);
3315 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3316 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3320 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3321 SDValue Cond = Op.getOperand(0);
3322 SDValue SelectTrue = Op.getOperand(1);
3323 SDValue SelectFalse = Op.getOperand(2);
3325 unsigned Opc = Cond.getOpcode();
3327 if (Cond.getResNo() == 1 &&
3328 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3329 Opc == ISD::USUBO)) {
3330 if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3333 SDValue Value, OverflowCmp;
3335 std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3336 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3337 EVT VT = Op.getValueType();
3339 return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3340 ARMcc, CCR, OverflowCmp);
3346 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3347 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3349 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3350 const ConstantSDNode *CMOVTrue =
3351 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3352 const ConstantSDNode *CMOVFalse =
3353 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3355 if (CMOVTrue && CMOVFalse) {
3356 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3357 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3361 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3363 False = SelectFalse;
3364 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3369 if (True.getNode() && False.getNode()) {
3370 EVT VT = Op.getValueType();
3371 SDValue ARMcc = Cond.getOperand(2);
3372 SDValue CCR = Cond.getOperand(3);
3373 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3374 assert(True.getValueType() == VT);
3375 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3380 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3381 // undefined bits before doing a full-word comparison with zero.
3382 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3383 DAG.getConstant(1, Cond.getValueType()));
3385 return DAG.getSelectCC(dl, Cond,
3386 DAG.getConstant(0, Cond.getValueType()),
3387 SelectTrue, SelectFalse, ISD::SETNE);
3390 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3391 if (CC == ISD::SETNE)
3393 return ISD::getSetCCInverse(CC, true);
3396 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3397 bool &swpCmpOps, bool &swpVselOps) {
3398 // Start by selecting the GE condition code for opcodes that return true for
3400 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3402 CondCode = ARMCC::GE;
3404 // and GT for opcodes that return false for 'equality'.
3405 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3407 CondCode = ARMCC::GT;
3409 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3410 // to swap the compare operands.
3411 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3415 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3416 // If we have an unordered opcode, we need to swap the operands to the VSEL
3417 // instruction (effectively negating the condition).
3419 // This also has the effect of swapping which one of 'less' or 'greater'
3420 // returns true, so we also swap the compare operands. It also switches
3421 // whether we return true for 'equality', so we compensate by picking the
3422 // opposite condition code to our original choice.
3423 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3424 CC == ISD::SETUGT) {
3425 swpCmpOps = !swpCmpOps;
3426 swpVselOps = !swpVselOps;
3427 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3430 // 'ordered' is 'anything but unordered', so use the VS condition code and
3431 // swap the VSEL operands.
3432 if (CC == ISD::SETO) {
3433 CondCode = ARMCC::VS;
3437 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3438 // code and swap the VSEL operands.
3439 if (CC == ISD::SETUNE) {
3440 CondCode = ARMCC::EQ;
3445 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3446 EVT VT = Op.getValueType();
3447 SDValue LHS = Op.getOperand(0);
3448 SDValue RHS = Op.getOperand(1);
3449 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3450 SDValue TrueVal = Op.getOperand(2);
3451 SDValue FalseVal = Op.getOperand(3);
3454 if (LHS.getValueType() == MVT::i32) {
3455 // Try to generate VSEL on ARMv8.
3456 // The VSEL instruction can't use all the usual ARM condition
3457 // codes: it only has two bits to select the condition code, so it's
3458 // constrained to use only GE, GT, VS and EQ.
3460 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3461 // swap the operands of the previous compare instruction (effectively
3462 // inverting the compare condition, swapping 'less' and 'greater') and
3463 // sometimes need to swap the operands to the VSEL (which inverts the
3464 // condition in the sense of firing whenever the previous condition didn't)
3465 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3466 TrueVal.getValueType() == MVT::f64)) {
3467 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3468 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3469 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3470 CC = getInverseCCForVSEL(CC);
3471 std::swap(TrueVal, FalseVal);
3476 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3477 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3478 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3482 ARMCC::CondCodes CondCode, CondCode2;
3483 FPCCToARMCC(CC, CondCode, CondCode2);
3485 // Try to generate VSEL on ARMv8.
3486 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3487 TrueVal.getValueType() == MVT::f64)) {
3488 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3489 // same operands, as follows:
3490 // c = fcmp [ogt, olt, ugt, ult] a, b
3492 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3493 // handled differently than the original code sequence.
3494 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3496 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3497 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3498 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3499 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3502 bool swpCmpOps = false;
3503 bool swpVselOps = false;
3504 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3506 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3507 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3509 std::swap(LHS, RHS);
3511 std::swap(TrueVal, FalseVal);
3515 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3516 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3517 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3518 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3520 if (CondCode2 != ARMCC::AL) {
3521 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3522 // FIXME: Needs another CMP because flag can have but one use.
3523 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3524 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3525 Result, TrueVal, ARMcc2, CCR, Cmp2);
3530 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3531 /// to morph to an integer compare sequence.
3532 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3533 const ARMSubtarget *Subtarget) {
3534 SDNode *N = Op.getNode();
3535 if (!N->hasOneUse())
3536 // Otherwise it requires moving the value from fp to integer registers.
3538 if (!N->getNumValues())
3540 EVT VT = Op.getValueType();
3541 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3542 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3543 // vmrs are very slow, e.g. cortex-a8.
3546 if (isFloatingPointZero(Op)) {
3550 return ISD::isNormalLoad(N);
3553 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3554 if (isFloatingPointZero(Op))
3555 return DAG.getConstant(0, MVT::i32);
3557 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3558 return DAG.getLoad(MVT::i32, SDLoc(Op),
3559 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3560 Ld->isVolatile(), Ld->isNonTemporal(),
3561 Ld->isInvariant(), Ld->getAlignment());
3563 llvm_unreachable("Unknown VFP cmp argument!");
3566 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3567 SDValue &RetVal1, SDValue &RetVal2) {
3568 if (isFloatingPointZero(Op)) {
3569 RetVal1 = DAG.getConstant(0, MVT::i32);
3570 RetVal2 = DAG.getConstant(0, MVT::i32);
3574 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3575 SDValue Ptr = Ld->getBasePtr();
3576 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3577 Ld->getChain(), Ptr,
3578 Ld->getPointerInfo(),
3579 Ld->isVolatile(), Ld->isNonTemporal(),
3580 Ld->isInvariant(), Ld->getAlignment());
3582 EVT PtrType = Ptr.getValueType();
3583 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3584 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3585 PtrType, Ptr, DAG.getConstant(4, PtrType));
3586 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3587 Ld->getChain(), NewPtr,
3588 Ld->getPointerInfo().getWithOffset(4),
3589 Ld->isVolatile(), Ld->isNonTemporal(),
3590 Ld->isInvariant(), NewAlign);
3594 llvm_unreachable("Unknown VFP cmp argument!");
3597 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3598 /// f32 and even f64 comparisons to integer ones.
3600 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3601 SDValue Chain = Op.getOperand(0);
3602 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3603 SDValue LHS = Op.getOperand(2);
3604 SDValue RHS = Op.getOperand(3);
3605 SDValue Dest = Op.getOperand(4);
3608 bool LHSSeenZero = false;
3609 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3610 bool RHSSeenZero = false;
3611 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3612 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3613 // If unsafe fp math optimization is enabled and there are no other uses of
3614 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3615 // to an integer comparison.
3616 if (CC == ISD::SETOEQ)
3618 else if (CC == ISD::SETUNE)
3621 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3623 if (LHS.getValueType() == MVT::f32) {
3624 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3625 bitcastf32Toi32(LHS, DAG), Mask);
3626 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3627 bitcastf32Toi32(RHS, DAG), Mask);
3628 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3629 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3630 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3631 Chain, Dest, ARMcc, CCR, Cmp);
3636 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3637 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3638 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3639 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3640 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3641 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3642 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3643 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3644 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3650 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3651 SDValue Chain = Op.getOperand(0);
3652 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3653 SDValue LHS = Op.getOperand(2);
3654 SDValue RHS = Op.getOperand(3);
3655 SDValue Dest = Op.getOperand(4);
3658 if (LHS.getValueType() == MVT::i32) {
3660 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3661 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3662 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3663 Chain, Dest, ARMcc, CCR, Cmp);
3666 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3668 if (getTargetMachine().Options.UnsafeFPMath &&
3669 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3670 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3671 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3672 if (Result.getNode())
3676 ARMCC::CondCodes CondCode, CondCode2;
3677 FPCCToARMCC(CC, CondCode, CondCode2);
3679 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3680 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3681 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3682 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3683 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3684 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3685 if (CondCode2 != ARMCC::AL) {
3686 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3687 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3688 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3693 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3694 SDValue Chain = Op.getOperand(0);
3695 SDValue Table = Op.getOperand(1);
3696 SDValue Index = Op.getOperand(2);
3699 EVT PTy = getPointerTy();
3700 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3701 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3702 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3703 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3704 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3705 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3706 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3707 if (Subtarget->isThumb2()) {
3708 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3709 // which does another jump to the destination. This also makes it easier
3710 // to translate it to TBB / TBH later.
3711 // FIXME: This might not work if the function is extremely large.
3712 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3713 Addr, Op.getOperand(2), JTI, UId);
3715 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3716 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3717 MachinePointerInfo::getJumpTable(),
3718 false, false, false, 0);
3719 Chain = Addr.getValue(1);
3720 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3721 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3723 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3724 MachinePointerInfo::getJumpTable(),
3725 false, false, false, 0);
3726 Chain = Addr.getValue(1);
3727 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3731 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3732 EVT VT = Op.getValueType();
3735 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3736 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3738 return DAG.UnrollVectorOp(Op.getNode());
3741 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3742 "Invalid type for custom lowering!");
3743 if (VT != MVT::v4i16)
3744 return DAG.UnrollVectorOp(Op.getNode());
3746 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3747 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3750 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3751 EVT VT = Op.getValueType();
3753 return LowerVectorFP_TO_INT(Op, DAG);
3758 switch (Op.getOpcode()) {
3759 default: llvm_unreachable("Invalid opcode!");
3760 case ISD::FP_TO_SINT:
3761 Opc = ARMISD::FTOSI;
3763 case ISD::FP_TO_UINT:
3764 Opc = ARMISD::FTOUI;
3767 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3768 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3771 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3772 EVT VT = Op.getValueType();
3775 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3776 if (VT.getVectorElementType() == MVT::f32)
3778 return DAG.UnrollVectorOp(Op.getNode());
3781 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3782 "Invalid type for custom lowering!");
3783 if (VT != MVT::v4f32)
3784 return DAG.UnrollVectorOp(Op.getNode());
3788 switch (Op.getOpcode()) {
3789 default: llvm_unreachable("Invalid opcode!");
3790 case ISD::SINT_TO_FP:
3791 CastOpc = ISD::SIGN_EXTEND;
3792 Opc = ISD::SINT_TO_FP;
3794 case ISD::UINT_TO_FP:
3795 CastOpc = ISD::ZERO_EXTEND;
3796 Opc = ISD::UINT_TO_FP;
3800 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3801 return DAG.getNode(Opc, dl, VT, Op);
3804 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3805 EVT VT = Op.getValueType();
3807 return LowerVectorINT_TO_FP(Op, DAG);
3812 switch (Op.getOpcode()) {
3813 default: llvm_unreachable("Invalid opcode!");
3814 case ISD::SINT_TO_FP:
3815 Opc = ARMISD::SITOF;
3817 case ISD::UINT_TO_FP:
3818 Opc = ARMISD::UITOF;
3822 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3823 return DAG.getNode(Opc, dl, VT, Op);
3826 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3827 // Implement fcopysign with a fabs and a conditional fneg.
3828 SDValue Tmp0 = Op.getOperand(0);
3829 SDValue Tmp1 = Op.getOperand(1);
3831 EVT VT = Op.getValueType();
3832 EVT SrcVT = Tmp1.getValueType();
3833 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3834 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3835 bool UseNEON = !InGPR && Subtarget->hasNEON();
3838 // Use VBSL to copy the sign bit.
3839 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3840 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3841 DAG.getTargetConstant(EncodedVal, MVT::i32));
3842 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3844 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3845 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3846 DAG.getConstant(32, MVT::i32));
3847 else /*if (VT == MVT::f32)*/
3848 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3849 if (SrcVT == MVT::f32) {
3850 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3852 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3853 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3854 DAG.getConstant(32, MVT::i32));
3855 } else if (VT == MVT::f32)
3856 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3857 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3858 DAG.getConstant(32, MVT::i32));
3859 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3860 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3862 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3864 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3865 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3866 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3868 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3869 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3870 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3871 if (VT == MVT::f32) {
3872 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3873 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3874 DAG.getConstant(0, MVT::i32));
3876 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3882 // Bitcast operand 1 to i32.
3883 if (SrcVT == MVT::f64)
3884 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3886 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3888 // Or in the signbit with integer operations.
3889 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3890 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3891 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3892 if (VT == MVT::f32) {
3893 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3894 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3895 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3896 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3899 // f64: Or the high part with signbit and then combine two parts.
3900 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3902 SDValue Lo = Tmp0.getValue(0);
3903 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3904 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3905 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3908 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3909 MachineFunction &MF = DAG.getMachineFunction();
3910 MachineFrameInfo *MFI = MF.getFrameInfo();
3911 MFI->setReturnAddressIsTaken(true);
3913 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3916 EVT VT = Op.getValueType();
3918 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3920 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3921 SDValue Offset = DAG.getConstant(4, MVT::i32);
3922 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3923 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3924 MachinePointerInfo(), false, false, false, 0);
3927 // Return LR, which contains the return address. Mark it an implicit live-in.
3928 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3929 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3932 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3933 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3934 MFI->setFrameAddressIsTaken(true);
3936 EVT VT = Op.getValueType();
3937 SDLoc dl(Op); // FIXME probably not meaningful
3938 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3939 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3940 ? ARM::R7 : ARM::R11;
3941 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3943 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3944 MachinePointerInfo(),
3945 false, false, false, 0);
3949 // FIXME? Maybe this could be a TableGen attribute on some registers and
3950 // this table could be generated automatically from RegInfo.
3951 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3953 unsigned Reg = StringSwitch<unsigned>(RegName)
3954 .Case("sp", ARM::SP)
3958 report_fatal_error("Invalid register name global variable");
3961 /// ExpandBITCAST - If the target supports VFP, this function is called to
3962 /// expand a bit convert where either the source or destination type is i64 to
3963 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3964 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3965 /// vectors), since the legalizer won't know what to do with that.
3966 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3967 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3969 SDValue Op = N->getOperand(0);
3971 // This function is only supposed to be called for i64 types, either as the
3972 // source or destination of the bit convert.
3973 EVT SrcVT = Op.getValueType();
3974 EVT DstVT = N->getValueType(0);
3975 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3976 "ExpandBITCAST called for non-i64 type");
3978 // Turn i64->f64 into VMOVDRR.
3979 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3980 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3981 DAG.getConstant(0, MVT::i32));
3982 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3983 DAG.getConstant(1, MVT::i32));
3984 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3985 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3988 // Turn f64->i64 into VMOVRRD.
3989 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3991 if (TLI.isBigEndian() && SrcVT.isVector() &&
3992 SrcVT.getVectorNumElements() > 1)
3993 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3994 DAG.getVTList(MVT::i32, MVT::i32),
3995 DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3997 Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3998 DAG.getVTList(MVT::i32, MVT::i32), Op);
3999 // Merge the pieces into a single i64 value.
4000 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4006 /// getZeroVector - Returns a vector of specified type with all zero elements.
4007 /// Zero vectors are used to represent vector negation and in those cases
4008 /// will be implemented with the NEON VNEG instruction. However, VNEG does
4009 /// not support i64 elements, so sometimes the zero vectors will need to be
4010 /// explicitly constructed. Regardless, use a canonical VMOV to create the
4012 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4013 assert(VT.isVector() && "Expected a vector type");
4014 // The canonical modified immediate encoding of a zero vector is....0!
4015 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4016 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4017 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4018 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4021 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4022 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4023 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4024 SelectionDAG &DAG) const {
4025 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4026 EVT VT = Op.getValueType();
4027 unsigned VTBits = VT.getSizeInBits();
4029 SDValue ShOpLo = Op.getOperand(0);
4030 SDValue ShOpHi = Op.getOperand(1);
4031 SDValue ShAmt = Op.getOperand(2);
4033 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4035 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4037 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4038 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4039 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4040 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4041 DAG.getConstant(VTBits, MVT::i32));
4042 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4043 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4044 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4046 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4047 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4049 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4050 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4053 SDValue Ops[2] = { Lo, Hi };
4054 return DAG.getMergeValues(Ops, dl);
4057 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4058 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4059 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4060 SelectionDAG &DAG) const {
4061 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4062 EVT VT = Op.getValueType();
4063 unsigned VTBits = VT.getSizeInBits();
4065 SDValue ShOpLo = Op.getOperand(0);
4066 SDValue ShOpHi = Op.getOperand(1);
4067 SDValue ShAmt = Op.getOperand(2);
4070 assert(Op.getOpcode() == ISD::SHL_PARTS);
4071 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4072 DAG.getConstant(VTBits, MVT::i32), ShAmt);
4073 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4074 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4075 DAG.getConstant(VTBits, MVT::i32));
4076 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4077 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4079 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4080 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4081 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4083 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4084 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4087 SDValue Ops[2] = { Lo, Hi };
4088 return DAG.getMergeValues(Ops, dl);
4091 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4092 SelectionDAG &DAG) const {
4093 // The rounding mode is in bits 23:22 of the FPSCR.
4094 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4095 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4096 // so that the shift + and get folded into a bitfield extract.
4098 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4099 DAG.getConstant(Intrinsic::arm_get_fpscr,
4101 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4102 DAG.getConstant(1U << 22, MVT::i32));
4103 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4104 DAG.getConstant(22, MVT::i32));
4105 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4106 DAG.getConstant(3, MVT::i32));
4109 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4110 const ARMSubtarget *ST) {
4111 EVT VT = N->getValueType(0);
4114 if (!ST->hasV6T2Ops())
4117 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4118 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4121 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4122 /// for each 16-bit element from operand, repeated. The basic idea is to
4123 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4125 /// Trace for v4i16:
4126 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4127 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4128 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4129 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4130 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4131 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4132 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4133 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4134 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4135 EVT VT = N->getValueType(0);
4138 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4139 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4140 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4141 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4142 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4143 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4146 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4147 /// bit-count for each 16-bit element from the operand. We need slightly
4148 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4149 /// 64/128-bit registers.
4151 /// Trace for v4i16:
4152 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4153 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4154 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4155 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4156 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4157 EVT VT = N->getValueType(0);
4160 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4161 if (VT.is64BitVector()) {
4162 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4163 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4164 DAG.getIntPtrConstant(0));
4166 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4167 BitCounts, DAG.getIntPtrConstant(0));
4168 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4172 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4173 /// bit-count for each 32-bit element from the operand. The idea here is
4174 /// to split the vector into 16-bit elements, leverage the 16-bit count
4175 /// routine, and then combine the results.
4177 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4178 /// input = [v0 v1 ] (vi: 32-bit elements)
4179 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4180 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4181 /// vrev: N0 = [k1 k0 k3 k2 ]
4183 /// N1 =+[k1 k0 k3 k2 ]
4185 /// N2 =+[k1 k3 k0 k2 ]
4187 /// Extended =+[k1 k3 k0 k2 ]
4189 /// Extracted=+[k1 k3 ]
4191 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4192 EVT VT = N->getValueType(0);
4195 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4197 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4198 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4199 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4200 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4201 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4203 if (VT.is64BitVector()) {
4204 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4205 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4206 DAG.getIntPtrConstant(0));
4208 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4209 DAG.getIntPtrConstant(0));
4210 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4214 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4215 const ARMSubtarget *ST) {
4216 EVT VT = N->getValueType(0);
4218 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4219 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4220 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4221 "Unexpected type for custom ctpop lowering");
4223 if (VT.getVectorElementType() == MVT::i32)
4224 return lowerCTPOP32BitElements(N, DAG);
4226 return lowerCTPOP16BitElements(N, DAG);
4229 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4230 const ARMSubtarget *ST) {
4231 EVT VT = N->getValueType(0);
4237 // Lower vector shifts on NEON to use VSHL.
4238 assert(ST->hasNEON() && "unexpected vector shift");
4240 // Left shifts translate directly to the vshiftu intrinsic.
4241 if (N->getOpcode() == ISD::SHL)
4242 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4243 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4244 N->getOperand(0), N->getOperand(1));
4246 assert((N->getOpcode() == ISD::SRA ||
4247 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4249 // NEON uses the same intrinsics for both left and right shifts. For
4250 // right shifts, the shift amounts are negative, so negate the vector of
4252 EVT ShiftVT = N->getOperand(1).getValueType();
4253 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4254 getZeroVector(ShiftVT, DAG, dl),
4256 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4257 Intrinsic::arm_neon_vshifts :
4258 Intrinsic::arm_neon_vshiftu);
4259 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4260 DAG.getConstant(vshiftInt, MVT::i32),
4261 N->getOperand(0), NegatedCount);
4264 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4265 const ARMSubtarget *ST) {
4266 EVT VT = N->getValueType(0);
4269 // We can get here for a node like i32 = ISD::SHL i32, i64
4273 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4274 "Unknown shift to lower!");
4276 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4277 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4278 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4281 // If we are in thumb mode, we don't have RRX.
4282 if (ST->isThumb1Only()) return SDValue();
4284 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4285 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4286 DAG.getConstant(0, MVT::i32));
4287 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4288 DAG.getConstant(1, MVT::i32));
4290 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4291 // captures the result into a carry flag.
4292 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4293 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4295 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4296 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4298 // Merge the pieces into a single i64 value.
4299 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4302 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4303 SDValue TmpOp0, TmpOp1;
4304 bool Invert = false;
4308 SDValue Op0 = Op.getOperand(0);
4309 SDValue Op1 = Op.getOperand(1);
4310 SDValue CC = Op.getOperand(2);
4311 EVT VT = Op.getValueType();
4312 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4315 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4316 switch (SetCCOpcode) {
4317 default: llvm_unreachable("Illegal FP comparison");
4319 case ISD::SETNE: Invert = true; // Fallthrough
4321 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4323 case ISD::SETLT: Swap = true; // Fallthrough
4325 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4327 case ISD::SETLE: Swap = true; // Fallthrough
4329 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4330 case ISD::SETUGE: Swap = true; // Fallthrough
4331 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4332 case ISD::SETUGT: Swap = true; // Fallthrough
4333 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4334 case ISD::SETUEQ: Invert = true; // Fallthrough
4336 // Expand this to (OLT | OGT).
4340 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4341 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4343 case ISD::SETUO: Invert = true; // Fallthrough
4345 // Expand this to (OLT | OGE).
4349 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4350 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4354 // Integer comparisons.
4355 switch (SetCCOpcode) {
4356 default: llvm_unreachable("Illegal integer comparison");
4357 case ISD::SETNE: Invert = true;
4358 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4359 case ISD::SETLT: Swap = true;
4360 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4361 case ISD::SETLE: Swap = true;
4362 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4363 case ISD::SETULT: Swap = true;
4364 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4365 case ISD::SETULE: Swap = true;
4366 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4369 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4370 if (Opc == ARMISD::VCEQ) {
4373 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4375 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4378 // Ignore bitconvert.
4379 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4380 AndOp = AndOp.getOperand(0);
4382 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4384 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4385 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4392 std::swap(Op0, Op1);
4394 // If one of the operands is a constant vector zero, attempt to fold the
4395 // comparison to a specialized compare-against-zero form.
4397 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4399 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4400 if (Opc == ARMISD::VCGE)
4401 Opc = ARMISD::VCLEZ;
4402 else if (Opc == ARMISD::VCGT)
4403 Opc = ARMISD::VCLTZ;
4408 if (SingleOp.getNode()) {
4411 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4413 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4415 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4417 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4419 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4421 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4424 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4428 Result = DAG.getNOT(dl, Result, VT);
4433 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4434 /// valid vector constant for a NEON instruction with a "modified immediate"
4435 /// operand (e.g., VMOV). If so, return the encoded value.
4436 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4437 unsigned SplatBitSize, SelectionDAG &DAG,
4438 EVT &VT, bool is128Bits, NEONModImmType type) {
4439 unsigned OpCmode, Imm;
4441 // SplatBitSize is set to the smallest size that splats the vector, so a
4442 // zero vector will always have SplatBitSize == 8. However, NEON modified
4443 // immediate instructions others than VMOV do not support the 8-bit encoding
4444 // of a zero vector, and the default encoding of zero is supposed to be the
4449 switch (SplatBitSize) {
4451 if (type != VMOVModImm)
4453 // Any 1-byte value is OK. Op=0, Cmode=1110.
4454 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4457 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4461 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4462 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4463 if ((SplatBits & ~0xff) == 0) {
4464 // Value = 0x00nn: Op=x, Cmode=100x.
4469 if ((SplatBits & ~0xff00) == 0) {
4470 // Value = 0xnn00: Op=x, Cmode=101x.
4472 Imm = SplatBits >> 8;
4478 // NEON's 32-bit VMOV supports splat values where:
4479 // * only one byte is nonzero, or
4480 // * the least significant byte is 0xff and the second byte is nonzero, or
4481 // * the least significant 2 bytes are 0xff and the third is nonzero.
4482 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4483 if ((SplatBits & ~0xff) == 0) {
4484 // Value = 0x000000nn: Op=x, Cmode=000x.
4489 if ((SplatBits & ~0xff00) == 0) {
4490 // Value = 0x0000nn00: Op=x, Cmode=001x.
4492 Imm = SplatBits >> 8;
4495 if ((SplatBits & ~0xff0000) == 0) {
4496 // Value = 0x00nn0000: Op=x, Cmode=010x.
4498 Imm = SplatBits >> 16;
4501 if ((SplatBits & ~0xff000000) == 0) {
4502 // Value = 0xnn000000: Op=x, Cmode=011x.
4504 Imm = SplatBits >> 24;
4508 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4509 if (type == OtherModImm) return SDValue();
4511 if ((SplatBits & ~0xffff) == 0 &&
4512 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4513 // Value = 0x0000nnff: Op=x, Cmode=1100.
4515 Imm = SplatBits >> 8;
4519 if ((SplatBits & ~0xffffff) == 0 &&
4520 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4521 // Value = 0x00nnffff: Op=x, Cmode=1101.
4523 Imm = SplatBits >> 16;
4527 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4528 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4529 // VMOV.I32. A (very) minor optimization would be to replicate the value
4530 // and fall through here to test for a valid 64-bit splat. But, then the
4531 // caller would also need to check and handle the change in size.
4535 if (type != VMOVModImm)
4537 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4538 uint64_t BitMask = 0xff;
4540 unsigned ImmMask = 1;
4542 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4543 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4546 } else if ((SplatBits & BitMask) != 0) {
4552 // Op=1, Cmode=1110.
4554 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4559 llvm_unreachable("unexpected size for isNEONModifiedImm");
4562 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4563 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4566 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4567 const ARMSubtarget *ST) const {
4571 bool IsDouble = Op.getValueType() == MVT::f64;
4572 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4574 // Try splatting with a VMOV.f32...
4575 APFloat FPVal = CFP->getValueAPF();
4576 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4579 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4580 // We have code in place to select a valid ConstantFP already, no need to
4585 // It's a float and we are trying to use NEON operations where
4586 // possible. Lower it to a splat followed by an extract.
4588 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4589 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4591 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4592 DAG.getConstant(0, MVT::i32));
4595 // The rest of our options are NEON only, make sure that's allowed before
4597 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4601 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4603 // It wouldn't really be worth bothering for doubles except for one very
4604 // important value, which does happen to match: 0.0. So make sure we don't do
4606 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4609 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4610 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4612 if (NewVal != SDValue()) {
4614 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4617 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4619 // It's a float: cast and extract a vector element.
4620 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4622 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4623 DAG.getConstant(0, MVT::i32));
4626 // Finally, try a VMVN.i32
4627 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4629 if (NewVal != SDValue()) {
4631 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4634 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4636 // It's a float: cast and extract a vector element.
4637 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4639 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4640 DAG.getConstant(0, MVT::i32));
4646 // check if an VEXT instruction can handle the shuffle mask when the
4647 // vector sources of the shuffle are the same.
4648 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4649 unsigned NumElts = VT.getVectorNumElements();
4651 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4657 // If this is a VEXT shuffle, the immediate value is the index of the first
4658 // element. The other shuffle indices must be the successive elements after
4660 unsigned ExpectedElt = Imm;
4661 for (unsigned i = 1; i < NumElts; ++i) {
4662 // Increment the expected index. If it wraps around, just follow it
4663 // back to index zero and keep going.
4665 if (ExpectedElt == NumElts)
4668 if (M[i] < 0) continue; // ignore UNDEF indices
4669 if (ExpectedElt != static_cast<unsigned>(M[i]))
4677 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4678 bool &ReverseVEXT, unsigned &Imm) {
4679 unsigned NumElts = VT.getVectorNumElements();
4680 ReverseVEXT = false;
4682 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4688 // If this is a VEXT shuffle, the immediate value is the index of the first
4689 // element. The other shuffle indices must be the successive elements after
4691 unsigned ExpectedElt = Imm;
4692 for (unsigned i = 1; i < NumElts; ++i) {
4693 // Increment the expected index. If it wraps around, it may still be
4694 // a VEXT but the source vectors must be swapped.
4696 if (ExpectedElt == NumElts * 2) {
4701 if (M[i] < 0) continue; // ignore UNDEF indices
4702 if (ExpectedElt != static_cast<unsigned>(M[i]))
4706 // Adjust the index value if the source operands will be swapped.
4713 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4714 /// instruction with the specified blocksize. (The order of the elements
4715 /// within each block of the vector is reversed.)
4716 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4717 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4718 "Only possible block sizes for VREV are: 16, 32, 64");
4720 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4724 unsigned NumElts = VT.getVectorNumElements();
4725 unsigned BlockElts = M[0] + 1;
4726 // If the first shuffle index is UNDEF, be optimistic.
4728 BlockElts = BlockSize / EltSz;
4730 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4733 for (unsigned i = 0; i < NumElts; ++i) {
4734 if (M[i] < 0) continue; // ignore UNDEF indices
4735 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4742 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4743 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4744 // range, then 0 is placed into the resulting vector. So pretty much any mask
4745 // of 8 elements can work here.
4746 return VT == MVT::v8i8 && M.size() == 8;
4749 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4750 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4754 unsigned NumElts = VT.getVectorNumElements();
4755 WhichResult = (M[0] == 0 ? 0 : 1);
4756 for (unsigned i = 0; i < NumElts; i += 2) {
4757 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4758 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4764 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4765 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4766 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4767 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4768 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4772 unsigned NumElts = VT.getVectorNumElements();
4773 WhichResult = (M[0] == 0 ? 0 : 1);
4774 for (unsigned i = 0; i < NumElts; i += 2) {
4775 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4776 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4782 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4783 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4787 unsigned NumElts = VT.getVectorNumElements();
4788 WhichResult = (M[0] == 0 ? 0 : 1);
4789 for (unsigned i = 0; i != NumElts; ++i) {
4790 if (M[i] < 0) continue; // ignore UNDEF indices
4791 if ((unsigned) M[i] != 2 * i + WhichResult)
4795 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4796 if (VT.is64BitVector() && EltSz == 32)
4802 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4803 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4804 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4805 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4806 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4810 unsigned Half = VT.getVectorNumElements() / 2;
4811 WhichResult = (M[0] == 0 ? 0 : 1);
4812 for (unsigned j = 0; j != 2; ++j) {
4813 unsigned Idx = WhichResult;
4814 for (unsigned i = 0; i != Half; ++i) {
4815 int MIdx = M[i + j * Half];
4816 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4822 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4823 if (VT.is64BitVector() && EltSz == 32)
4829 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4830 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4834 unsigned NumElts = VT.getVectorNumElements();
4835 WhichResult = (M[0] == 0 ? 0 : 1);
4836 unsigned Idx = WhichResult * NumElts / 2;
4837 for (unsigned i = 0; i != NumElts; i += 2) {
4838 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4839 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4844 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4845 if (VT.is64BitVector() && EltSz == 32)
4851 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4852 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4853 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4854 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4855 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4859 unsigned NumElts = VT.getVectorNumElements();
4860 WhichResult = (M[0] == 0 ? 0 : 1);
4861 unsigned Idx = WhichResult * NumElts / 2;
4862 for (unsigned i = 0; i != NumElts; i += 2) {
4863 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4864 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4869 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4870 if (VT.is64BitVector() && EltSz == 32)
4876 /// \return true if this is a reverse operation on an vector.
4877 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4878 unsigned NumElts = VT.getVectorNumElements();
4879 // Make sure the mask has the right size.
4880 if (NumElts != M.size())
4883 // Look for <15, ..., 3, -1, 1, 0>.
4884 for (unsigned i = 0; i != NumElts; ++i)
4885 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4891 // If N is an integer constant that can be moved into a register in one
4892 // instruction, return an SDValue of such a constant (will become a MOV
4893 // instruction). Otherwise return null.
4894 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4895 const ARMSubtarget *ST, SDLoc dl) {
4897 if (!isa<ConstantSDNode>(N))
4899 Val = cast<ConstantSDNode>(N)->getZExtValue();
4901 if (ST->isThumb1Only()) {
4902 if (Val <= 255 || ~Val <= 255)
4903 return DAG.getConstant(Val, MVT::i32);
4905 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4906 return DAG.getConstant(Val, MVT::i32);
4911 // If this is a case we can't handle, return null and let the default
4912 // expansion code take care of it.
4913 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4914 const ARMSubtarget *ST) const {
4915 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4917 EVT VT = Op.getValueType();
4919 APInt SplatBits, SplatUndef;
4920 unsigned SplatBitSize;
4922 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4923 if (SplatBitSize <= 64) {
4924 // Check if an immediate VMOV works.
4926 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4927 SplatUndef.getZExtValue(), SplatBitSize,
4928 DAG, VmovVT, VT.is128BitVector(),
4930 if (Val.getNode()) {
4931 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4932 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4935 // Try an immediate VMVN.
4936 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4937 Val = isNEONModifiedImm(NegatedImm,
4938 SplatUndef.getZExtValue(), SplatBitSize,
4939 DAG, VmovVT, VT.is128BitVector(),
4941 if (Val.getNode()) {
4942 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4943 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4946 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4947 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4948 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4950 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4951 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4957 // Scan through the operands to see if only one value is used.
4959 // As an optimisation, even if more than one value is used it may be more
4960 // profitable to splat with one value then change some lanes.
4962 // Heuristically we decide to do this if the vector has a "dominant" value,
4963 // defined as splatted to more than half of the lanes.
4964 unsigned NumElts = VT.getVectorNumElements();
4965 bool isOnlyLowElement = true;
4966 bool usesOnlyOneValue = true;
4967 bool hasDominantValue = false;
4968 bool isConstant = true;
4970 // Map of the number of times a particular SDValue appears in the
4972 DenseMap<SDValue, unsigned> ValueCounts;
4974 for (unsigned i = 0; i < NumElts; ++i) {
4975 SDValue V = Op.getOperand(i);
4976 if (V.getOpcode() == ISD::UNDEF)
4979 isOnlyLowElement = false;
4980 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4983 ValueCounts.insert(std::make_pair(V, 0));
4984 unsigned &Count = ValueCounts[V];
4986 // Is this value dominant? (takes up more than half of the lanes)
4987 if (++Count > (NumElts / 2)) {
4988 hasDominantValue = true;
4992 if (ValueCounts.size() != 1)
4993 usesOnlyOneValue = false;
4994 if (!Value.getNode() && ValueCounts.size() > 0)
4995 Value = ValueCounts.begin()->first;
4997 if (ValueCounts.size() == 0)
4998 return DAG.getUNDEF(VT);
5000 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5001 // Keep going if we are hitting this case.
5002 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5003 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5005 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5007 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
5008 // i32 and try again.
5009 if (hasDominantValue && EltSize <= 32) {
5013 // If we are VDUPing a value that comes directly from a vector, that will
5014 // cause an unnecessary move to and from a GPR, where instead we could
5015 // just use VDUPLANE. We can only do this if the lane being extracted
5016 // is at a constant index, as the VDUP from lane instructions only have
5017 // constant-index forms.
5018 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5019 isa<ConstantSDNode>(Value->getOperand(1))) {
5020 // We need to create a new undef vector to use for the VDUPLANE if the
5021 // size of the vector from which we get the value is different than the
5022 // size of the vector that we need to create. We will insert the element
5023 // such that the register coalescer will remove unnecessary copies.
5024 if (VT != Value->getOperand(0).getValueType()) {
5025 ConstantSDNode *constIndex;
5026 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5027 assert(constIndex && "The index is not a constant!");
5028 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5029 VT.getVectorNumElements();
5030 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5031 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5032 Value, DAG.getConstant(index, MVT::i32)),
5033 DAG.getConstant(index, MVT::i32));
5035 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5036 Value->getOperand(0), Value->getOperand(1));
5038 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5040 if (!usesOnlyOneValue) {
5041 // The dominant value was splatted as 'N', but we now have to insert
5042 // all differing elements.
5043 for (unsigned I = 0; I < NumElts; ++I) {
5044 if (Op.getOperand(I) == Value)
5046 SmallVector<SDValue, 3> Ops;
5048 Ops.push_back(Op.getOperand(I));
5049 Ops.push_back(DAG.getConstant(I, MVT::i32));
5050 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5055 if (VT.getVectorElementType().isFloatingPoint()) {
5056 SmallVector<SDValue, 8> Ops;
5057 for (unsigned i = 0; i < NumElts; ++i)
5058 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5060 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5061 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5062 Val = LowerBUILD_VECTOR(Val, DAG, ST);
5064 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5066 if (usesOnlyOneValue) {
5067 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5068 if (isConstant && Val.getNode())
5069 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5073 // If all elements are constants and the case above didn't get hit, fall back
5074 // to the default expansion, which will generate a load from the constant
5079 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5081 SDValue shuffle = ReconstructShuffle(Op, DAG);
5082 if (shuffle != SDValue())
5086 // Vectors with 32- or 64-bit elements can be built by directly assigning
5087 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
5088 // will be legalized.
5089 if (EltSize >= 32) {
5090 // Do the expansion with floating-point types, since that is what the VFP
5091 // registers are defined to use, and since i64 is not legal.
5092 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5093 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5094 SmallVector<SDValue, 8> Ops;
5095 for (unsigned i = 0; i < NumElts; ++i)
5096 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5097 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5098 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5101 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5102 // know the default expansion would otherwise fall back on something even
5103 // worse. For a vector with one or two non-undef values, that's
5104 // scalar_to_vector for the elements followed by a shuffle (provided the
5105 // shuffle is valid for the target) and materialization element by element
5106 // on the stack followed by a load for everything else.
5107 if (!isConstant && !usesOnlyOneValue) {
5108 SDValue Vec = DAG.getUNDEF(VT);
5109 for (unsigned i = 0 ; i < NumElts; ++i) {
5110 SDValue V = Op.getOperand(i);
5111 if (V.getOpcode() == ISD::UNDEF)
5113 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5114 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5122 // Gather data to see if the operation can be modelled as a
5123 // shuffle in combination with VEXTs.
5124 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5125 SelectionDAG &DAG) const {
5127 EVT VT = Op.getValueType();
5128 unsigned NumElts = VT.getVectorNumElements();
5130 SmallVector<SDValue, 2> SourceVecs;
5131 SmallVector<unsigned, 2> MinElts;
5132 SmallVector<unsigned, 2> MaxElts;
5134 for (unsigned i = 0; i < NumElts; ++i) {
5135 SDValue V = Op.getOperand(i);
5136 if (V.getOpcode() == ISD::UNDEF)
5138 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5139 // A shuffle can only come from building a vector from various
5140 // elements of other vectors.
5142 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5143 VT.getVectorElementType()) {
5144 // This code doesn't know how to handle shuffles where the vector
5145 // element types do not match (this happens because type legalization
5146 // promotes the return type of EXTRACT_VECTOR_ELT).
5147 // FIXME: It might be appropriate to extend this code to handle
5148 // mismatched types.
5152 // Record this extraction against the appropriate vector if possible...
5153 SDValue SourceVec = V.getOperand(0);
5154 // If the element number isn't a constant, we can't effectively
5155 // analyze what's going on.
5156 if (!isa<ConstantSDNode>(V.getOperand(1)))
5158 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5159 bool FoundSource = false;
5160 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5161 if (SourceVecs[j] == SourceVec) {
5162 if (MinElts[j] > EltNo)
5164 if (MaxElts[j] < EltNo)
5171 // Or record a new source if not...
5173 SourceVecs.push_back(SourceVec);
5174 MinElts.push_back(EltNo);
5175 MaxElts.push_back(EltNo);
5179 // Currently only do something sane when at most two source vectors
5181 if (SourceVecs.size() > 2)
5184 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5185 int VEXTOffsets[2] = {0, 0};
5187 // This loop extracts the usage patterns of the source vectors
5188 // and prepares appropriate SDValues for a shuffle if possible.
5189 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5190 if (SourceVecs[i].getValueType() == VT) {
5191 // No VEXT necessary
5192 ShuffleSrcs[i] = SourceVecs[i];
5195 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5196 // It probably isn't worth padding out a smaller vector just to
5197 // break it down again in a shuffle.
5201 // Since only 64-bit and 128-bit vectors are legal on ARM and
5202 // we've eliminated the other cases...
5203 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5204 "unexpected vector sizes in ReconstructShuffle");
5206 if (MaxElts[i] - MinElts[i] >= NumElts) {
5207 // Span too large for a VEXT to cope
5211 if (MinElts[i] >= NumElts) {
5212 // The extraction can just take the second half
5213 VEXTOffsets[i] = NumElts;
5214 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5216 DAG.getIntPtrConstant(NumElts));
5217 } else if (MaxElts[i] < NumElts) {
5218 // The extraction can just take the first half
5220 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5222 DAG.getIntPtrConstant(0));
5224 // An actual VEXT is needed
5225 VEXTOffsets[i] = MinElts[i];
5226 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5228 DAG.getIntPtrConstant(0));
5229 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5231 DAG.getIntPtrConstant(NumElts));
5232 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5233 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5237 SmallVector<int, 8> Mask;
5239 for (unsigned i = 0; i < NumElts; ++i) {
5240 SDValue Entry = Op.getOperand(i);
5241 if (Entry.getOpcode() == ISD::UNDEF) {
5246 SDValue ExtractVec = Entry.getOperand(0);
5247 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5248 .getOperand(1))->getSExtValue();
5249 if (ExtractVec == SourceVecs[0]) {
5250 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5252 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5256 // Final check before we try to produce nonsense...
5257 if (isShuffleMaskLegal(Mask, VT))
5258 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5264 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5265 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5266 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5267 /// are assumed to be legal.
5269 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5271 if (VT.getVectorNumElements() == 4 &&
5272 (VT.is128BitVector() || VT.is64BitVector())) {
5273 unsigned PFIndexes[4];
5274 for (unsigned i = 0; i != 4; ++i) {
5278 PFIndexes[i] = M[i];
5281 // Compute the index in the perfect shuffle table.
5282 unsigned PFTableIndex =
5283 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5284 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5285 unsigned Cost = (PFEntry >> 30);
5292 unsigned Imm, WhichResult;
5294 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5295 return (EltSize >= 32 ||
5296 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5297 isVREVMask(M, VT, 64) ||
5298 isVREVMask(M, VT, 32) ||
5299 isVREVMask(M, VT, 16) ||
5300 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5301 isVTBLMask(M, VT) ||
5302 isVTRNMask(M, VT, WhichResult) ||
5303 isVUZPMask(M, VT, WhichResult) ||
5304 isVZIPMask(M, VT, WhichResult) ||
5305 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5306 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5307 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5308 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5311 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5312 /// the specified operations to build the shuffle.
5313 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5314 SDValue RHS, SelectionDAG &DAG,
5316 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5317 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5318 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5321 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5330 OP_VUZPL, // VUZP, left result
5331 OP_VUZPR, // VUZP, right result
5332 OP_VZIPL, // VZIP, left result
5333 OP_VZIPR, // VZIP, right result
5334 OP_VTRNL, // VTRN, left result
5335 OP_VTRNR // VTRN, right result
5338 if (OpNum == OP_COPY) {
5339 if (LHSID == (1*9+2)*9+3) return LHS;
5340 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5344 SDValue OpLHS, OpRHS;
5345 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5346 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5347 EVT VT = OpLHS.getValueType();
5350 default: llvm_unreachable("Unknown shuffle opcode!");
5352 // VREV divides the vector in half and swaps within the half.
5353 if (VT.getVectorElementType() == MVT::i32 ||
5354 VT.getVectorElementType() == MVT::f32)
5355 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5356 // vrev <4 x i16> -> VREV32
5357 if (VT.getVectorElementType() == MVT::i16)
5358 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5359 // vrev <4 x i8> -> VREV16
5360 assert(VT.getVectorElementType() == MVT::i8);
5361 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5366 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5367 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5371 return DAG.getNode(ARMISD::VEXT, dl, VT,
5373 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5376 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5377 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5380 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5381 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5384 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5385 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5389 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5390 ArrayRef<int> ShuffleMask,
5391 SelectionDAG &DAG) {
5392 // Check to see if we can use the VTBL instruction.
5393 SDValue V1 = Op.getOperand(0);
5394 SDValue V2 = Op.getOperand(1);
5397 SmallVector<SDValue, 8> VTBLMask;
5398 for (ArrayRef<int>::iterator
5399 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5400 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5402 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5403 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5404 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5406 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5407 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5410 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5411 SelectionDAG &DAG) {
5413 SDValue OpLHS = Op.getOperand(0);
5414 EVT VT = OpLHS.getValueType();
5416 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5417 "Expect an v8i16/v16i8 type");
5418 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5419 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5420 // extract the first 8 bytes into the top double word and the last 8 bytes
5421 // into the bottom double word. The v8i16 case is similar.
5422 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5423 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5424 DAG.getConstant(ExtractNum, MVT::i32));
5427 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5428 SDValue V1 = Op.getOperand(0);
5429 SDValue V2 = Op.getOperand(1);
5431 EVT VT = Op.getValueType();
5432 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5434 // Convert shuffles that are directly supported on NEON to target-specific
5435 // DAG nodes, instead of keeping them as shuffles and matching them again
5436 // during code selection. This is more efficient and avoids the possibility
5437 // of inconsistencies between legalization and selection.
5438 // FIXME: floating-point vectors should be canonicalized to integer vectors
5439 // of the same time so that they get CSEd properly.
5440 ArrayRef<int> ShuffleMask = SVN->getMask();
5442 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5443 if (EltSize <= 32) {
5444 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5445 int Lane = SVN->getSplatIndex();
5446 // If this is undef splat, generate it via "just" vdup, if possible.
5447 if (Lane == -1) Lane = 0;
5449 // Test if V1 is a SCALAR_TO_VECTOR.
5450 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5451 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5453 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5454 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5456 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5457 !isa<ConstantSDNode>(V1.getOperand(0))) {
5458 bool IsScalarToVector = true;
5459 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5460 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5461 IsScalarToVector = false;
5464 if (IsScalarToVector)
5465 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5467 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5468 DAG.getConstant(Lane, MVT::i32));
5473 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5476 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5477 DAG.getConstant(Imm, MVT::i32));
5480 if (isVREVMask(ShuffleMask, VT, 64))
5481 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5482 if (isVREVMask(ShuffleMask, VT, 32))
5483 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5484 if (isVREVMask(ShuffleMask, VT, 16))
5485 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5487 if (V2->getOpcode() == ISD::UNDEF &&
5488 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5489 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5490 DAG.getConstant(Imm, MVT::i32));
5493 // Check for Neon shuffles that modify both input vectors in place.
5494 // If both results are used, i.e., if there are two shuffles with the same
5495 // source operands and with masks corresponding to both results of one of
5496 // these operations, DAG memoization will ensure that a single node is
5497 // used for both shuffles.
5498 unsigned WhichResult;
5499 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5500 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5501 V1, V2).getValue(WhichResult);
5502 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5503 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5504 V1, V2).getValue(WhichResult);
5505 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5506 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5507 V1, V2).getValue(WhichResult);
5509 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5510 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5511 V1, V1).getValue(WhichResult);
5512 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5513 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5514 V1, V1).getValue(WhichResult);
5515 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5516 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5517 V1, V1).getValue(WhichResult);
5520 // If the shuffle is not directly supported and it has 4 elements, use
5521 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5522 unsigned NumElts = VT.getVectorNumElements();
5524 unsigned PFIndexes[4];
5525 for (unsigned i = 0; i != 4; ++i) {
5526 if (ShuffleMask[i] < 0)
5529 PFIndexes[i] = ShuffleMask[i];
5532 // Compute the index in the perfect shuffle table.
5533 unsigned PFTableIndex =
5534 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5535 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5536 unsigned Cost = (PFEntry >> 30);
5539 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5542 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5543 if (EltSize >= 32) {
5544 // Do the expansion with floating-point types, since that is what the VFP
5545 // registers are defined to use, and since i64 is not legal.
5546 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5547 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5548 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5549 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5550 SmallVector<SDValue, 8> Ops;
5551 for (unsigned i = 0; i < NumElts; ++i) {
5552 if (ShuffleMask[i] < 0)
5553 Ops.push_back(DAG.getUNDEF(EltVT));
5555 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5556 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5557 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5560 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5561 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5564 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5565 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5567 if (VT == MVT::v8i8) {
5568 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5569 if (NewOp.getNode())
5576 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5577 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5578 SDValue Lane = Op.getOperand(2);
5579 if (!isa<ConstantSDNode>(Lane))
5585 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5586 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5587 SDValue Lane = Op.getOperand(1);
5588 if (!isa<ConstantSDNode>(Lane))
5591 SDValue Vec = Op.getOperand(0);
5592 if (Op.getValueType() == MVT::i32 &&
5593 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5595 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5601 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5602 // The only time a CONCAT_VECTORS operation can have legal types is when
5603 // two 64-bit vectors are concatenated to a 128-bit vector.
5604 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5605 "unexpected CONCAT_VECTORS");
5607 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5608 SDValue Op0 = Op.getOperand(0);
5609 SDValue Op1 = Op.getOperand(1);
5610 if (Op0.getOpcode() != ISD::UNDEF)
5611 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5612 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5613 DAG.getIntPtrConstant(0));
5614 if (Op1.getOpcode() != ISD::UNDEF)
5615 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5616 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5617 DAG.getIntPtrConstant(1));
5618 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5621 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5622 /// element has been zero/sign-extended, depending on the isSigned parameter,
5623 /// from an integer type half its size.
5624 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5626 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5627 EVT VT = N->getValueType(0);
5628 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5629 SDNode *BVN = N->getOperand(0).getNode();
5630 if (BVN->getValueType(0) != MVT::v4i32 ||
5631 BVN->getOpcode() != ISD::BUILD_VECTOR)
5633 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5634 unsigned HiElt = 1 - LoElt;
5635 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5636 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5637 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5638 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5639 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5642 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5643 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5646 if (Hi0->isNullValue() && Hi1->isNullValue())
5652 if (N->getOpcode() != ISD::BUILD_VECTOR)
5655 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5656 SDNode *Elt = N->getOperand(i).getNode();
5657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5658 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5659 unsigned HalfSize = EltSize / 2;
5661 if (!isIntN(HalfSize, C->getSExtValue()))
5664 if (!isUIntN(HalfSize, C->getZExtValue()))
5675 /// isSignExtended - Check if a node is a vector value that is sign-extended
5676 /// or a constant BUILD_VECTOR with sign-extended elements.
5677 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5678 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5680 if (isExtendedBUILD_VECTOR(N, DAG, true))
5685 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5686 /// or a constant BUILD_VECTOR with zero-extended elements.
5687 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5688 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5690 if (isExtendedBUILD_VECTOR(N, DAG, false))
5695 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5696 if (OrigVT.getSizeInBits() >= 64)
5699 assert(OrigVT.isSimple() && "Expecting a simple value type");
5701 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5702 switch (OrigSimpleTy) {
5703 default: llvm_unreachable("Unexpected Vector Type");
5712 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5713 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5714 /// We insert the required extension here to get the vector to fill a D register.
5715 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5718 unsigned ExtOpcode) {
5719 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5720 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5721 // 64-bits we need to insert a new extension so that it will be 64-bits.
5722 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5723 if (OrigTy.getSizeInBits() >= 64)
5726 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5727 EVT NewVT = getExtensionTo64Bits(OrigTy);
5729 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5732 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5733 /// does not do any sign/zero extension. If the original vector is less
5734 /// than 64 bits, an appropriate extension will be added after the load to
5735 /// reach a total size of 64 bits. We have to add the extension separately
5736 /// because ARM does not have a sign/zero extending load for vectors.
5737 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5738 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5740 // The load already has the right type.
5741 if (ExtendedTy == LD->getMemoryVT())
5742 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5743 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5744 LD->isNonTemporal(), LD->isInvariant(),
5745 LD->getAlignment());
5747 // We need to create a zextload/sextload. We cannot just create a load
5748 // followed by a zext/zext node because LowerMUL is also run during normal
5749 // operation legalization where we can't create illegal types.
5750 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5751 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5752 LD->getMemoryVT(), LD->isVolatile(),
5753 LD->isNonTemporal(), LD->getAlignment());
5756 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5757 /// extending load, or BUILD_VECTOR with extended elements, return the
5758 /// unextended value. The unextended vector should be 64 bits so that it can
5759 /// be used as an operand to a VMULL instruction. If the original vector size
5760 /// before extension is less than 64 bits we add a an extension to resize
5761 /// the vector to 64 bits.
5762 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5763 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5764 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5765 N->getOperand(0)->getValueType(0),
5769 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5770 return SkipLoadExtensionForVMULL(LD, DAG);
5772 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5773 // have been legalized as a BITCAST from v4i32.
5774 if (N->getOpcode() == ISD::BITCAST) {
5775 SDNode *BVN = N->getOperand(0).getNode();
5776 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5777 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5778 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5779 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5780 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5782 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5783 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5784 EVT VT = N->getValueType(0);
5785 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5786 unsigned NumElts = VT.getVectorNumElements();
5787 MVT TruncVT = MVT::getIntegerVT(EltSize);
5788 SmallVector<SDValue, 8> Ops;
5789 for (unsigned i = 0; i != NumElts; ++i) {
5790 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5791 const APInt &CInt = C->getAPIntValue();
5792 // Element types smaller than 32 bits are not legal, so use i32 elements.
5793 // The values are implicitly truncated so sext vs. zext doesn't matter.
5794 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5796 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5797 MVT::getVectorVT(TruncVT, NumElts), Ops);
5800 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5801 unsigned Opcode = N->getOpcode();
5802 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5803 SDNode *N0 = N->getOperand(0).getNode();
5804 SDNode *N1 = N->getOperand(1).getNode();
5805 return N0->hasOneUse() && N1->hasOneUse() &&
5806 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5811 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5812 unsigned Opcode = N->getOpcode();
5813 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5814 SDNode *N0 = N->getOperand(0).getNode();
5815 SDNode *N1 = N->getOperand(1).getNode();
5816 return N0->hasOneUse() && N1->hasOneUse() &&
5817 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5822 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5823 // Multiplications are only custom-lowered for 128-bit vectors so that
5824 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5825 EVT VT = Op.getValueType();
5826 assert(VT.is128BitVector() && VT.isInteger() &&
5827 "unexpected type for custom-lowering ISD::MUL");
5828 SDNode *N0 = Op.getOperand(0).getNode();
5829 SDNode *N1 = Op.getOperand(1).getNode();
5830 unsigned NewOpc = 0;
5832 bool isN0SExt = isSignExtended(N0, DAG);
5833 bool isN1SExt = isSignExtended(N1, DAG);
5834 if (isN0SExt && isN1SExt)
5835 NewOpc = ARMISD::VMULLs;
5837 bool isN0ZExt = isZeroExtended(N0, DAG);
5838 bool isN1ZExt = isZeroExtended(N1, DAG);
5839 if (isN0ZExt && isN1ZExt)
5840 NewOpc = ARMISD::VMULLu;
5841 else if (isN1SExt || isN1ZExt) {
5842 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5843 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5844 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5845 NewOpc = ARMISD::VMULLs;
5847 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5848 NewOpc = ARMISD::VMULLu;
5850 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5852 NewOpc = ARMISD::VMULLu;
5858 if (VT == MVT::v2i64)
5859 // Fall through to expand this. It is not legal.
5862 // Other vector multiplications are legal.
5867 // Legalize to a VMULL instruction.
5870 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5872 Op0 = SkipExtensionForVMULL(N0, DAG);
5873 assert(Op0.getValueType().is64BitVector() &&
5874 Op1.getValueType().is64BitVector() &&
5875 "unexpected types for extended operands to VMULL");
5876 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5879 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5880 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5887 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5888 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5889 EVT Op1VT = Op1.getValueType();
5890 return DAG.getNode(N0->getOpcode(), DL, VT,
5891 DAG.getNode(NewOpc, DL, VT,
5892 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5893 DAG.getNode(NewOpc, DL, VT,
5894 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5898 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5900 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5901 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5902 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5903 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5904 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5905 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5906 // Get reciprocal estimate.
5907 // float4 recip = vrecpeq_f32(yf);
5908 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5909 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5910 // Because char has a smaller range than uchar, we can actually get away
5911 // without any newton steps. This requires that we use a weird bias
5912 // of 0xb000, however (again, this has been exhaustively tested).
5913 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5914 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5915 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5916 Y = DAG.getConstant(0xb000, MVT::i32);
5917 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5918 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5919 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5920 // Convert back to short.
5921 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5922 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5927 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5929 // Convert to float.
5930 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5931 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5932 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5933 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5934 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5935 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5937 // Use reciprocal estimate and one refinement step.
5938 // float4 recip = vrecpeq_f32(yf);
5939 // recip *= vrecpsq_f32(yf, recip);
5940 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5941 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5942 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5943 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5945 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5946 // Because short has a smaller range than ushort, we can actually get away
5947 // with only a single newton step. This requires that we use a weird bias
5948 // of 89, however (again, this has been exhaustively tested).
5949 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5950 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5951 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5952 N1 = DAG.getConstant(0x89, MVT::i32);
5953 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5954 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5955 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5956 // Convert back to integer and return.
5957 // return vmovn_s32(vcvt_s32_f32(result));
5958 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5959 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5963 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5964 EVT VT = Op.getValueType();
5965 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5966 "unexpected type for custom-lowering ISD::SDIV");
5969 SDValue N0 = Op.getOperand(0);
5970 SDValue N1 = Op.getOperand(1);
5973 if (VT == MVT::v8i8) {
5974 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5975 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5977 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5978 DAG.getIntPtrConstant(4));
5979 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5980 DAG.getIntPtrConstant(4));
5981 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5982 DAG.getIntPtrConstant(0));
5983 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5984 DAG.getIntPtrConstant(0));
5986 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5987 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5989 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5990 N0 = LowerCONCAT_VECTORS(N0, DAG);
5992 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5995 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5998 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5999 EVT VT = Op.getValueType();
6000 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6001 "unexpected type for custom-lowering ISD::UDIV");
6004 SDValue N0 = Op.getOperand(0);
6005 SDValue N1 = Op.getOperand(1);
6008 if (VT == MVT::v8i8) {
6009 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6010 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6012 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6013 DAG.getIntPtrConstant(4));
6014 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6015 DAG.getIntPtrConstant(4));
6016 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6017 DAG.getIntPtrConstant(0));
6018 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6019 DAG.getIntPtrConstant(0));
6021 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6022 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6024 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6025 N0 = LowerCONCAT_VECTORS(N0, DAG);
6027 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6028 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6033 // v4i16 sdiv ... Convert to float.
6034 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6035 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6036 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6037 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6038 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6039 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6041 // Use reciprocal estimate and two refinement steps.
6042 // float4 recip = vrecpeq_f32(yf);
6043 // recip *= vrecpsq_f32(yf, recip);
6044 // recip *= vrecpsq_f32(yf, recip);
6045 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6046 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6047 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6048 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6050 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6051 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6052 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6054 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6055 // Simply multiplying by the reciprocal estimate can leave us a few ulps
6056 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6057 // and that it will never cause us to return an answer too large).
6058 // float4 result = as_float4(as_int4(xf*recip) + 2);
6059 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6060 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6061 N1 = DAG.getConstant(2, MVT::i32);
6062 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6063 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6064 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6065 // Convert back to integer and return.
6066 // return vmovn_u32(vcvt_s32_f32(result));
6067 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6068 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6072 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6073 EVT VT = Op.getNode()->getValueType(0);
6074 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6077 bool ExtraOp = false;
6078 switch (Op.getOpcode()) {
6079 default: llvm_unreachable("Invalid code");
6080 case ISD::ADDC: Opc = ARMISD::ADDC; break;
6081 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6082 case ISD::SUBC: Opc = ARMISD::SUBC; break;
6083 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6087 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6089 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6090 Op.getOperand(1), Op.getOperand(2));
6093 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6094 assert(Subtarget->isTargetDarwin());
6096 // For iOS, we want to call an alternative entry point: __sincos_stret,
6097 // return values are passed via sret.
6099 SDValue Arg = Op.getOperand(0);
6100 EVT ArgVT = Arg.getValueType();
6101 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6103 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6104 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6106 // Pair of floats / doubles used to pass the result.
6107 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6109 // Create stack object for sret.
6110 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6111 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6112 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6113 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6119 Entry.Ty = RetTy->getPointerTo();
6120 Entry.isSExt = false;
6121 Entry.isZExt = false;
6122 Entry.isSRet = true;
6123 Args.push_back(Entry);
6127 Entry.isSExt = false;
6128 Entry.isZExt = false;
6129 Args.push_back(Entry);
6131 const char *LibcallName = (ArgVT == MVT::f64)
6132 ? "__sincos_stret" : "__sincosf_stret";
6133 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6136 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6137 false, false, false, false, 0,
6138 CallingConv::C, /*isTaillCall=*/false,
6139 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6140 Callee, Args, DAG, dl);
6141 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6143 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6144 MachinePointerInfo(), false, false, false, 0);
6146 // Address of cos field.
6147 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6148 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6149 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6150 MachinePointerInfo(), false, false, false, 0);
6152 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6153 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6154 LoadSin.getValue(0), LoadCos.getValue(0));
6157 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6158 // Monotonic load/store is legal for all targets
6159 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6162 // Acquire/Release load/store is not legal for targets without a
6163 // dmb or equivalent available.
6167 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6168 SmallVectorImpl<SDValue> &Results,
6170 const ARMSubtarget *Subtarget) {
6172 SDValue Cycles32, OutChain;
6174 if (Subtarget->hasPerfMon()) {
6175 // Under Power Management extensions, the cycle-count is:
6176 // mrc p15, #0, <Rt>, c9, c13, #0
6177 SDValue Ops[] = { N->getOperand(0), // Chain
6178 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6179 DAG.getConstant(15, MVT::i32),
6180 DAG.getConstant(0, MVT::i32),
6181 DAG.getConstant(9, MVT::i32),
6182 DAG.getConstant(13, MVT::i32),
6183 DAG.getConstant(0, MVT::i32)
6186 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6187 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6188 OutChain = Cycles32.getValue(1);
6190 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6191 // there are older ARM CPUs that have implementation-specific ways of
6192 // obtaining this information (FIXME!).
6193 Cycles32 = DAG.getConstant(0, MVT::i32);
6194 OutChain = DAG.getEntryNode();
6198 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6199 Cycles32, DAG.getConstant(0, MVT::i32));
6200 Results.push_back(Cycles64);
6201 Results.push_back(OutChain);
6204 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6205 switch (Op.getOpcode()) {
6206 default: llvm_unreachable("Don't know how to custom lower this!");
6207 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6208 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6209 case ISD::GlobalAddress:
6210 switch (Subtarget->getTargetTriple().getObjectFormat()) {
6211 default: llvm_unreachable("unknown object format");
6213 return LowerGlobalAddressWindows(Op, DAG);
6215 return LowerGlobalAddressELF(Op, DAG);
6217 return LowerGlobalAddressDarwin(Op, DAG);
6219 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6220 case ISD::SELECT: return LowerSELECT(Op, DAG);
6221 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6222 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6223 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6224 case ISD::VASTART: return LowerVASTART(Op, DAG);
6225 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6226 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6227 case ISD::SINT_TO_FP:
6228 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6229 case ISD::FP_TO_SINT:
6230 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6231 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6232 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6233 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6234 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6235 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6236 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6237 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6239 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6242 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6243 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6244 case ISD::SRL_PARTS:
6245 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6246 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6247 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6248 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6249 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6250 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6251 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6252 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6253 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6254 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6255 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6256 case ISD::MUL: return LowerMUL(Op, DAG);
6257 case ISD::SDIV: return LowerSDIV(Op, DAG);
6258 case ISD::UDIV: return LowerUDIV(Op, DAG);
6262 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6267 return LowerXALUO(Op, DAG);
6268 case ISD::ATOMIC_LOAD:
6269 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6270 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6272 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6276 /// ReplaceNodeResults - Replace the results of node with an illegal result
6277 /// type with new values built out of custom code.
6278 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6279 SmallVectorImpl<SDValue>&Results,
6280 SelectionDAG &DAG) const {
6282 switch (N->getOpcode()) {
6284 llvm_unreachable("Don't know how to custom expand this!");
6286 Res = ExpandBITCAST(N, DAG);
6290 Res = Expand64BitShift(N, DAG, Subtarget);
6292 case ISD::READCYCLECOUNTER:
6293 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6297 Results.push_back(Res);
6300 //===----------------------------------------------------------------------===//
6301 // ARM Scheduler Hooks
6302 //===----------------------------------------------------------------------===//
6304 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6305 /// registers the function context.
6306 void ARMTargetLowering::
6307 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6308 MachineBasicBlock *DispatchBB, int FI) const {
6309 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6310 DebugLoc dl = MI->getDebugLoc();
6311 MachineFunction *MF = MBB->getParent();
6312 MachineRegisterInfo *MRI = &MF->getRegInfo();
6313 MachineConstantPool *MCP = MF->getConstantPool();
6314 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6315 const Function *F = MF->getFunction();
6317 bool isThumb = Subtarget->isThumb();
6318 bool isThumb2 = Subtarget->isThumb2();
6320 unsigned PCLabelId = AFI->createPICLabelUId();
6321 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6322 ARMConstantPoolValue *CPV =
6323 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6324 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6326 const TargetRegisterClass *TRC = isThumb ?
6327 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6328 (const TargetRegisterClass*)&ARM::GPRRegClass;
6330 // Grab constant pool and fixed stack memory operands.
6331 MachineMemOperand *CPMMO =
6332 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6333 MachineMemOperand::MOLoad, 4, 4);
6335 MachineMemOperand *FIMMOSt =
6336 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6337 MachineMemOperand::MOStore, 4, 4);
6339 // Load the address of the dispatch MBB into the jump buffer.
6341 // Incoming value: jbuf
6342 // ldr.n r5, LCPI1_1
6345 // str r5, [$jbuf, #+4] ; &jbuf[1]
6346 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6347 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6348 .addConstantPoolIndex(CPI)
6349 .addMemOperand(CPMMO));
6350 // Set the low bit because of thumb mode.
6351 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6353 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6354 .addReg(NewVReg1, RegState::Kill)
6356 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6357 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6358 .addReg(NewVReg2, RegState::Kill)
6360 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6361 .addReg(NewVReg3, RegState::Kill)
6363 .addImm(36) // &jbuf[1] :: pc
6364 .addMemOperand(FIMMOSt));
6365 } else if (isThumb) {
6366 // Incoming value: jbuf
6367 // ldr.n r1, LCPI1_4
6371 // add r2, $jbuf, #+4 ; &jbuf[1]
6373 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6374 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6375 .addConstantPoolIndex(CPI)
6376 .addMemOperand(CPMMO));
6377 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6378 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6379 .addReg(NewVReg1, RegState::Kill)
6381 // Set the low bit because of thumb mode.
6382 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6383 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6384 .addReg(ARM::CPSR, RegState::Define)
6386 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6387 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6388 .addReg(ARM::CPSR, RegState::Define)
6389 .addReg(NewVReg2, RegState::Kill)
6390 .addReg(NewVReg3, RegState::Kill));
6391 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6392 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6394 .addImm(36)); // &jbuf[1] :: pc
6395 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6396 .addReg(NewVReg4, RegState::Kill)
6397 .addReg(NewVReg5, RegState::Kill)
6399 .addMemOperand(FIMMOSt));
6401 // Incoming value: jbuf
6404 // str r1, [$jbuf, #+4] ; &jbuf[1]
6405 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6406 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6407 .addConstantPoolIndex(CPI)
6409 .addMemOperand(CPMMO));
6410 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6411 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6412 .addReg(NewVReg1, RegState::Kill)
6413 .addImm(PCLabelId));
6414 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6415 .addReg(NewVReg2, RegState::Kill)
6417 .addImm(36) // &jbuf[1] :: pc
6418 .addMemOperand(FIMMOSt));
6422 MachineBasicBlock *ARMTargetLowering::
6423 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6424 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6425 DebugLoc dl = MI->getDebugLoc();
6426 MachineFunction *MF = MBB->getParent();
6427 MachineRegisterInfo *MRI = &MF->getRegInfo();
6428 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6429 MachineFrameInfo *MFI = MF->getFrameInfo();
6430 int FI = MFI->getFunctionContextIndex();
6432 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6433 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6434 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6436 // Get a mapping of the call site numbers to all of the landing pads they're
6438 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6439 unsigned MaxCSNum = 0;
6440 MachineModuleInfo &MMI = MF->getMMI();
6441 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6443 if (!BB->isLandingPad()) continue;
6445 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6447 for (MachineBasicBlock::iterator
6448 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6449 if (!II->isEHLabel()) continue;
6451 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6452 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6454 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6455 for (SmallVectorImpl<unsigned>::iterator
6456 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6457 CSI != CSE; ++CSI) {
6458 CallSiteNumToLPad[*CSI].push_back(BB);
6459 MaxCSNum = std::max(MaxCSNum, *CSI);
6465 // Get an ordered list of the machine basic blocks for the jump table.
6466 std::vector<MachineBasicBlock*> LPadList;
6467 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6468 LPadList.reserve(CallSiteNumToLPad.size());
6469 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6470 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6471 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6472 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6473 LPadList.push_back(*II);
6474 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6478 assert(!LPadList.empty() &&
6479 "No landing pad destinations for the dispatch jump table!");
6481 // Create the jump table and associated information.
6482 MachineJumpTableInfo *JTI =
6483 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6484 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6485 unsigned UId = AFI->createJumpTableUId();
6486 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6488 // Create the MBBs for the dispatch code.
6490 // Shove the dispatch's address into the return slot in the function context.
6491 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6492 DispatchBB->setIsLandingPad();
6494 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6495 unsigned trap_opcode;
6496 if (Subtarget->isThumb())
6497 trap_opcode = ARM::tTRAP;
6499 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6501 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6502 DispatchBB->addSuccessor(TrapBB);
6504 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6505 DispatchBB->addSuccessor(DispContBB);
6508 MF->insert(MF->end(), DispatchBB);
6509 MF->insert(MF->end(), DispContBB);
6510 MF->insert(MF->end(), TrapBB);
6512 // Insert code into the entry block that creates and registers the function
6514 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6516 MachineMemOperand *FIMMOLd =
6517 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6518 MachineMemOperand::MOLoad |
6519 MachineMemOperand::MOVolatile, 4, 4);
6521 MachineInstrBuilder MIB;
6522 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6524 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6525 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6527 // Add a register mask with no preserved registers. This results in all
6528 // registers being marked as clobbered.
6529 MIB.addRegMask(RI.getNoPreservedMask());
6531 unsigned NumLPads = LPadList.size();
6532 if (Subtarget->isThumb2()) {
6533 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6534 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6537 .addMemOperand(FIMMOLd));
6539 if (NumLPads < 256) {
6540 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6542 .addImm(LPadList.size()));
6544 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6545 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6546 .addImm(NumLPads & 0xFFFF));
6548 unsigned VReg2 = VReg1;
6549 if ((NumLPads & 0xFFFF0000) != 0) {
6550 VReg2 = MRI->createVirtualRegister(TRC);
6551 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6553 .addImm(NumLPads >> 16));
6556 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6561 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6566 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6567 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6568 .addJumpTableIndex(MJTI)
6571 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6574 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6575 .addReg(NewVReg3, RegState::Kill)
6577 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6579 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6580 .addReg(NewVReg4, RegState::Kill)
6582 .addJumpTableIndex(MJTI)
6584 } else if (Subtarget->isThumb()) {
6585 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6586 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6589 .addMemOperand(FIMMOLd));
6591 if (NumLPads < 256) {
6592 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6596 MachineConstantPool *ConstantPool = MF->getConstantPool();
6597 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6598 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6600 // MachineConstantPool wants an explicit alignment.
6601 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6603 Align = getDataLayout()->getTypeAllocSize(C->getType());
6604 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6606 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6607 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6608 .addReg(VReg1, RegState::Define)
6609 .addConstantPoolIndex(Idx));
6610 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6615 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6620 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6621 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6622 .addReg(ARM::CPSR, RegState::Define)
6626 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6627 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6628 .addJumpTableIndex(MJTI)
6631 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6632 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6633 .addReg(ARM::CPSR, RegState::Define)
6634 .addReg(NewVReg2, RegState::Kill)
6637 MachineMemOperand *JTMMOLd =
6638 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6639 MachineMemOperand::MOLoad, 4, 4);
6641 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6642 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6643 .addReg(NewVReg4, RegState::Kill)
6645 .addMemOperand(JTMMOLd));
6647 unsigned NewVReg6 = NewVReg5;
6648 if (RelocM == Reloc::PIC_) {
6649 NewVReg6 = MRI->createVirtualRegister(TRC);
6650 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6651 .addReg(ARM::CPSR, RegState::Define)
6652 .addReg(NewVReg5, RegState::Kill)
6656 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6657 .addReg(NewVReg6, RegState::Kill)
6658 .addJumpTableIndex(MJTI)
6661 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6662 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6665 .addMemOperand(FIMMOLd));
6667 if (NumLPads < 256) {
6668 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6671 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6672 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6673 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6674 .addImm(NumLPads & 0xFFFF));
6676 unsigned VReg2 = VReg1;
6677 if ((NumLPads & 0xFFFF0000) != 0) {
6678 VReg2 = MRI->createVirtualRegister(TRC);
6679 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6681 .addImm(NumLPads >> 16));
6684 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6688 MachineConstantPool *ConstantPool = MF->getConstantPool();
6689 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6690 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6692 // MachineConstantPool wants an explicit alignment.
6693 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6695 Align = getDataLayout()->getTypeAllocSize(C->getType());
6696 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6698 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6699 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6700 .addReg(VReg1, RegState::Define)
6701 .addConstantPoolIndex(Idx)
6703 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6705 .addReg(VReg1, RegState::Kill));
6708 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6713 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6715 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6717 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6718 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6719 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6720 .addJumpTableIndex(MJTI)
6723 MachineMemOperand *JTMMOLd =
6724 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6725 MachineMemOperand::MOLoad, 4, 4);
6726 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6728 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6729 .addReg(NewVReg3, RegState::Kill)
6732 .addMemOperand(JTMMOLd));
6734 if (RelocM == Reloc::PIC_) {
6735 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6736 .addReg(NewVReg5, RegState::Kill)
6738 .addJumpTableIndex(MJTI)
6741 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6742 .addReg(NewVReg5, RegState::Kill)
6743 .addJumpTableIndex(MJTI)
6748 // Add the jump table entries as successors to the MBB.
6749 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6750 for (std::vector<MachineBasicBlock*>::iterator
6751 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6752 MachineBasicBlock *CurMBB = *I;
6753 if (SeenMBBs.insert(CurMBB))
6754 DispContBB->addSuccessor(CurMBB);
6757 // N.B. the order the invoke BBs are processed in doesn't matter here.
6758 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6759 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6760 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6761 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6762 MachineBasicBlock *BB = *I;
6764 // Remove the landing pad successor from the invoke block and replace it
6765 // with the new dispatch block.
6766 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6768 while (!Successors.empty()) {
6769 MachineBasicBlock *SMBB = Successors.pop_back_val();
6770 if (SMBB->isLandingPad()) {
6771 BB->removeSuccessor(SMBB);
6772 MBBLPads.push_back(SMBB);
6776 BB->addSuccessor(DispatchBB);
6778 // Find the invoke call and mark all of the callee-saved registers as
6779 // 'implicit defined' so that they're spilled. This prevents code from
6780 // moving instructions to before the EH block, where they will never be
6782 for (MachineBasicBlock::reverse_iterator
6783 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6784 if (!II->isCall()) continue;
6786 DenseMap<unsigned, bool> DefRegs;
6787 for (MachineInstr::mop_iterator
6788 OI = II->operands_begin(), OE = II->operands_end();
6790 if (!OI->isReg()) continue;
6791 DefRegs[OI->getReg()] = true;
6794 MachineInstrBuilder MIB(*MF, &*II);
6796 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6797 unsigned Reg = SavedRegs[i];
6798 if (Subtarget->isThumb2() &&
6799 !ARM::tGPRRegClass.contains(Reg) &&
6800 !ARM::hGPRRegClass.contains(Reg))
6802 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6804 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6807 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6814 // Mark all former landing pads as non-landing pads. The dispatch is the only
6816 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6817 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6818 (*I)->setIsLandingPad(false);
6820 // The instruction is gone now.
6821 MI->eraseFromParent();
6827 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6828 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6829 E = MBB->succ_end(); I != E; ++I)
6832 llvm_unreachable("Expecting a BB with two successors!");
6835 /// Return the load opcode for a given load size. If load size >= 8,
6836 /// neon opcode will be returned.
6837 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6839 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6840 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6842 return LdSize == 4 ? ARM::tLDRi
6843 : LdSize == 2 ? ARM::tLDRHi
6844 : LdSize == 1 ? ARM::tLDRBi : 0;
6846 return LdSize == 4 ? ARM::t2LDR_POST
6847 : LdSize == 2 ? ARM::t2LDRH_POST
6848 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6849 return LdSize == 4 ? ARM::LDR_POST_IMM
6850 : LdSize == 2 ? ARM::LDRH_POST
6851 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6854 /// Return the store opcode for a given store size. If store size >= 8,
6855 /// neon opcode will be returned.
6856 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6858 return StSize == 16 ? ARM::VST1q32wb_fixed
6859 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6861 return StSize == 4 ? ARM::tSTRi
6862 : StSize == 2 ? ARM::tSTRHi
6863 : StSize == 1 ? ARM::tSTRBi : 0;
6865 return StSize == 4 ? ARM::t2STR_POST
6866 : StSize == 2 ? ARM::t2STRH_POST
6867 : StSize == 1 ? ARM::t2STRB_POST : 0;
6868 return StSize == 4 ? ARM::STR_POST_IMM
6869 : StSize == 2 ? ARM::STRH_POST
6870 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6873 /// Emit a post-increment load operation with given size. The instructions
6874 /// will be added to BB at Pos.
6875 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6876 const TargetInstrInfo *TII, DebugLoc dl,
6877 unsigned LdSize, unsigned Data, unsigned AddrIn,
6878 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6879 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6880 assert(LdOpc != 0 && "Should have a load opcode");
6882 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6883 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6885 } else if (IsThumb1) {
6886 // load + update AddrIn
6887 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6888 .addReg(AddrIn).addImm(0));
6889 MachineInstrBuilder MIB =
6890 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6891 MIB = AddDefaultT1CC(MIB);
6892 MIB.addReg(AddrIn).addImm(LdSize);
6893 AddDefaultPred(MIB);
6894 } else if (IsThumb2) {
6895 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6896 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6899 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6900 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6901 .addReg(0).addImm(LdSize));
6905 /// Emit a post-increment store operation with given size. The instructions
6906 /// will be added to BB at Pos.
6907 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6908 const TargetInstrInfo *TII, DebugLoc dl,
6909 unsigned StSize, unsigned Data, unsigned AddrIn,
6910 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6911 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6912 assert(StOpc != 0 && "Should have a store opcode");
6914 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6915 .addReg(AddrIn).addImm(0).addReg(Data));
6916 } else if (IsThumb1) {
6917 // store + update AddrIn
6918 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6919 .addReg(AddrIn).addImm(0));
6920 MachineInstrBuilder MIB =
6921 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6922 MIB = AddDefaultT1CC(MIB);
6923 MIB.addReg(AddrIn).addImm(StSize);
6924 AddDefaultPred(MIB);
6925 } else if (IsThumb2) {
6926 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6927 .addReg(Data).addReg(AddrIn).addImm(StSize));
6929 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6930 .addReg(Data).addReg(AddrIn).addReg(0)
6936 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6937 MachineBasicBlock *BB) const {
6938 // This pseudo instruction has 3 operands: dst, src, size
6939 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6940 // Otherwise, we will generate unrolled scalar copies.
6941 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6942 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6943 MachineFunction::iterator It = BB;
6946 unsigned dest = MI->getOperand(0).getReg();
6947 unsigned src = MI->getOperand(1).getReg();
6948 unsigned SizeVal = MI->getOperand(2).getImm();
6949 unsigned Align = MI->getOperand(3).getImm();
6950 DebugLoc dl = MI->getDebugLoc();
6952 MachineFunction *MF = BB->getParent();
6953 MachineRegisterInfo &MRI = MF->getRegInfo();
6954 unsigned UnitSize = 0;
6955 const TargetRegisterClass *TRC = nullptr;
6956 const TargetRegisterClass *VecTRC = nullptr;
6958 bool IsThumb1 = Subtarget->isThumb1Only();
6959 bool IsThumb2 = Subtarget->isThumb2();
6963 } else if (Align & 2) {
6966 // Check whether we can use NEON instructions.
6967 if (!MF->getFunction()->getAttributes().
6968 hasAttribute(AttributeSet::FunctionIndex,
6969 Attribute::NoImplicitFloat) &&
6970 Subtarget->hasNEON()) {
6971 if ((Align % 16 == 0) && SizeVal >= 16)
6973 else if ((Align % 8 == 0) && SizeVal >= 8)
6976 // Can't use NEON instructions.
6981 // Select the correct opcode and register class for unit size load/store
6982 bool IsNeon = UnitSize >= 8;
6983 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6984 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6986 VecTRC = UnitSize == 16
6987 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6989 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6992 unsigned BytesLeft = SizeVal % UnitSize;
6993 unsigned LoopSize = SizeVal - BytesLeft;
6995 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6996 // Use LDR and STR to copy.
6997 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6998 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6999 unsigned srcIn = src;
7000 unsigned destIn = dest;
7001 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7002 unsigned srcOut = MRI.createVirtualRegister(TRC);
7003 unsigned destOut = MRI.createVirtualRegister(TRC);
7004 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7005 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7006 IsThumb1, IsThumb2);
7007 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7008 IsThumb1, IsThumb2);
7013 // Handle the leftover bytes with LDRB and STRB.
7014 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7015 // [destOut] = STRB_POST(scratch, destIn, 1)
7016 for (unsigned i = 0; i < BytesLeft; i++) {
7017 unsigned srcOut = MRI.createVirtualRegister(TRC);
7018 unsigned destOut = MRI.createVirtualRegister(TRC);
7019 unsigned scratch = MRI.createVirtualRegister(TRC);
7020 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7021 IsThumb1, IsThumb2);
7022 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7023 IsThumb1, IsThumb2);
7027 MI->eraseFromParent(); // The instruction is gone now.
7031 // Expand the pseudo op to a loop.
7034 // movw varEnd, # --> with thumb2
7036 // ldrcp varEnd, idx --> without thumb2
7037 // fallthrough --> loopMBB
7039 // PHI varPhi, varEnd, varLoop
7040 // PHI srcPhi, src, srcLoop
7041 // PHI destPhi, dst, destLoop
7042 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7043 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7044 // subs varLoop, varPhi, #UnitSize
7046 // fallthrough --> exitMBB
7048 // epilogue to handle left-over bytes
7049 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7050 // [destOut] = STRB_POST(scratch, destLoop, 1)
7051 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7052 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7053 MF->insert(It, loopMBB);
7054 MF->insert(It, exitMBB);
7056 // Transfer the remainder of BB and its successor edges to exitMBB.
7057 exitMBB->splice(exitMBB->begin(), BB,
7058 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7059 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7061 // Load an immediate to varEnd.
7062 unsigned varEnd = MRI.createVirtualRegister(TRC);
7064 unsigned Vtmp = varEnd;
7065 if ((LoopSize & 0xFFFF0000) != 0)
7066 Vtmp = MRI.createVirtualRegister(TRC);
7067 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7068 .addImm(LoopSize & 0xFFFF));
7070 if ((LoopSize & 0xFFFF0000) != 0)
7071 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7072 .addReg(Vtmp).addImm(LoopSize >> 16));
7074 MachineConstantPool *ConstantPool = MF->getConstantPool();
7075 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7076 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7078 // MachineConstantPool wants an explicit alignment.
7079 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7081 Align = getDataLayout()->getTypeAllocSize(C->getType());
7082 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7085 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7086 varEnd, RegState::Define).addConstantPoolIndex(Idx));
7088 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7089 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7091 BB->addSuccessor(loopMBB);
7093 // Generate the loop body:
7094 // varPhi = PHI(varLoop, varEnd)
7095 // srcPhi = PHI(srcLoop, src)
7096 // destPhi = PHI(destLoop, dst)
7097 MachineBasicBlock *entryBB = BB;
7099 unsigned varLoop = MRI.createVirtualRegister(TRC);
7100 unsigned varPhi = MRI.createVirtualRegister(TRC);
7101 unsigned srcLoop = MRI.createVirtualRegister(TRC);
7102 unsigned srcPhi = MRI.createVirtualRegister(TRC);
7103 unsigned destLoop = MRI.createVirtualRegister(TRC);
7104 unsigned destPhi = MRI.createVirtualRegister(TRC);
7106 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7107 .addReg(varLoop).addMBB(loopMBB)
7108 .addReg(varEnd).addMBB(entryBB);
7109 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7110 .addReg(srcLoop).addMBB(loopMBB)
7111 .addReg(src).addMBB(entryBB);
7112 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7113 .addReg(destLoop).addMBB(loopMBB)
7114 .addReg(dest).addMBB(entryBB);
7116 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7117 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7118 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7119 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7120 IsThumb1, IsThumb2);
7121 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7122 IsThumb1, IsThumb2);
7124 // Decrement loop variable by UnitSize.
7126 MachineInstrBuilder MIB =
7127 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7128 MIB = AddDefaultT1CC(MIB);
7129 MIB.addReg(varPhi).addImm(UnitSize);
7130 AddDefaultPred(MIB);
7132 MachineInstrBuilder MIB =
7133 BuildMI(*BB, BB->end(), dl,
7134 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7135 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7136 MIB->getOperand(5).setReg(ARM::CPSR);
7137 MIB->getOperand(5).setIsDef(true);
7139 BuildMI(*BB, BB->end(), dl,
7140 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7141 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7143 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7144 BB->addSuccessor(loopMBB);
7145 BB->addSuccessor(exitMBB);
7147 // Add epilogue to handle BytesLeft.
7149 MachineInstr *StartOfExit = exitMBB->begin();
7151 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7152 // [destOut] = STRB_POST(scratch, destLoop, 1)
7153 unsigned srcIn = srcLoop;
7154 unsigned destIn = destLoop;
7155 for (unsigned i = 0; i < BytesLeft; i++) {
7156 unsigned srcOut = MRI.createVirtualRegister(TRC);
7157 unsigned destOut = MRI.createVirtualRegister(TRC);
7158 unsigned scratch = MRI.createVirtualRegister(TRC);
7159 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7160 IsThumb1, IsThumb2);
7161 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7162 IsThumb1, IsThumb2);
7167 MI->eraseFromParent(); // The instruction is gone now.
7172 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7173 MachineBasicBlock *BB) const {
7174 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7175 DebugLoc dl = MI->getDebugLoc();
7176 bool isThumb2 = Subtarget->isThumb2();
7177 switch (MI->getOpcode()) {
7180 llvm_unreachable("Unexpected instr type to insert");
7182 // The Thumb2 pre-indexed stores have the same MI operands, they just
7183 // define them differently in the .td files from the isel patterns, so
7184 // they need pseudos.
7185 case ARM::t2STR_preidx:
7186 MI->setDesc(TII->get(ARM::t2STR_PRE));
7188 case ARM::t2STRB_preidx:
7189 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7191 case ARM::t2STRH_preidx:
7192 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7195 case ARM::STRi_preidx:
7196 case ARM::STRBi_preidx: {
7197 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7198 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7199 // Decode the offset.
7200 unsigned Offset = MI->getOperand(4).getImm();
7201 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7202 Offset = ARM_AM::getAM2Offset(Offset);
7206 MachineMemOperand *MMO = *MI->memoperands_begin();
7207 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7208 .addOperand(MI->getOperand(0)) // Rn_wb
7209 .addOperand(MI->getOperand(1)) // Rt
7210 .addOperand(MI->getOperand(2)) // Rn
7211 .addImm(Offset) // offset (skip GPR==zero_reg)
7212 .addOperand(MI->getOperand(5)) // pred
7213 .addOperand(MI->getOperand(6))
7214 .addMemOperand(MMO);
7215 MI->eraseFromParent();
7218 case ARM::STRr_preidx:
7219 case ARM::STRBr_preidx:
7220 case ARM::STRH_preidx: {
7222 switch (MI->getOpcode()) {
7223 default: llvm_unreachable("unexpected opcode!");
7224 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7225 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7226 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7228 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7229 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7230 MIB.addOperand(MI->getOperand(i));
7231 MI->eraseFromParent();
7235 case ARM::tMOVCCr_pseudo: {
7236 // To "insert" a SELECT_CC instruction, we actually have to insert the
7237 // diamond control-flow pattern. The incoming instruction knows the
7238 // destination vreg to set, the condition code register to branch on, the
7239 // true/false values to select between, and a branch opcode to use.
7240 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7241 MachineFunction::iterator It = BB;
7247 // cmpTY ccX, r1, r2
7249 // fallthrough --> copy0MBB
7250 MachineBasicBlock *thisMBB = BB;
7251 MachineFunction *F = BB->getParent();
7252 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7253 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7254 F->insert(It, copy0MBB);
7255 F->insert(It, sinkMBB);
7257 // Transfer the remainder of BB and its successor edges to sinkMBB.
7258 sinkMBB->splice(sinkMBB->begin(), BB,
7259 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7260 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7262 BB->addSuccessor(copy0MBB);
7263 BB->addSuccessor(sinkMBB);
7265 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7266 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7269 // %FalseValue = ...
7270 // # fallthrough to sinkMBB
7273 // Update machine-CFG edges
7274 BB->addSuccessor(sinkMBB);
7277 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7280 BuildMI(*BB, BB->begin(), dl,
7281 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7282 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7283 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7285 MI->eraseFromParent(); // The pseudo instruction is gone now.
7290 case ARM::BCCZi64: {
7291 // If there is an unconditional branch to the other successor, remove it.
7292 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7294 // Compare both parts that make up the double comparison separately for
7296 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7298 unsigned LHS1 = MI->getOperand(1).getReg();
7299 unsigned LHS2 = MI->getOperand(2).getReg();
7301 AddDefaultPred(BuildMI(BB, dl,
7302 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7303 .addReg(LHS1).addImm(0));
7304 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7305 .addReg(LHS2).addImm(0)
7306 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7308 unsigned RHS1 = MI->getOperand(3).getReg();
7309 unsigned RHS2 = MI->getOperand(4).getReg();
7310 AddDefaultPred(BuildMI(BB, dl,
7311 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7312 .addReg(LHS1).addReg(RHS1));
7313 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7314 .addReg(LHS2).addReg(RHS2)
7315 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7318 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7319 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7320 if (MI->getOperand(0).getImm() == ARMCC::NE)
7321 std::swap(destMBB, exitMBB);
7323 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7324 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7326 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7328 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7330 MI->eraseFromParent(); // The pseudo instruction is gone now.
7334 case ARM::Int_eh_sjlj_setjmp:
7335 case ARM::Int_eh_sjlj_setjmp_nofp:
7336 case ARM::tInt_eh_sjlj_setjmp:
7337 case ARM::t2Int_eh_sjlj_setjmp:
7338 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7339 EmitSjLjDispatchBlock(MI, BB);
7344 // To insert an ABS instruction, we have to insert the
7345 // diamond control-flow pattern. The incoming instruction knows the
7346 // source vreg to test against 0, the destination vreg to set,
7347 // the condition code register to branch on, the
7348 // true/false values to select between, and a branch opcode to use.
7353 // BCC (branch to SinkBB if V0 >= 0)
7354 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7355 // SinkBB: V1 = PHI(V2, V3)
7356 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7357 MachineFunction::iterator BBI = BB;
7359 MachineFunction *Fn = BB->getParent();
7360 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7361 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7362 Fn->insert(BBI, RSBBB);
7363 Fn->insert(BBI, SinkBB);
7365 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7366 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7367 bool isThumb2 = Subtarget->isThumb2();
7368 MachineRegisterInfo &MRI = Fn->getRegInfo();
7369 // In Thumb mode S must not be specified if source register is the SP or
7370 // PC and if destination register is the SP, so restrict register class
7371 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7372 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7373 (const TargetRegisterClass*)&ARM::GPRRegClass);
7375 // Transfer the remainder of BB and its successor edges to sinkMBB.
7376 SinkBB->splice(SinkBB->begin(), BB,
7377 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7378 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7380 BB->addSuccessor(RSBBB);
7381 BB->addSuccessor(SinkBB);
7383 // fall through to SinkMBB
7384 RSBBB->addSuccessor(SinkBB);
7386 // insert a cmp at the end of BB
7387 AddDefaultPred(BuildMI(BB, dl,
7388 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7389 .addReg(ABSSrcReg).addImm(0));
7391 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7393 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7394 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7396 // insert rsbri in RSBBB
7397 // Note: BCC and rsbri will be converted into predicated rsbmi
7398 // by if-conversion pass
7399 BuildMI(*RSBBB, RSBBB->begin(), dl,
7400 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7401 .addReg(ABSSrcReg, RegState::Kill)
7402 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7404 // insert PHI in SinkBB,
7405 // reuse ABSDstReg to not change uses of ABS instruction
7406 BuildMI(*SinkBB, SinkBB->begin(), dl,
7407 TII->get(ARM::PHI), ABSDstReg)
7408 .addReg(NewRsbDstReg).addMBB(RSBBB)
7409 .addReg(ABSSrcReg).addMBB(BB);
7411 // remove ABS instruction
7412 MI->eraseFromParent();
7414 // return last added BB
7417 case ARM::COPY_STRUCT_BYVAL_I32:
7419 return EmitStructByval(MI, BB);
7423 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7424 SDNode *Node) const {
7425 if (!MI->hasPostISelHook()) {
7426 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7427 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7431 const MCInstrDesc *MCID = &MI->getDesc();
7432 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7433 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7434 // operand is still set to noreg. If needed, set the optional operand's
7435 // register to CPSR, and remove the redundant implicit def.
7437 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7439 // Rename pseudo opcodes.
7440 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7442 const ARMBaseInstrInfo *TII =
7443 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7444 MCID = &TII->get(NewOpc);
7446 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7447 "converted opcode should be the same except for cc_out");
7451 // Add the optional cc_out operand
7452 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7454 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7456 // Any ARM instruction that sets the 's' bit should specify an optional
7457 // "cc_out" operand in the last operand position.
7458 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7459 assert(!NewOpc && "Optional cc_out operand required");
7462 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7463 // since we already have an optional CPSR def.
7464 bool definesCPSR = false;
7465 bool deadCPSR = false;
7466 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7468 const MachineOperand &MO = MI->getOperand(i);
7469 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7473 MI->RemoveOperand(i);
7478 assert(!NewOpc && "Optional cc_out operand required");
7481 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7483 assert(!MI->getOperand(ccOutIdx).getReg() &&
7484 "expect uninitialized optional cc_out operand");
7488 // If this instruction was defined with an optional CPSR def and its dag node
7489 // had a live implicit CPSR def, then activate the optional CPSR def.
7490 MachineOperand &MO = MI->getOperand(ccOutIdx);
7491 MO.setReg(ARM::CPSR);
7495 //===----------------------------------------------------------------------===//
7496 // ARM Optimization Hooks
7497 //===----------------------------------------------------------------------===//
7499 // Helper function that checks if N is a null or all ones constant.
7500 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7501 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7504 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7507 // Return true if N is conditionally 0 or all ones.
7508 // Detects these expressions where cc is an i1 value:
7510 // (select cc 0, y) [AllOnes=0]
7511 // (select cc y, 0) [AllOnes=0]
7512 // (zext cc) [AllOnes=0]
7513 // (sext cc) [AllOnes=0/1]
7514 // (select cc -1, y) [AllOnes=1]
7515 // (select cc y, -1) [AllOnes=1]
7517 // Invert is set when N is the null/all ones constant when CC is false.
7518 // OtherOp is set to the alternative value of N.
7519 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7520 SDValue &CC, bool &Invert,
7522 SelectionDAG &DAG) {
7523 switch (N->getOpcode()) {
7524 default: return false;
7526 CC = N->getOperand(0);
7527 SDValue N1 = N->getOperand(1);
7528 SDValue N2 = N->getOperand(2);
7529 if (isZeroOrAllOnes(N1, AllOnes)) {
7534 if (isZeroOrAllOnes(N2, AllOnes)) {
7541 case ISD::ZERO_EXTEND:
7542 // (zext cc) can never be the all ones value.
7546 case ISD::SIGN_EXTEND: {
7547 EVT VT = N->getValueType(0);
7548 CC = N->getOperand(0);
7549 if (CC.getValueType() != MVT::i1)
7553 // When looking for an AllOnes constant, N is an sext, and the 'other'
7555 OtherOp = DAG.getConstant(0, VT);
7556 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7557 // When looking for a 0 constant, N can be zext or sext.
7558 OtherOp = DAG.getConstant(1, VT);
7560 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7566 // Combine a constant select operand into its use:
7568 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7569 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7570 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7571 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7572 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7574 // The transform is rejected if the select doesn't have a constant operand that
7575 // is null, or all ones when AllOnes is set.
7577 // Also recognize sext/zext from i1:
7579 // (add (zext cc), x) -> (select cc (add x, 1), x)
7580 // (add (sext cc), x) -> (select cc (add x, -1), x)
7582 // These transformations eventually create predicated instructions.
7584 // @param N The node to transform.
7585 // @param Slct The N operand that is a select.
7586 // @param OtherOp The other N operand (x above).
7587 // @param DCI Context.
7588 // @param AllOnes Require the select constant to be all ones instead of null.
7589 // @returns The new node, or SDValue() on failure.
7591 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7592 TargetLowering::DAGCombinerInfo &DCI,
7593 bool AllOnes = false) {
7594 SelectionDAG &DAG = DCI.DAG;
7595 EVT VT = N->getValueType(0);
7596 SDValue NonConstantVal;
7599 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7600 NonConstantVal, DAG))
7603 // Slct is now know to be the desired identity constant when CC is true.
7604 SDValue TrueVal = OtherOp;
7605 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7606 OtherOp, NonConstantVal);
7607 // Unless SwapSelectOps says CC should be false.
7609 std::swap(TrueVal, FalseVal);
7611 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7612 CCOp, TrueVal, FalseVal);
7615 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7617 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7618 TargetLowering::DAGCombinerInfo &DCI) {
7619 SDValue N0 = N->getOperand(0);
7620 SDValue N1 = N->getOperand(1);
7621 if (N0.getNode()->hasOneUse()) {
7622 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7623 if (Result.getNode())
7626 if (N1.getNode()->hasOneUse()) {
7627 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7628 if (Result.getNode())
7634 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7635 // (only after legalization).
7636 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7637 TargetLowering::DAGCombinerInfo &DCI,
7638 const ARMSubtarget *Subtarget) {
7640 // Only perform optimization if after legalize, and if NEON is available. We
7641 // also expected both operands to be BUILD_VECTORs.
7642 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7643 || N0.getOpcode() != ISD::BUILD_VECTOR
7644 || N1.getOpcode() != ISD::BUILD_VECTOR)
7647 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7648 EVT VT = N->getValueType(0);
7649 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7652 // Check that the vector operands are of the right form.
7653 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7654 // operands, where N is the size of the formed vector.
7655 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7656 // index such that we have a pair wise add pattern.
7658 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7659 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7661 SDValue Vec = N0->getOperand(0)->getOperand(0);
7662 SDNode *V = Vec.getNode();
7663 unsigned nextIndex = 0;
7665 // For each operands to the ADD which are BUILD_VECTORs,
7666 // check to see if each of their operands are an EXTRACT_VECTOR with
7667 // the same vector and appropriate index.
7668 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7669 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7670 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7672 SDValue ExtVec0 = N0->getOperand(i);
7673 SDValue ExtVec1 = N1->getOperand(i);
7675 // First operand is the vector, verify its the same.
7676 if (V != ExtVec0->getOperand(0).getNode() ||
7677 V != ExtVec1->getOperand(0).getNode())
7680 // Second is the constant, verify its correct.
7681 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7682 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7684 // For the constant, we want to see all the even or all the odd.
7685 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7686 || C1->getZExtValue() != nextIndex+1)
7695 // Create VPADDL node.
7696 SelectionDAG &DAG = DCI.DAG;
7697 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7699 // Build operand list.
7700 SmallVector<SDValue, 8> Ops;
7701 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7702 TLI.getPointerTy()));
7704 // Input is the vector.
7707 // Get widened type and narrowed type.
7709 unsigned numElem = VT.getVectorNumElements();
7711 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7712 switch (inputLaneType.getSimpleVT().SimpleTy) {
7713 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7714 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7715 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7717 llvm_unreachable("Invalid vector element type for padd optimization.");
7720 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7721 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7722 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7725 static SDValue findMUL_LOHI(SDValue V) {
7726 if (V->getOpcode() == ISD::UMUL_LOHI ||
7727 V->getOpcode() == ISD::SMUL_LOHI)
7732 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7733 TargetLowering::DAGCombinerInfo &DCI,
7734 const ARMSubtarget *Subtarget) {
7736 if (Subtarget->isThumb1Only()) return SDValue();
7738 // Only perform the checks after legalize when the pattern is available.
7739 if (DCI.isBeforeLegalize()) return SDValue();
7741 // Look for multiply add opportunities.
7742 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7743 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7744 // a glue link from the first add to the second add.
7745 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7746 // a S/UMLAL instruction.
7749 // \ / \ [no multiline comment]
7755 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7756 SDValue AddcOp0 = AddcNode->getOperand(0);
7757 SDValue AddcOp1 = AddcNode->getOperand(1);
7759 // Check if the two operands are from the same mul_lohi node.
7760 if (AddcOp0.getNode() == AddcOp1.getNode())
7763 assert(AddcNode->getNumValues() == 2 &&
7764 AddcNode->getValueType(0) == MVT::i32 &&
7765 "Expect ADDC with two result values. First: i32");
7767 // Check that we have a glued ADDC node.
7768 if (AddcNode->getValueType(1) != MVT::Glue)
7771 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7772 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7773 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7774 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7775 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7778 // Look for the glued ADDE.
7779 SDNode* AddeNode = AddcNode->getGluedUser();
7783 // Make sure it is really an ADDE.
7784 if (AddeNode->getOpcode() != ISD::ADDE)
7787 assert(AddeNode->getNumOperands() == 3 &&
7788 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7789 "ADDE node has the wrong inputs");
7791 // Check for the triangle shape.
7792 SDValue AddeOp0 = AddeNode->getOperand(0);
7793 SDValue AddeOp1 = AddeNode->getOperand(1);
7795 // Make sure that the ADDE operands are not coming from the same node.
7796 if (AddeOp0.getNode() == AddeOp1.getNode())
7799 // Find the MUL_LOHI node walking up ADDE's operands.
7800 bool IsLeftOperandMUL = false;
7801 SDValue MULOp = findMUL_LOHI(AddeOp0);
7802 if (MULOp == SDValue())
7803 MULOp = findMUL_LOHI(AddeOp1);
7805 IsLeftOperandMUL = true;
7806 if (MULOp == SDValue())
7809 // Figure out the right opcode.
7810 unsigned Opc = MULOp->getOpcode();
7811 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7813 // Figure out the high and low input values to the MLAL node.
7814 SDValue* HiMul = &MULOp;
7815 SDValue* HiAdd = nullptr;
7816 SDValue* LoMul = nullptr;
7817 SDValue* LowAdd = nullptr;
7819 if (IsLeftOperandMUL)
7825 if (AddcOp0->getOpcode() == Opc) {
7829 if (AddcOp1->getOpcode() == Opc) {
7837 if (LoMul->getNode() != HiMul->getNode())
7840 // Create the merged node.
7841 SelectionDAG &DAG = DCI.DAG;
7843 // Build operand list.
7844 SmallVector<SDValue, 8> Ops;
7845 Ops.push_back(LoMul->getOperand(0));
7846 Ops.push_back(LoMul->getOperand(1));
7847 Ops.push_back(*LowAdd);
7848 Ops.push_back(*HiAdd);
7850 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7851 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7853 // Replace the ADDs' nodes uses by the MLA node's values.
7854 SDValue HiMLALResult(MLALNode.getNode(), 1);
7855 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7857 SDValue LoMLALResult(MLALNode.getNode(), 0);
7858 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7860 // Return original node to notify the driver to stop replacing.
7861 SDValue resNode(AddcNode, 0);
7865 /// PerformADDCCombine - Target-specific dag combine transform from
7866 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7867 static SDValue PerformADDCCombine(SDNode *N,
7868 TargetLowering::DAGCombinerInfo &DCI,
7869 const ARMSubtarget *Subtarget) {
7871 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7875 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7876 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7877 /// called with the default operands, and if that fails, with commuted
7879 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7880 TargetLowering::DAGCombinerInfo &DCI,
7881 const ARMSubtarget *Subtarget){
7883 // Attempt to create vpaddl for this add.
7884 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7885 if (Result.getNode())
7888 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7889 if (N0.getNode()->hasOneUse()) {
7890 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7891 if (Result.getNode()) return Result;
7896 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7898 static SDValue PerformADDCombine(SDNode *N,
7899 TargetLowering::DAGCombinerInfo &DCI,
7900 const ARMSubtarget *Subtarget) {
7901 SDValue N0 = N->getOperand(0);
7902 SDValue N1 = N->getOperand(1);
7904 // First try with the default operand order.
7905 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7906 if (Result.getNode())
7909 // If that didn't work, try again with the operands commuted.
7910 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7913 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7915 static SDValue PerformSUBCombine(SDNode *N,
7916 TargetLowering::DAGCombinerInfo &DCI) {
7917 SDValue N0 = N->getOperand(0);
7918 SDValue N1 = N->getOperand(1);
7920 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7921 if (N1.getNode()->hasOneUse()) {
7922 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7923 if (Result.getNode()) return Result;
7929 /// PerformVMULCombine
7930 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7931 /// special multiplier accumulator forwarding.
7937 // However, for (A + B) * (A + B),
7944 static SDValue PerformVMULCombine(SDNode *N,
7945 TargetLowering::DAGCombinerInfo &DCI,
7946 const ARMSubtarget *Subtarget) {
7947 if (!Subtarget->hasVMLxForwarding())
7950 SelectionDAG &DAG = DCI.DAG;
7951 SDValue N0 = N->getOperand(0);
7952 SDValue N1 = N->getOperand(1);
7953 unsigned Opcode = N0.getOpcode();
7954 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7955 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7956 Opcode = N1.getOpcode();
7957 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7958 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7966 EVT VT = N->getValueType(0);
7968 SDValue N00 = N0->getOperand(0);
7969 SDValue N01 = N0->getOperand(1);
7970 return DAG.getNode(Opcode, DL, VT,
7971 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7972 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7975 static SDValue PerformMULCombine(SDNode *N,
7976 TargetLowering::DAGCombinerInfo &DCI,
7977 const ARMSubtarget *Subtarget) {
7978 SelectionDAG &DAG = DCI.DAG;
7980 if (Subtarget->isThumb1Only())
7983 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7986 EVT VT = N->getValueType(0);
7987 if (VT.is64BitVector() || VT.is128BitVector())
7988 return PerformVMULCombine(N, DCI, Subtarget);
7992 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7996 int64_t MulAmt = C->getSExtValue();
7997 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7999 ShiftAmt = ShiftAmt & (32 - 1);
8000 SDValue V = N->getOperand(0);
8004 MulAmt >>= ShiftAmt;
8007 if (isPowerOf2_32(MulAmt - 1)) {
8008 // (mul x, 2^N + 1) => (add (shl x, N), x)
8009 Res = DAG.getNode(ISD::ADD, DL, VT,
8011 DAG.getNode(ISD::SHL, DL, VT,
8013 DAG.getConstant(Log2_32(MulAmt - 1),
8015 } else if (isPowerOf2_32(MulAmt + 1)) {
8016 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8017 Res = DAG.getNode(ISD::SUB, DL, VT,
8018 DAG.getNode(ISD::SHL, DL, VT,
8020 DAG.getConstant(Log2_32(MulAmt + 1),
8026 uint64_t MulAmtAbs = -MulAmt;
8027 if (isPowerOf2_32(MulAmtAbs + 1)) {
8028 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8029 Res = DAG.getNode(ISD::SUB, DL, VT,
8031 DAG.getNode(ISD::SHL, DL, VT,
8033 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8035 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8036 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8037 Res = DAG.getNode(ISD::ADD, DL, VT,
8039 DAG.getNode(ISD::SHL, DL, VT,
8041 DAG.getConstant(Log2_32(MulAmtAbs-1),
8043 Res = DAG.getNode(ISD::SUB, DL, VT,
8044 DAG.getConstant(0, MVT::i32),Res);
8051 Res = DAG.getNode(ISD::SHL, DL, VT,
8052 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8054 // Do not add new nodes to DAG combiner worklist.
8055 DCI.CombineTo(N, Res, false);
8059 static SDValue PerformANDCombine(SDNode *N,
8060 TargetLowering::DAGCombinerInfo &DCI,
8061 const ARMSubtarget *Subtarget) {
8063 // Attempt to use immediate-form VBIC
8064 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8066 EVT VT = N->getValueType(0);
8067 SelectionDAG &DAG = DCI.DAG;
8069 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8072 APInt SplatBits, SplatUndef;
8073 unsigned SplatBitSize;
8076 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8077 if (SplatBitSize <= 64) {
8079 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8080 SplatUndef.getZExtValue(), SplatBitSize,
8081 DAG, VbicVT, VT.is128BitVector(),
8083 if (Val.getNode()) {
8085 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8086 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8087 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8092 if (!Subtarget->isThumb1Only()) {
8093 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8094 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8095 if (Result.getNode())
8102 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8103 static SDValue PerformORCombine(SDNode *N,
8104 TargetLowering::DAGCombinerInfo &DCI,
8105 const ARMSubtarget *Subtarget) {
8106 // Attempt to use immediate-form VORR
8107 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8109 EVT VT = N->getValueType(0);
8110 SelectionDAG &DAG = DCI.DAG;
8112 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8115 APInt SplatBits, SplatUndef;
8116 unsigned SplatBitSize;
8118 if (BVN && Subtarget->hasNEON() &&
8119 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8120 if (SplatBitSize <= 64) {
8122 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8123 SplatUndef.getZExtValue(), SplatBitSize,
8124 DAG, VorrVT, VT.is128BitVector(),
8126 if (Val.getNode()) {
8128 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8129 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8130 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8135 if (!Subtarget->isThumb1Only()) {
8136 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8137 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8138 if (Result.getNode())
8142 // The code below optimizes (or (and X, Y), Z).
8143 // The AND operand needs to have a single user to make these optimizations
8145 SDValue N0 = N->getOperand(0);
8146 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8148 SDValue N1 = N->getOperand(1);
8150 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8151 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8152 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8154 unsigned SplatBitSize;
8157 APInt SplatBits0, SplatBits1;
8158 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8159 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8160 // Ensure that the second operand of both ands are constants
8161 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8162 HasAnyUndefs) && !HasAnyUndefs) {
8163 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8164 HasAnyUndefs) && !HasAnyUndefs) {
8165 // Ensure that the bit width of the constants are the same and that
8166 // the splat arguments are logical inverses as per the pattern we
8167 // are trying to simplify.
8168 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8169 SplatBits0 == ~SplatBits1) {
8170 // Canonicalize the vector type to make instruction selection
8172 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8173 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8177 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8183 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8186 // BFI is only available on V6T2+
8187 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8191 // 1) or (and A, mask), val => ARMbfi A, val, mask
8192 // iff (val & mask) == val
8194 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8195 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8196 // && mask == ~mask2
8197 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8198 // && ~mask == mask2
8199 // (i.e., copy a bitfield value into another bitfield of the same width)
8204 SDValue N00 = N0.getOperand(0);
8206 // The value and the mask need to be constants so we can verify this is
8207 // actually a bitfield set. If the mask is 0xffff, we can do better
8208 // via a movt instruction, so don't use BFI in that case.
8209 SDValue MaskOp = N0.getOperand(1);
8210 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8213 unsigned Mask = MaskC->getZExtValue();
8217 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8218 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8220 unsigned Val = N1C->getZExtValue();
8221 if ((Val & ~Mask) != Val)
8224 if (ARM::isBitFieldInvertedMask(Mask)) {
8225 Val >>= countTrailingZeros(~Mask);
8227 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8228 DAG.getConstant(Val, MVT::i32),
8229 DAG.getConstant(Mask, MVT::i32));
8231 // Do not add new nodes to DAG combiner worklist.
8232 DCI.CombineTo(N, Res, false);
8235 } else if (N1.getOpcode() == ISD::AND) {
8236 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8237 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8240 unsigned Mask2 = N11C->getZExtValue();
8242 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8244 if (ARM::isBitFieldInvertedMask(Mask) &&
8246 // The pack halfword instruction works better for masks that fit it,
8247 // so use that when it's available.
8248 if (Subtarget->hasT2ExtractPack() &&
8249 (Mask == 0xffff || Mask == 0xffff0000))
8252 unsigned amt = countTrailingZeros(Mask2);
8253 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8254 DAG.getConstant(amt, MVT::i32));
8255 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8256 DAG.getConstant(Mask, MVT::i32));
8257 // Do not add new nodes to DAG combiner worklist.
8258 DCI.CombineTo(N, Res, false);
8260 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8262 // The pack halfword instruction works better for masks that fit it,
8263 // so use that when it's available.
8264 if (Subtarget->hasT2ExtractPack() &&
8265 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8268 unsigned lsb = countTrailingZeros(Mask);
8269 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8270 DAG.getConstant(lsb, MVT::i32));
8271 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8272 DAG.getConstant(Mask2, MVT::i32));
8273 // Do not add new nodes to DAG combiner worklist.
8274 DCI.CombineTo(N, Res, false);
8279 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8280 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8281 ARM::isBitFieldInvertedMask(~Mask)) {
8282 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8283 // where lsb(mask) == #shamt and masked bits of B are known zero.
8284 SDValue ShAmt = N00.getOperand(1);
8285 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8286 unsigned LSB = countTrailingZeros(Mask);
8290 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8291 DAG.getConstant(~Mask, MVT::i32));
8293 // Do not add new nodes to DAG combiner worklist.
8294 DCI.CombineTo(N, Res, false);
8300 static SDValue PerformXORCombine(SDNode *N,
8301 TargetLowering::DAGCombinerInfo &DCI,
8302 const ARMSubtarget *Subtarget) {
8303 EVT VT = N->getValueType(0);
8304 SelectionDAG &DAG = DCI.DAG;
8306 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8309 if (!Subtarget->isThumb1Only()) {
8310 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8311 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8312 if (Result.getNode())
8319 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8320 /// the bits being cleared by the AND are not demanded by the BFI.
8321 static SDValue PerformBFICombine(SDNode *N,
8322 TargetLowering::DAGCombinerInfo &DCI) {
8323 SDValue N1 = N->getOperand(1);
8324 if (N1.getOpcode() == ISD::AND) {
8325 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8328 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8329 unsigned LSB = countTrailingZeros(~InvMask);
8330 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8331 unsigned Mask = (1 << Width)-1;
8332 unsigned Mask2 = N11C->getZExtValue();
8333 if ((Mask & (~Mask2)) == 0)
8334 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8335 N->getOperand(0), N1.getOperand(0),
8341 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8342 /// ARMISD::VMOVRRD.
8343 static SDValue PerformVMOVRRDCombine(SDNode *N,
8344 TargetLowering::DAGCombinerInfo &DCI) {
8345 // vmovrrd(vmovdrr x, y) -> x,y
8346 SDValue InDouble = N->getOperand(0);
8347 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8348 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8350 // vmovrrd(load f64) -> (load i32), (load i32)
8351 SDNode *InNode = InDouble.getNode();
8352 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8353 InNode->getValueType(0) == MVT::f64 &&
8354 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8355 !cast<LoadSDNode>(InNode)->isVolatile()) {
8356 // TODO: Should this be done for non-FrameIndex operands?
8357 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8359 SelectionDAG &DAG = DCI.DAG;
8361 SDValue BasePtr = LD->getBasePtr();
8362 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8363 LD->getPointerInfo(), LD->isVolatile(),
8364 LD->isNonTemporal(), LD->isInvariant(),
8365 LD->getAlignment());
8367 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8368 DAG.getConstant(4, MVT::i32));
8369 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8370 LD->getPointerInfo(), LD->isVolatile(),
8371 LD->isNonTemporal(), LD->isInvariant(),
8372 std::min(4U, LD->getAlignment() / 2));
8374 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8375 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8376 DCI.RemoveFromWorklist(LD);
8384 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8385 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8386 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8387 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8388 SDValue Op0 = N->getOperand(0);
8389 SDValue Op1 = N->getOperand(1);
8390 if (Op0.getOpcode() == ISD::BITCAST)
8391 Op0 = Op0.getOperand(0);
8392 if (Op1.getOpcode() == ISD::BITCAST)
8393 Op1 = Op1.getOperand(0);
8394 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8395 Op0.getNode() == Op1.getNode() &&
8396 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8397 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8398 N->getValueType(0), Op0.getOperand(0));
8402 /// PerformSTORECombine - Target-specific dag combine xforms for
8404 static SDValue PerformSTORECombine(SDNode *N,
8405 TargetLowering::DAGCombinerInfo &DCI) {
8406 StoreSDNode *St = cast<StoreSDNode>(N);
8407 if (St->isVolatile())
8410 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8411 // pack all of the elements in one place. Next, store to memory in fewer
8413 SDValue StVal = St->getValue();
8414 EVT VT = StVal.getValueType();
8415 if (St->isTruncatingStore() && VT.isVector()) {
8416 SelectionDAG &DAG = DCI.DAG;
8417 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8418 EVT StVT = St->getMemoryVT();
8419 unsigned NumElems = VT.getVectorNumElements();
8420 assert(StVT != VT && "Cannot truncate to the same type");
8421 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8422 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8424 // From, To sizes and ElemCount must be pow of two
8425 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8427 // We are going to use the original vector elt for storing.
8428 // Accumulated smaller vector elements must be a multiple of the store size.
8429 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8431 unsigned SizeRatio = FromEltSz / ToEltSz;
8432 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8434 // Create a type on which we perform the shuffle.
8435 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8436 NumElems*SizeRatio);
8437 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8440 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8441 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8442 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8444 // Can't shuffle using an illegal type.
8445 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8447 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8448 DAG.getUNDEF(WideVec.getValueType()),
8450 // At this point all of the data is stored at the bottom of the
8451 // register. We now need to save it to mem.
8453 // Find the largest store unit
8454 MVT StoreType = MVT::i8;
8455 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8456 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8457 MVT Tp = (MVT::SimpleValueType)tp;
8458 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8461 // Didn't find a legal store type.
8462 if (!TLI.isTypeLegal(StoreType))
8465 // Bitcast the original vector into a vector of store-size units
8466 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8467 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8468 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8469 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8470 SmallVector<SDValue, 8> Chains;
8471 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8472 TLI.getPointerTy());
8473 SDValue BasePtr = St->getBasePtr();
8475 // Perform one or more big stores into memory.
8476 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8477 for (unsigned I = 0; I < E; I++) {
8478 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8479 StoreType, ShuffWide,
8480 DAG.getIntPtrConstant(I));
8481 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8482 St->getPointerInfo(), St->isVolatile(),
8483 St->isNonTemporal(), St->getAlignment());
8484 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8486 Chains.push_back(Ch);
8488 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8491 if (!ISD::isNormalStore(St))
8494 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8495 // ARM stores of arguments in the same cache line.
8496 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8497 StVal.getNode()->hasOneUse()) {
8498 SelectionDAG &DAG = DCI.DAG;
8499 bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8501 SDValue BasePtr = St->getBasePtr();
8502 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8503 StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8504 BasePtr, St->getPointerInfo(), St->isVolatile(),
8505 St->isNonTemporal(), St->getAlignment());
8507 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8508 DAG.getConstant(4, MVT::i32));
8509 return DAG.getStore(NewST1.getValue(0), DL,
8510 StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8511 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8512 St->isNonTemporal(),
8513 std::min(4U, St->getAlignment() / 2));
8516 if (StVal.getValueType() != MVT::i64 ||
8517 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8520 // Bitcast an i64 store extracted from a vector to f64.
8521 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8522 SelectionDAG &DAG = DCI.DAG;
8524 SDValue IntVec = StVal.getOperand(0);
8525 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8526 IntVec.getValueType().getVectorNumElements());
8527 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8528 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8529 Vec, StVal.getOperand(1));
8531 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8532 // Make the DAGCombiner fold the bitcasts.
8533 DCI.AddToWorklist(Vec.getNode());
8534 DCI.AddToWorklist(ExtElt.getNode());
8535 DCI.AddToWorklist(V.getNode());
8536 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8537 St->getPointerInfo(), St->isVolatile(),
8538 St->isNonTemporal(), St->getAlignment(),
8542 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8543 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8544 /// i64 vector to have f64 elements, since the value can then be loaded
8545 /// directly into a VFP register.
8546 static bool hasNormalLoadOperand(SDNode *N) {
8547 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8548 for (unsigned i = 0; i < NumElts; ++i) {
8549 SDNode *Elt = N->getOperand(i).getNode();
8550 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8556 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8557 /// ISD::BUILD_VECTOR.
8558 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8559 TargetLowering::DAGCombinerInfo &DCI){
8560 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8561 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8562 // into a pair of GPRs, which is fine when the value is used as a scalar,
8563 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8564 SelectionDAG &DAG = DCI.DAG;
8565 if (N->getNumOperands() == 2) {
8566 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8571 // Load i64 elements as f64 values so that type legalization does not split
8572 // them up into i32 values.
8573 EVT VT = N->getValueType(0);
8574 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8577 SmallVector<SDValue, 8> Ops;
8578 unsigned NumElts = VT.getVectorNumElements();
8579 for (unsigned i = 0; i < NumElts; ++i) {
8580 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8582 // Make the DAGCombiner fold the bitcast.
8583 DCI.AddToWorklist(V.getNode());
8585 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8586 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8587 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8590 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8592 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8593 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8594 // At that time, we may have inserted bitcasts from integer to float.
8595 // If these bitcasts have survived DAGCombine, change the lowering of this
8596 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8597 // force to use floating point types.
8599 // Make sure we can change the type of the vector.
8600 // This is possible iff:
8601 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8602 // 1.1. Vector is used only once.
8603 // 1.2. Use is a bit convert to an integer type.
8604 // 2. The size of its operands are 32-bits (64-bits are not legal).
8605 EVT VT = N->getValueType(0);
8606 EVT EltVT = VT.getVectorElementType();
8608 // Check 1.1. and 2.
8609 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8612 // By construction, the input type must be float.
8613 assert(EltVT == MVT::f32 && "Unexpected type!");
8616 SDNode *Use = *N->use_begin();
8617 if (Use->getOpcode() != ISD::BITCAST ||
8618 Use->getValueType(0).isFloatingPoint())
8621 // Check profitability.
8622 // Model is, if more than half of the relevant operands are bitcast from
8623 // i32, turn the build_vector into a sequence of insert_vector_elt.
8624 // Relevant operands are everything that is not statically
8625 // (i.e., at compile time) bitcasted.
8626 unsigned NumOfBitCastedElts = 0;
8627 unsigned NumElts = VT.getVectorNumElements();
8628 unsigned NumOfRelevantElts = NumElts;
8629 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8630 SDValue Elt = N->getOperand(Idx);
8631 if (Elt->getOpcode() == ISD::BITCAST) {
8632 // Assume only bit cast to i32 will go away.
8633 if (Elt->getOperand(0).getValueType() == MVT::i32)
8634 ++NumOfBitCastedElts;
8635 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8636 // Constants are statically casted, thus do not count them as
8637 // relevant operands.
8638 --NumOfRelevantElts;
8641 // Check if more than half of the elements require a non-free bitcast.
8642 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8645 SelectionDAG &DAG = DCI.DAG;
8646 // Create the new vector type.
8647 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8648 // Check if the type is legal.
8649 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8650 if (!TLI.isTypeLegal(VecVT))
8654 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8655 // => BITCAST INSERT_VECTOR_ELT
8656 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8658 SDValue Vec = DAG.getUNDEF(VecVT);
8660 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8661 SDValue V = N->getOperand(Idx);
8662 if (V.getOpcode() == ISD::UNDEF)
8664 if (V.getOpcode() == ISD::BITCAST &&
8665 V->getOperand(0).getValueType() == MVT::i32)
8666 // Fold obvious case.
8667 V = V.getOperand(0);
8669 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8670 // Make the DAGCombiner fold the bitcasts.
8671 DCI.AddToWorklist(V.getNode());
8673 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8674 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8676 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8677 // Make the DAGCombiner fold the bitcasts.
8678 DCI.AddToWorklist(Vec.getNode());
8682 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8683 /// ISD::INSERT_VECTOR_ELT.
8684 static SDValue PerformInsertEltCombine(SDNode *N,
8685 TargetLowering::DAGCombinerInfo &DCI) {
8686 // Bitcast an i64 load inserted into a vector to f64.
8687 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8688 EVT VT = N->getValueType(0);
8689 SDNode *Elt = N->getOperand(1).getNode();
8690 if (VT.getVectorElementType() != MVT::i64 ||
8691 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8694 SelectionDAG &DAG = DCI.DAG;
8696 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8697 VT.getVectorNumElements());
8698 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8699 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8700 // Make the DAGCombiner fold the bitcasts.
8701 DCI.AddToWorklist(Vec.getNode());
8702 DCI.AddToWorklist(V.getNode());
8703 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8704 Vec, V, N->getOperand(2));
8705 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8708 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8709 /// ISD::VECTOR_SHUFFLE.
8710 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8711 // The LLVM shufflevector instruction does not require the shuffle mask
8712 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8713 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8714 // operands do not match the mask length, they are extended by concatenating
8715 // them with undef vectors. That is probably the right thing for other
8716 // targets, but for NEON it is better to concatenate two double-register
8717 // size vector operands into a single quad-register size vector. Do that
8718 // transformation here:
8719 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8720 // shuffle(concat(v1, v2), undef)
8721 SDValue Op0 = N->getOperand(0);
8722 SDValue Op1 = N->getOperand(1);
8723 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8724 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8725 Op0.getNumOperands() != 2 ||
8726 Op1.getNumOperands() != 2)
8728 SDValue Concat0Op1 = Op0.getOperand(1);
8729 SDValue Concat1Op1 = Op1.getOperand(1);
8730 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8731 Concat1Op1.getOpcode() != ISD::UNDEF)
8733 // Skip the transformation if any of the types are illegal.
8734 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8735 EVT VT = N->getValueType(0);
8736 if (!TLI.isTypeLegal(VT) ||
8737 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8738 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8741 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8742 Op0.getOperand(0), Op1.getOperand(0));
8743 // Translate the shuffle mask.
8744 SmallVector<int, 16> NewMask;
8745 unsigned NumElts = VT.getVectorNumElements();
8746 unsigned HalfElts = NumElts/2;
8747 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8748 for (unsigned n = 0; n < NumElts; ++n) {
8749 int MaskElt = SVN->getMaskElt(n);
8751 if (MaskElt < (int)HalfElts)
8753 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8754 NewElt = HalfElts + MaskElt - NumElts;
8755 NewMask.push_back(NewElt);
8757 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8758 DAG.getUNDEF(VT), NewMask.data());
8761 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8762 /// NEON load/store intrinsics to merge base address updates.
8763 static SDValue CombineBaseUpdate(SDNode *N,
8764 TargetLowering::DAGCombinerInfo &DCI) {
8765 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8768 SelectionDAG &DAG = DCI.DAG;
8769 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8770 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8771 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8772 SDValue Addr = N->getOperand(AddrOpIdx);
8774 // Search for a use of the address operand that is an increment.
8775 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8776 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8778 if (User->getOpcode() != ISD::ADD ||
8779 UI.getUse().getResNo() != Addr.getResNo())
8782 // Check that the add is independent of the load/store. Otherwise, folding
8783 // it would create a cycle.
8784 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8787 // Find the new opcode for the updating load/store.
8789 bool isLaneOp = false;
8790 unsigned NewOpc = 0;
8791 unsigned NumVecs = 0;
8793 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8795 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8796 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8798 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8800 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8802 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8804 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8805 NumVecs = 2; isLaneOp = true; break;
8806 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8807 NumVecs = 3; isLaneOp = true; break;
8808 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8809 NumVecs = 4; isLaneOp = true; break;
8810 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8811 NumVecs = 1; isLoad = false; break;
8812 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8813 NumVecs = 2; isLoad = false; break;
8814 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8815 NumVecs = 3; isLoad = false; break;
8816 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8817 NumVecs = 4; isLoad = false; break;
8818 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8819 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8820 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8821 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8822 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8823 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8827 switch (N->getOpcode()) {
8828 default: llvm_unreachable("unexpected opcode for Neon base update");
8829 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8830 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8831 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8835 // Find the size of memory referenced by the load/store.
8838 VecTy = N->getValueType(0);
8840 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8841 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8843 NumBytes /= VecTy.getVectorNumElements();
8845 // If the increment is a constant, it must match the memory ref size.
8846 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8847 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8848 uint64_t IncVal = CInc->getZExtValue();
8849 if (IncVal != NumBytes)
8851 } else if (NumBytes >= 3 * 16) {
8852 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8853 // separate instructions that make it harder to use a non-constant update.
8857 // Create the new updating load/store node.
8859 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8861 for (n = 0; n < NumResultVecs; ++n)
8863 Tys[n++] = MVT::i32;
8864 Tys[n] = MVT::Other;
8865 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8866 SmallVector<SDValue, 8> Ops;
8867 Ops.push_back(N->getOperand(0)); // incoming chain
8868 Ops.push_back(N->getOperand(AddrOpIdx));
8870 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8871 Ops.push_back(N->getOperand(i));
8873 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8874 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8875 Ops, MemInt->getMemoryVT(),
8876 MemInt->getMemOperand());
8879 std::vector<SDValue> NewResults;
8880 for (unsigned i = 0; i < NumResultVecs; ++i) {
8881 NewResults.push_back(SDValue(UpdN.getNode(), i));
8883 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8884 DCI.CombineTo(N, NewResults);
8885 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8892 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8893 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8894 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8896 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8897 SelectionDAG &DAG = DCI.DAG;
8898 EVT VT = N->getValueType(0);
8899 // vldN-dup instructions only support 64-bit vectors for N > 1.
8900 if (!VT.is64BitVector())
8903 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8904 SDNode *VLD = N->getOperand(0).getNode();
8905 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8907 unsigned NumVecs = 0;
8908 unsigned NewOpc = 0;
8909 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8910 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8912 NewOpc = ARMISD::VLD2DUP;
8913 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8915 NewOpc = ARMISD::VLD3DUP;
8916 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8918 NewOpc = ARMISD::VLD4DUP;
8923 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8924 // numbers match the load.
8925 unsigned VLDLaneNo =
8926 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8927 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8929 // Ignore uses of the chain result.
8930 if (UI.getUse().getResNo() == NumVecs)
8933 if (User->getOpcode() != ARMISD::VDUPLANE ||
8934 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8938 // Create the vldN-dup node.
8941 for (n = 0; n < NumVecs; ++n)
8943 Tys[n] = MVT::Other;
8944 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8945 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8946 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8947 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8948 Ops, VLDMemInt->getMemoryVT(),
8949 VLDMemInt->getMemOperand());
8952 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8954 unsigned ResNo = UI.getUse().getResNo();
8955 // Ignore uses of the chain result.
8956 if (ResNo == NumVecs)
8959 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8962 // Now the vldN-lane intrinsic is dead except for its chain result.
8963 // Update uses of the chain.
8964 std::vector<SDValue> VLDDupResults;
8965 for (unsigned n = 0; n < NumVecs; ++n)
8966 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8967 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8968 DCI.CombineTo(VLD, VLDDupResults);
8973 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8974 /// ARMISD::VDUPLANE.
8975 static SDValue PerformVDUPLANECombine(SDNode *N,
8976 TargetLowering::DAGCombinerInfo &DCI) {
8977 SDValue Op = N->getOperand(0);
8979 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8980 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8981 if (CombineVLDDUP(N, DCI))
8982 return SDValue(N, 0);
8984 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8985 // redundant. Ignore bit_converts for now; element sizes are checked below.
8986 while (Op.getOpcode() == ISD::BITCAST)
8987 Op = Op.getOperand(0);
8988 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8991 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8992 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8993 // The canonical VMOV for a zero vector uses a 32-bit element size.
8994 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8996 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8998 EVT VT = N->getValueType(0);
8999 if (EltSize > VT.getVectorElementType().getSizeInBits())
9002 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9005 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9006 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9007 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9011 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9013 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9018 APFloat APF = C->getValueAPF();
9019 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9020 != APFloat::opOK || !isExact)
9023 c0 = (I == 0) ? cN : c0;
9024 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9031 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9032 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9033 /// when the VMUL has a constant operand that is a power of 2.
9035 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9036 /// vmul.f32 d16, d17, d16
9037 /// vcvt.s32.f32 d16, d16
9039 /// vcvt.s32.f32 d16, d16, #3
9040 static SDValue PerformVCVTCombine(SDNode *N,
9041 TargetLowering::DAGCombinerInfo &DCI,
9042 const ARMSubtarget *Subtarget) {
9043 SelectionDAG &DAG = DCI.DAG;
9044 SDValue Op = N->getOperand(0);
9046 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9047 Op.getOpcode() != ISD::FMUL)
9051 SDValue N0 = Op->getOperand(0);
9052 SDValue ConstVec = Op->getOperand(1);
9053 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9055 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9056 !isConstVecPow2(ConstVec, isSigned, C))
9059 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9060 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9061 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9062 // These instructions only exist converting from f32 to i32. We can handle
9063 // smaller integers by generating an extra truncate, but larger ones would
9068 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9069 Intrinsic::arm_neon_vcvtfp2fxu;
9070 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9071 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9072 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9073 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9074 DAG.getConstant(Log2_64(C), MVT::i32));
9076 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9077 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9082 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9083 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9084 /// when the VDIV has a constant operand that is a power of 2.
9086 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9087 /// vcvt.f32.s32 d16, d16
9088 /// vdiv.f32 d16, d17, d16
9090 /// vcvt.f32.s32 d16, d16, #3
9091 static SDValue PerformVDIVCombine(SDNode *N,
9092 TargetLowering::DAGCombinerInfo &DCI,
9093 const ARMSubtarget *Subtarget) {
9094 SelectionDAG &DAG = DCI.DAG;
9095 SDValue Op = N->getOperand(0);
9096 unsigned OpOpcode = Op.getNode()->getOpcode();
9098 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9099 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9103 SDValue ConstVec = N->getOperand(1);
9104 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9106 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9107 !isConstVecPow2(ConstVec, isSigned, C))
9110 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9111 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9112 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9113 // These instructions only exist converting from i32 to f32. We can handle
9114 // smaller integers by generating an extra extend, but larger ones would
9119 SDValue ConvInput = Op.getOperand(0);
9120 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9121 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9122 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9123 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9126 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9127 Intrinsic::arm_neon_vcvtfxu2fp;
9128 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9130 DAG.getConstant(IntrinsicOpcode, MVT::i32),
9131 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9134 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9135 /// operand of a vector shift operation, where all the elements of the
9136 /// build_vector must have the same constant integer value.
9137 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9138 // Ignore bit_converts.
9139 while (Op.getOpcode() == ISD::BITCAST)
9140 Op = Op.getOperand(0);
9141 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9142 APInt SplatBits, SplatUndef;
9143 unsigned SplatBitSize;
9145 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9146 HasAnyUndefs, ElementBits) ||
9147 SplatBitSize > ElementBits)
9149 Cnt = SplatBits.getSExtValue();
9153 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9154 /// operand of a vector shift left operation. That value must be in the range:
9155 /// 0 <= Value < ElementBits for a left shift; or
9156 /// 0 <= Value <= ElementBits for a long left shift.
9157 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9158 assert(VT.isVector() && "vector shift count is not a vector type");
9159 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9160 if (! getVShiftImm(Op, ElementBits, Cnt))
9162 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9165 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9166 /// operand of a vector shift right operation. For a shift opcode, the value
9167 /// is positive, but for an intrinsic the value count must be negative. The
9168 /// absolute value must be in the range:
9169 /// 1 <= |Value| <= ElementBits for a right shift; or
9170 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
9171 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9173 assert(VT.isVector() && "vector shift count is not a vector type");
9174 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9175 if (! getVShiftImm(Op, ElementBits, Cnt))
9179 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9182 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9183 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9184 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9187 // Don't do anything for most intrinsics.
9190 // Vector shifts: check for immediate versions and lower them.
9191 // Note: This is done during DAG combining instead of DAG legalizing because
9192 // the build_vectors for 64-bit vector element shift counts are generally
9193 // not legal, and it is hard to see their values after they get legalized to
9194 // loads from a constant pool.
9195 case Intrinsic::arm_neon_vshifts:
9196 case Intrinsic::arm_neon_vshiftu:
9197 case Intrinsic::arm_neon_vrshifts:
9198 case Intrinsic::arm_neon_vrshiftu:
9199 case Intrinsic::arm_neon_vrshiftn:
9200 case Intrinsic::arm_neon_vqshifts:
9201 case Intrinsic::arm_neon_vqshiftu:
9202 case Intrinsic::arm_neon_vqshiftsu:
9203 case Intrinsic::arm_neon_vqshiftns:
9204 case Intrinsic::arm_neon_vqshiftnu:
9205 case Intrinsic::arm_neon_vqshiftnsu:
9206 case Intrinsic::arm_neon_vqrshiftns:
9207 case Intrinsic::arm_neon_vqrshiftnu:
9208 case Intrinsic::arm_neon_vqrshiftnsu: {
9209 EVT VT = N->getOperand(1).getValueType();
9211 unsigned VShiftOpc = 0;
9214 case Intrinsic::arm_neon_vshifts:
9215 case Intrinsic::arm_neon_vshiftu:
9216 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9217 VShiftOpc = ARMISD::VSHL;
9220 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9221 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9222 ARMISD::VSHRs : ARMISD::VSHRu);
9227 case Intrinsic::arm_neon_vrshifts:
9228 case Intrinsic::arm_neon_vrshiftu:
9229 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9233 case Intrinsic::arm_neon_vqshifts:
9234 case Intrinsic::arm_neon_vqshiftu:
9235 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9239 case Intrinsic::arm_neon_vqshiftsu:
9240 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9242 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9244 case Intrinsic::arm_neon_vrshiftn:
9245 case Intrinsic::arm_neon_vqshiftns:
9246 case Intrinsic::arm_neon_vqshiftnu:
9247 case Intrinsic::arm_neon_vqshiftnsu:
9248 case Intrinsic::arm_neon_vqrshiftns:
9249 case Intrinsic::arm_neon_vqrshiftnu:
9250 case Intrinsic::arm_neon_vqrshiftnsu:
9251 // Narrowing shifts require an immediate right shift.
9252 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9254 llvm_unreachable("invalid shift count for narrowing vector shift "
9258 llvm_unreachable("unhandled vector shift");
9262 case Intrinsic::arm_neon_vshifts:
9263 case Intrinsic::arm_neon_vshiftu:
9264 // Opcode already set above.
9266 case Intrinsic::arm_neon_vrshifts:
9267 VShiftOpc = ARMISD::VRSHRs; break;
9268 case Intrinsic::arm_neon_vrshiftu:
9269 VShiftOpc = ARMISD::VRSHRu; break;
9270 case Intrinsic::arm_neon_vrshiftn:
9271 VShiftOpc = ARMISD::VRSHRN; break;
9272 case Intrinsic::arm_neon_vqshifts:
9273 VShiftOpc = ARMISD::VQSHLs; break;
9274 case Intrinsic::arm_neon_vqshiftu:
9275 VShiftOpc = ARMISD::VQSHLu; break;
9276 case Intrinsic::arm_neon_vqshiftsu:
9277 VShiftOpc = ARMISD::VQSHLsu; break;
9278 case Intrinsic::arm_neon_vqshiftns:
9279 VShiftOpc = ARMISD::VQSHRNs; break;
9280 case Intrinsic::arm_neon_vqshiftnu:
9281 VShiftOpc = ARMISD::VQSHRNu; break;
9282 case Intrinsic::arm_neon_vqshiftnsu:
9283 VShiftOpc = ARMISD::VQSHRNsu; break;
9284 case Intrinsic::arm_neon_vqrshiftns:
9285 VShiftOpc = ARMISD::VQRSHRNs; break;
9286 case Intrinsic::arm_neon_vqrshiftnu:
9287 VShiftOpc = ARMISD::VQRSHRNu; break;
9288 case Intrinsic::arm_neon_vqrshiftnsu:
9289 VShiftOpc = ARMISD::VQRSHRNsu; break;
9292 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9293 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9296 case Intrinsic::arm_neon_vshiftins: {
9297 EVT VT = N->getOperand(1).getValueType();
9299 unsigned VShiftOpc = 0;
9301 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9302 VShiftOpc = ARMISD::VSLI;
9303 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9304 VShiftOpc = ARMISD::VSRI;
9306 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9309 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9310 N->getOperand(1), N->getOperand(2),
9311 DAG.getConstant(Cnt, MVT::i32));
9314 case Intrinsic::arm_neon_vqrshifts:
9315 case Intrinsic::arm_neon_vqrshiftu:
9316 // No immediate versions of these to check for.
9323 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9324 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9325 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9326 /// vector element shift counts are generally not legal, and it is hard to see
9327 /// their values after they get legalized to loads from a constant pool.
9328 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9329 const ARMSubtarget *ST) {
9330 EVT VT = N->getValueType(0);
9331 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9332 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9333 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9334 SDValue N1 = N->getOperand(1);
9335 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9336 SDValue N0 = N->getOperand(0);
9337 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9338 DAG.MaskedValueIsZero(N0.getOperand(0),
9339 APInt::getHighBitsSet(32, 16)))
9340 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9344 // Nothing to be done for scalar shifts.
9345 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9346 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9349 assert(ST->hasNEON() && "unexpected vector shift");
9352 switch (N->getOpcode()) {
9353 default: llvm_unreachable("unexpected shift opcode");
9356 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9357 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9358 DAG.getConstant(Cnt, MVT::i32));
9363 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9364 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9365 ARMISD::VSHRs : ARMISD::VSHRu);
9366 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9367 DAG.getConstant(Cnt, MVT::i32));
9373 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9374 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9375 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9376 const ARMSubtarget *ST) {
9377 SDValue N0 = N->getOperand(0);
9379 // Check for sign- and zero-extensions of vector extract operations of 8-
9380 // and 16-bit vector elements. NEON supports these directly. They are
9381 // handled during DAG combining because type legalization will promote them
9382 // to 32-bit types and it is messy to recognize the operations after that.
9383 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9384 SDValue Vec = N0.getOperand(0);
9385 SDValue Lane = N0.getOperand(1);
9386 EVT VT = N->getValueType(0);
9387 EVT EltVT = N0.getValueType();
9388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9390 if (VT == MVT::i32 &&
9391 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9392 TLI.isTypeLegal(Vec.getValueType()) &&
9393 isa<ConstantSDNode>(Lane)) {
9396 switch (N->getOpcode()) {
9397 default: llvm_unreachable("unexpected opcode");
9398 case ISD::SIGN_EXTEND:
9399 Opc = ARMISD::VGETLANEs;
9401 case ISD::ZERO_EXTEND:
9402 case ISD::ANY_EXTEND:
9403 Opc = ARMISD::VGETLANEu;
9406 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9413 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9414 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9415 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9416 const ARMSubtarget *ST) {
9417 // If the target supports NEON, try to use vmax/vmin instructions for f32
9418 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9419 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9420 // a NaN; only do the transformation when it matches that behavior.
9422 // For now only do this when using NEON for FP operations; if using VFP, it
9423 // is not obvious that the benefit outweighs the cost of switching to the
9425 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9426 N->getValueType(0) != MVT::f32)
9429 SDValue CondLHS = N->getOperand(0);
9430 SDValue CondRHS = N->getOperand(1);
9431 SDValue LHS = N->getOperand(2);
9432 SDValue RHS = N->getOperand(3);
9433 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9435 unsigned Opcode = 0;
9437 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9438 IsReversed = false; // x CC y ? x : y
9439 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9440 IsReversed = true ; // x CC y ? y : x
9454 // If LHS is NaN, an ordered comparison will be false and the result will
9455 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9456 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9457 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9458 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9460 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9461 // will return -0, so vmin can only be used for unsafe math or if one of
9462 // the operands is known to be nonzero.
9463 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9464 !DAG.getTarget().Options.UnsafeFPMath &&
9465 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9467 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9476 // If LHS is NaN, an ordered comparison will be false and the result will
9477 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9478 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9479 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9480 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9482 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9483 // will return +0, so vmax can only be used for unsafe math or if one of
9484 // the operands is known to be nonzero.
9485 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9486 !DAG.getTarget().Options.UnsafeFPMath &&
9487 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9489 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9495 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9498 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9500 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9501 SDValue Cmp = N->getOperand(4);
9502 if (Cmp.getOpcode() != ARMISD::CMPZ)
9503 // Only looking at EQ and NE cases.
9506 EVT VT = N->getValueType(0);
9508 SDValue LHS = Cmp.getOperand(0);
9509 SDValue RHS = Cmp.getOperand(1);
9510 SDValue FalseVal = N->getOperand(0);
9511 SDValue TrueVal = N->getOperand(1);
9512 SDValue ARMcc = N->getOperand(2);
9513 ARMCC::CondCodes CC =
9514 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9532 /// FIXME: Turn this into a target neutral optimization?
9534 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9535 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9536 N->getOperand(3), Cmp);
9537 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9539 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9540 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9541 N->getOperand(3), NewCmp);
9544 if (Res.getNode()) {
9545 APInt KnownZero, KnownOne;
9546 DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9547 // Capture demanded bits information that would be otherwise lost.
9548 if (KnownZero == 0xfffffffe)
9549 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9550 DAG.getValueType(MVT::i1));
9551 else if (KnownZero == 0xffffff00)
9552 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9553 DAG.getValueType(MVT::i8));
9554 else if (KnownZero == 0xffff0000)
9555 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9556 DAG.getValueType(MVT::i16));
9562 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9563 DAGCombinerInfo &DCI) const {
9564 switch (N->getOpcode()) {
9566 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9567 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9568 case ISD::SUB: return PerformSUBCombine(N, DCI);
9569 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9570 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9571 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9572 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9573 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9574 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9575 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9576 case ISD::STORE: return PerformSTORECombine(N, DCI);
9577 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9578 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9579 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9580 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9581 case ISD::FP_TO_SINT:
9582 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9583 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9584 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9587 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9588 case ISD::SIGN_EXTEND:
9589 case ISD::ZERO_EXTEND:
9590 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9591 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9592 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9593 case ARMISD::VLD2DUP:
9594 case ARMISD::VLD3DUP:
9595 case ARMISD::VLD4DUP:
9596 return CombineBaseUpdate(N, DCI);
9597 case ARMISD::BUILD_VECTOR:
9598 return PerformARMBUILD_VECTORCombine(N, DCI);
9599 case ISD::INTRINSIC_VOID:
9600 case ISD::INTRINSIC_W_CHAIN:
9601 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9602 case Intrinsic::arm_neon_vld1:
9603 case Intrinsic::arm_neon_vld2:
9604 case Intrinsic::arm_neon_vld3:
9605 case Intrinsic::arm_neon_vld4:
9606 case Intrinsic::arm_neon_vld2lane:
9607 case Intrinsic::arm_neon_vld3lane:
9608 case Intrinsic::arm_neon_vld4lane:
9609 case Intrinsic::arm_neon_vst1:
9610 case Intrinsic::arm_neon_vst2:
9611 case Intrinsic::arm_neon_vst3:
9612 case Intrinsic::arm_neon_vst4:
9613 case Intrinsic::arm_neon_vst2lane:
9614 case Intrinsic::arm_neon_vst3lane:
9615 case Intrinsic::arm_neon_vst4lane:
9616 return CombineBaseUpdate(N, DCI);
9624 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9626 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9629 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9631 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9632 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9634 switch (VT.getSimpleVT().SimpleTy) {
9640 // Unaligned access can use (for example) LRDB, LRDH, LDR
9641 if (AllowsUnaligned) {
9643 *Fast = Subtarget->hasV7Ops();
9650 // For any little-endian targets with neon, we can support unaligned ld/st
9651 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9652 // A big-endian target may also explicitly support unaligned accesses
9653 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9663 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9664 unsigned AlignCheck) {
9665 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9666 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9669 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9670 unsigned DstAlign, unsigned SrcAlign,
9671 bool IsMemset, bool ZeroMemset,
9673 MachineFunction &MF) const {
9674 const Function *F = MF.getFunction();
9676 // See if we can use NEON instructions for this...
9677 if ((!IsMemset || ZeroMemset) &&
9678 Subtarget->hasNEON() &&
9679 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9680 Attribute::NoImplicitFloat)) {
9683 (memOpAlign(SrcAlign, DstAlign, 16) ||
9684 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9686 } else if (Size >= 8 &&
9687 (memOpAlign(SrcAlign, DstAlign, 8) ||
9688 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9693 // Lowering to i32/i16 if the size permits.
9699 // Let the target-independent logic figure it out.
9703 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9704 if (Val.getOpcode() != ISD::LOAD)
9707 EVT VT1 = Val.getValueType();
9708 if (!VT1.isSimple() || !VT1.isInteger() ||
9709 !VT2.isSimple() || !VT2.isInteger())
9712 switch (VT1.getSimpleVT().SimpleTy) {
9717 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9724 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9725 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9728 if (!isTypeLegal(EVT::getEVT(Ty1)))
9731 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9733 // Assuming the caller doesn't have a zeroext or signext return parameter,
9734 // truncation all the way down to i1 is valid.
9739 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9744 switch (VT.getSimpleVT().SimpleTy) {
9745 default: return false;
9760 if ((V & (Scale - 1)) != 0)
9763 return V == (V & ((1LL << 5) - 1));
9766 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9767 const ARMSubtarget *Subtarget) {
9774 switch (VT.getSimpleVT().SimpleTy) {
9775 default: return false;
9780 // + imm12 or - imm8
9782 return V == (V & ((1LL << 8) - 1));
9783 return V == (V & ((1LL << 12) - 1));
9786 // Same as ARM mode. FIXME: NEON?
9787 if (!Subtarget->hasVFP2())
9792 return V == (V & ((1LL << 8) - 1));
9796 /// isLegalAddressImmediate - Return true if the integer value can be used
9797 /// as the offset of the target addressing mode for load / store of the
9799 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9800 const ARMSubtarget *Subtarget) {
9807 if (Subtarget->isThumb1Only())
9808 return isLegalT1AddressImmediate(V, VT);
9809 else if (Subtarget->isThumb2())
9810 return isLegalT2AddressImmediate(V, VT, Subtarget);
9815 switch (VT.getSimpleVT().SimpleTy) {
9816 default: return false;
9821 return V == (V & ((1LL << 12) - 1));
9824 return V == (V & ((1LL << 8) - 1));
9827 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9832 return V == (V & ((1LL << 8) - 1));
9836 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9838 int Scale = AM.Scale;
9842 switch (VT.getSimpleVT().SimpleTy) {
9843 default: return false;
9852 return Scale == 2 || Scale == 4 || Scale == 8;
9855 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9859 // Note, we allow "void" uses (basically, uses that aren't loads or
9860 // stores), because arm allows folding a scale into many arithmetic
9861 // operations. This should be made more precise and revisited later.
9863 // Allow r << imm, but the imm has to be a multiple of two.
9864 if (Scale & 1) return false;
9865 return isPowerOf2_32(Scale);
9869 /// isLegalAddressingMode - Return true if the addressing mode represented
9870 /// by AM is legal for this target, for a load/store of the specified type.
9871 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9873 EVT VT = getValueType(Ty, true);
9874 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9877 // Can never fold addr of global into load/store.
9882 case 0: // no scale reg, must be "r+i" or "r", or "i".
9885 if (Subtarget->isThumb1Only())
9889 // ARM doesn't support any R+R*scale+imm addr modes.
9896 if (Subtarget->isThumb2())
9897 return isLegalT2ScaledAddressingMode(AM, VT);
9899 int Scale = AM.Scale;
9900 switch (VT.getSimpleVT().SimpleTy) {
9901 default: return false;
9905 if (Scale < 0) Scale = -Scale;
9909 return isPowerOf2_32(Scale & ~1);
9913 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9918 // Note, we allow "void" uses (basically, uses that aren't loads or
9919 // stores), because arm allows folding a scale into many arithmetic
9920 // operations. This should be made more precise and revisited later.
9922 // Allow r << imm, but the imm has to be a multiple of two.
9923 if (Scale & 1) return false;
9924 return isPowerOf2_32(Scale);
9930 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9931 /// icmp immediate, that is the target has icmp instructions which can compare
9932 /// a register against the immediate without having to materialize the
9933 /// immediate into a register.
9934 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9935 // Thumb2 and ARM modes can use cmn for negative immediates.
9936 if (!Subtarget->isThumb())
9937 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9938 if (Subtarget->isThumb2())
9939 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9940 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9941 return Imm >= 0 && Imm <= 255;
9944 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9945 /// *or sub* immediate, that is the target has add or sub instructions which can
9946 /// add a register with the immediate without having to materialize the
9947 /// immediate into a register.
9948 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9949 // Same encoding for add/sub, just flip the sign.
9950 int64_t AbsImm = llvm::abs64(Imm);
9951 if (!Subtarget->isThumb())
9952 return ARM_AM::getSOImmVal(AbsImm) != -1;
9953 if (Subtarget->isThumb2())
9954 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9955 // Thumb1 only has 8-bit unsigned immediate.
9956 return AbsImm >= 0 && AbsImm <= 255;
9959 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9960 bool isSEXTLoad, SDValue &Base,
9961 SDValue &Offset, bool &isInc,
9962 SelectionDAG &DAG) {
9963 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9966 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9968 Base = Ptr->getOperand(0);
9969 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9970 int RHSC = (int)RHS->getZExtValue();
9971 if (RHSC < 0 && RHSC > -256) {
9972 assert(Ptr->getOpcode() == ISD::ADD);
9974 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9978 isInc = (Ptr->getOpcode() == ISD::ADD);
9979 Offset = Ptr->getOperand(1);
9981 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9983 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9984 int RHSC = (int)RHS->getZExtValue();
9985 if (RHSC < 0 && RHSC > -0x1000) {
9986 assert(Ptr->getOpcode() == ISD::ADD);
9988 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9989 Base = Ptr->getOperand(0);
9994 if (Ptr->getOpcode() == ISD::ADD) {
9996 ARM_AM::ShiftOpc ShOpcVal=
9997 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9998 if (ShOpcVal != ARM_AM::no_shift) {
9999 Base = Ptr->getOperand(1);
10000 Offset = Ptr->getOperand(0);
10002 Base = Ptr->getOperand(0);
10003 Offset = Ptr->getOperand(1);
10008 isInc = (Ptr->getOpcode() == ISD::ADD);
10009 Base = Ptr->getOperand(0);
10010 Offset = Ptr->getOperand(1);
10014 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10018 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10019 bool isSEXTLoad, SDValue &Base,
10020 SDValue &Offset, bool &isInc,
10021 SelectionDAG &DAG) {
10022 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10025 Base = Ptr->getOperand(0);
10026 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10027 int RHSC = (int)RHS->getZExtValue();
10028 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10029 assert(Ptr->getOpcode() == ISD::ADD);
10031 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10033 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10034 isInc = Ptr->getOpcode() == ISD::ADD;
10035 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10043 /// getPreIndexedAddressParts - returns true by value, base pointer and
10044 /// offset pointer and addressing mode by reference if the node's address
10045 /// can be legally represented as pre-indexed load / store address.
10047 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10049 ISD::MemIndexedMode &AM,
10050 SelectionDAG &DAG) const {
10051 if (Subtarget->isThumb1Only())
10056 bool isSEXTLoad = false;
10057 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10058 Ptr = LD->getBasePtr();
10059 VT = LD->getMemoryVT();
10060 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10061 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10062 Ptr = ST->getBasePtr();
10063 VT = ST->getMemoryVT();
10068 bool isLegal = false;
10069 if (Subtarget->isThumb2())
10070 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10071 Offset, isInc, DAG);
10073 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10074 Offset, isInc, DAG);
10078 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10082 /// getPostIndexedAddressParts - returns true by value, base pointer and
10083 /// offset pointer and addressing mode by reference if this node can be
10084 /// combined with a load / store to form a post-indexed load / store.
10085 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10088 ISD::MemIndexedMode &AM,
10089 SelectionDAG &DAG) const {
10090 if (Subtarget->isThumb1Only())
10095 bool isSEXTLoad = false;
10096 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10097 VT = LD->getMemoryVT();
10098 Ptr = LD->getBasePtr();
10099 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10100 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10101 VT = ST->getMemoryVT();
10102 Ptr = ST->getBasePtr();
10107 bool isLegal = false;
10108 if (Subtarget->isThumb2())
10109 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10112 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10118 // Swap base ptr and offset to catch more post-index load / store when
10119 // it's legal. In Thumb2 mode, offset must be an immediate.
10120 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10121 !Subtarget->isThumb2())
10122 std::swap(Base, Offset);
10124 // Post-indexed load / store update the base pointer.
10129 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10133 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10136 const SelectionDAG &DAG,
10137 unsigned Depth) const {
10138 unsigned BitWidth = KnownOne.getBitWidth();
10139 KnownZero = KnownOne = APInt(BitWidth, 0);
10140 switch (Op.getOpcode()) {
10146 // These nodes' second result is a boolean
10147 if (Op.getResNo() == 0)
10149 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10151 case ARMISD::CMOV: {
10152 // Bits are known zero/one if known on the LHS and RHS.
10153 DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10154 if (KnownZero == 0 && KnownOne == 0) return;
10156 APInt KnownZeroRHS, KnownOneRHS;
10157 DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10158 KnownZero &= KnownZeroRHS;
10159 KnownOne &= KnownOneRHS;
10162 case ISD::INTRINSIC_W_CHAIN: {
10163 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10164 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10167 case Intrinsic::arm_ldaex:
10168 case Intrinsic::arm_ldrex: {
10169 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10170 unsigned MemBits = VT.getScalarType().getSizeInBits();
10171 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10179 //===----------------------------------------------------------------------===//
10180 // ARM Inline Assembly Support
10181 //===----------------------------------------------------------------------===//
10183 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10184 // Looking for "rev" which is V6+.
10185 if (!Subtarget->hasV6Ops())
10188 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10189 std::string AsmStr = IA->getAsmString();
10190 SmallVector<StringRef, 4> AsmPieces;
10191 SplitString(AsmStr, AsmPieces, ";\n");
10193 switch (AsmPieces.size()) {
10194 default: return false;
10196 AsmStr = AsmPieces[0];
10198 SplitString(AsmStr, AsmPieces, " \t,");
10201 if (AsmPieces.size() == 3 &&
10202 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10203 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10204 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10205 if (Ty && Ty->getBitWidth() == 32)
10206 return IntrinsicLowering::LowerToByteSwap(CI);
10214 /// getConstraintType - Given a constraint letter, return the type of
10215 /// constraint it is for this target.
10216 ARMTargetLowering::ConstraintType
10217 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10218 if (Constraint.size() == 1) {
10219 switch (Constraint[0]) {
10221 case 'l': return C_RegisterClass;
10222 case 'w': return C_RegisterClass;
10223 case 'h': return C_RegisterClass;
10224 case 'x': return C_RegisterClass;
10225 case 't': return C_RegisterClass;
10226 case 'j': return C_Other; // Constant for movw.
10227 // An address with a single base register. Due to the way we
10228 // currently handle addresses it is the same as an 'r' memory constraint.
10229 case 'Q': return C_Memory;
10231 } else if (Constraint.size() == 2) {
10232 switch (Constraint[0]) {
10234 // All 'U+' constraints are addresses.
10235 case 'U': return C_Memory;
10238 return TargetLowering::getConstraintType(Constraint);
10241 /// Examine constraint type and operand type and determine a weight value.
10242 /// This object must already have been set up with the operand type
10243 /// and the current alternative constraint selected.
10244 TargetLowering::ConstraintWeight
10245 ARMTargetLowering::getSingleConstraintMatchWeight(
10246 AsmOperandInfo &info, const char *constraint) const {
10247 ConstraintWeight weight = CW_Invalid;
10248 Value *CallOperandVal = info.CallOperandVal;
10249 // If we don't have a value, we can't do a match,
10250 // but allow it at the lowest weight.
10251 if (!CallOperandVal)
10253 Type *type = CallOperandVal->getType();
10254 // Look at the constraint type.
10255 switch (*constraint) {
10257 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10260 if (type->isIntegerTy()) {
10261 if (Subtarget->isThumb())
10262 weight = CW_SpecificReg;
10264 weight = CW_Register;
10268 if (type->isFloatingPointTy())
10269 weight = CW_Register;
10275 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10277 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10279 if (Constraint.size() == 1) {
10280 // GCC ARM Constraint Letters
10281 switch (Constraint[0]) {
10282 case 'l': // Low regs or general regs.
10283 if (Subtarget->isThumb())
10284 return RCPair(0U, &ARM::tGPRRegClass);
10285 return RCPair(0U, &ARM::GPRRegClass);
10286 case 'h': // High regs or no regs.
10287 if (Subtarget->isThumb())
10288 return RCPair(0U, &ARM::hGPRRegClass);
10291 return RCPair(0U, &ARM::GPRRegClass);
10293 if (VT == MVT::Other)
10295 if (VT == MVT::f32)
10296 return RCPair(0U, &ARM::SPRRegClass);
10297 if (VT.getSizeInBits() == 64)
10298 return RCPair(0U, &ARM::DPRRegClass);
10299 if (VT.getSizeInBits() == 128)
10300 return RCPair(0U, &ARM::QPRRegClass);
10303 if (VT == MVT::Other)
10305 if (VT == MVT::f32)
10306 return RCPair(0U, &ARM::SPR_8RegClass);
10307 if (VT.getSizeInBits() == 64)
10308 return RCPair(0U, &ARM::DPR_8RegClass);
10309 if (VT.getSizeInBits() == 128)
10310 return RCPair(0U, &ARM::QPR_8RegClass);
10313 if (VT == MVT::f32)
10314 return RCPair(0U, &ARM::SPRRegClass);
10318 if (StringRef("{cc}").equals_lower(Constraint))
10319 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10321 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10324 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10325 /// vector. If it is invalid, don't add anything to Ops.
10326 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10327 std::string &Constraint,
10328 std::vector<SDValue>&Ops,
10329 SelectionDAG &DAG) const {
10332 // Currently only support length 1 constraints.
10333 if (Constraint.length() != 1) return;
10335 char ConstraintLetter = Constraint[0];
10336 switch (ConstraintLetter) {
10339 case 'I': case 'J': case 'K': case 'L':
10340 case 'M': case 'N': case 'O':
10341 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10345 int64_t CVal64 = C->getSExtValue();
10346 int CVal = (int) CVal64;
10347 // None of these constraints allow values larger than 32 bits. Check
10348 // that the value fits in an int.
10349 if (CVal != CVal64)
10352 switch (ConstraintLetter) {
10354 // Constant suitable for movw, must be between 0 and
10356 if (Subtarget->hasV6T2Ops())
10357 if (CVal >= 0 && CVal <= 65535)
10361 if (Subtarget->isThumb1Only()) {
10362 // This must be a constant between 0 and 255, for ADD
10364 if (CVal >= 0 && CVal <= 255)
10366 } else if (Subtarget->isThumb2()) {
10367 // A constant that can be used as an immediate value in a
10368 // data-processing instruction.
10369 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10372 // A constant that can be used as an immediate value in a
10373 // data-processing instruction.
10374 if (ARM_AM::getSOImmVal(CVal) != -1)
10380 if (Subtarget->isThumb()) { // FIXME thumb2
10381 // This must be a constant between -255 and -1, for negated ADD
10382 // immediates. This can be used in GCC with an "n" modifier that
10383 // prints the negated value, for use with SUB instructions. It is
10384 // not useful otherwise but is implemented for compatibility.
10385 if (CVal >= -255 && CVal <= -1)
10388 // This must be a constant between -4095 and 4095. It is not clear
10389 // what this constraint is intended for. Implemented for
10390 // compatibility with GCC.
10391 if (CVal >= -4095 && CVal <= 4095)
10397 if (Subtarget->isThumb1Only()) {
10398 // A 32-bit value where only one byte has a nonzero value. Exclude
10399 // zero to match GCC. This constraint is used by GCC internally for
10400 // constants that can be loaded with a move/shift combination.
10401 // It is not useful otherwise but is implemented for compatibility.
10402 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10404 } else if (Subtarget->isThumb2()) {
10405 // A constant whose bitwise inverse can be used as an immediate
10406 // value in a data-processing instruction. This can be used in GCC
10407 // with a "B" modifier that prints the inverted value, for use with
10408 // BIC and MVN instructions. It is not useful otherwise but is
10409 // implemented for compatibility.
10410 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10413 // A constant whose bitwise inverse can be used as an immediate
10414 // value in a data-processing instruction. This can be used in GCC
10415 // with a "B" modifier that prints the inverted value, for use with
10416 // BIC and MVN instructions. It is not useful otherwise but is
10417 // implemented for compatibility.
10418 if (ARM_AM::getSOImmVal(~CVal) != -1)
10424 if (Subtarget->isThumb1Only()) {
10425 // This must be a constant between -7 and 7,
10426 // for 3-operand ADD/SUB immediate instructions.
10427 if (CVal >= -7 && CVal < 7)
10429 } else if (Subtarget->isThumb2()) {
10430 // A constant whose negation can be used as an immediate value in a
10431 // data-processing instruction. This can be used in GCC with an "n"
10432 // modifier that prints the negated value, for use with SUB
10433 // instructions. It is not useful otherwise but is implemented for
10435 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10438 // A constant whose negation can be used as an immediate value in a
10439 // data-processing instruction. This can be used in GCC with an "n"
10440 // modifier that prints the negated value, for use with SUB
10441 // instructions. It is not useful otherwise but is implemented for
10443 if (ARM_AM::getSOImmVal(-CVal) != -1)
10449 if (Subtarget->isThumb()) { // FIXME thumb2
10450 // This must be a multiple of 4 between 0 and 1020, for
10451 // ADD sp + immediate.
10452 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10455 // A power of two or a constant between 0 and 32. This is used in
10456 // GCC for the shift amount on shifted register operands, but it is
10457 // useful in general for any shift amounts.
10458 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10464 if (Subtarget->isThumb()) { // FIXME thumb2
10465 // This must be a constant between 0 and 31, for shift amounts.
10466 if (CVal >= 0 && CVal <= 31)
10472 if (Subtarget->isThumb()) { // FIXME thumb2
10473 // This must be a multiple of 4 between -508 and 508, for
10474 // ADD/SUB sp = sp + immediate.
10475 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10480 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10484 if (Result.getNode()) {
10485 Ops.push_back(Result);
10488 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10491 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10492 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10493 unsigned Opcode = Op->getOpcode();
10494 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10495 "Invalid opcode for Div/Rem lowering");
10496 bool isSigned = (Opcode == ISD::SDIVREM);
10497 EVT VT = Op->getValueType(0);
10498 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10501 switch (VT.getSimpleVT().SimpleTy) {
10502 default: llvm_unreachable("Unexpected request for libcall!");
10503 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10504 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10505 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10506 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10509 SDValue InChain = DAG.getEntryNode();
10511 TargetLowering::ArgListTy Args;
10512 TargetLowering::ArgListEntry Entry;
10513 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10514 EVT ArgVT = Op->getOperand(i).getValueType();
10515 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10516 Entry.Node = Op->getOperand(i);
10518 Entry.isSExt = isSigned;
10519 Entry.isZExt = !isSigned;
10520 Args.push_back(Entry);
10523 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10526 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10530 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10531 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10532 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10533 Callee, Args, DAG, dl);
10534 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10536 return CallInfo.first;
10540 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10541 // The ARM target isn't yet aware of offsets.
10545 bool ARM::isBitFieldInvertedMask(unsigned v) {
10546 if (v == 0xffffffff)
10549 // there can be 1's on either or both "outsides", all the "inside"
10550 // bits must be 0's
10551 unsigned TO = CountTrailingOnes_32(v);
10552 unsigned LO = CountLeadingOnes_32(v);
10553 v = (v >> TO) << TO;
10554 v = (v << LO) >> LO;
10558 /// isFPImmLegal - Returns true if the target can instruction select the
10559 /// specified FP immediate natively. If false, the legalizer will
10560 /// materialize the FP immediate as a load from a constant pool.
10561 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10562 if (!Subtarget->hasVFP3())
10564 if (VT == MVT::f32)
10565 return ARM_AM::getFP32Imm(Imm) != -1;
10566 if (VT == MVT::f64)
10567 return ARM_AM::getFP64Imm(Imm) != -1;
10571 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10572 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10573 /// specified in the intrinsic calls.
10574 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10576 unsigned Intrinsic) const {
10577 switch (Intrinsic) {
10578 case Intrinsic::arm_neon_vld1:
10579 case Intrinsic::arm_neon_vld2:
10580 case Intrinsic::arm_neon_vld3:
10581 case Intrinsic::arm_neon_vld4:
10582 case Intrinsic::arm_neon_vld2lane:
10583 case Intrinsic::arm_neon_vld3lane:
10584 case Intrinsic::arm_neon_vld4lane: {
10585 Info.opc = ISD::INTRINSIC_W_CHAIN;
10586 // Conservatively set memVT to the entire set of vectors loaded.
10587 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10588 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10589 Info.ptrVal = I.getArgOperand(0);
10591 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10592 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10593 Info.vol = false; // volatile loads with NEON intrinsics not supported
10594 Info.readMem = true;
10595 Info.writeMem = false;
10598 case Intrinsic::arm_neon_vst1:
10599 case Intrinsic::arm_neon_vst2:
10600 case Intrinsic::arm_neon_vst3:
10601 case Intrinsic::arm_neon_vst4:
10602 case Intrinsic::arm_neon_vst2lane:
10603 case Intrinsic::arm_neon_vst3lane:
10604 case Intrinsic::arm_neon_vst4lane: {
10605 Info.opc = ISD::INTRINSIC_VOID;
10606 // Conservatively set memVT to the entire set of vectors stored.
10607 unsigned NumElts = 0;
10608 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10609 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10610 if (!ArgTy->isVectorTy())
10612 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10614 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10615 Info.ptrVal = I.getArgOperand(0);
10617 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10618 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10619 Info.vol = false; // volatile stores with NEON intrinsics not supported
10620 Info.readMem = false;
10621 Info.writeMem = true;
10624 case Intrinsic::arm_ldaex:
10625 case Intrinsic::arm_ldrex: {
10626 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10627 Info.opc = ISD::INTRINSIC_W_CHAIN;
10628 Info.memVT = MVT::getVT(PtrTy->getElementType());
10629 Info.ptrVal = I.getArgOperand(0);
10631 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10633 Info.readMem = true;
10634 Info.writeMem = false;
10637 case Intrinsic::arm_stlex:
10638 case Intrinsic::arm_strex: {
10639 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10640 Info.opc = ISD::INTRINSIC_W_CHAIN;
10641 Info.memVT = MVT::getVT(PtrTy->getElementType());
10642 Info.ptrVal = I.getArgOperand(1);
10644 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10646 Info.readMem = false;
10647 Info.writeMem = true;
10650 case Intrinsic::arm_stlexd:
10651 case Intrinsic::arm_strexd: {
10652 Info.opc = ISD::INTRINSIC_W_CHAIN;
10653 Info.memVT = MVT::i64;
10654 Info.ptrVal = I.getArgOperand(2);
10658 Info.readMem = false;
10659 Info.writeMem = true;
10662 case Intrinsic::arm_ldaexd:
10663 case Intrinsic::arm_ldrexd: {
10664 Info.opc = ISD::INTRINSIC_W_CHAIN;
10665 Info.memVT = MVT::i64;
10666 Info.ptrVal = I.getArgOperand(0);
10670 Info.readMem = true;
10671 Info.writeMem = false;
10681 /// \brief Returns true if it is beneficial to convert a load of a constant
10682 /// to just the constant itself.
10683 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10685 assert(Ty->isIntegerTy());
10687 unsigned Bits = Ty->getPrimitiveSizeInBits();
10688 if (Bits == 0 || Bits > 32)
10693 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10694 // Loads and stores less than 64-bits are already atomic; ones above that
10695 // are doomed anyway, so defer to the default libcall and blame the OS when
10696 // things go wrong:
10697 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10698 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10699 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10700 return LI->getType()->getPrimitiveSizeInBits() == 64;
10702 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10703 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10706 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10707 AtomicOrdering Ord) const {
10708 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10709 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10711 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10713 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10714 // intrinsic must return {i32, i32} and we have to recombine them into a
10715 // single i64 here.
10716 if (ValTy->getPrimitiveSizeInBits() == 64) {
10717 Intrinsic::ID Int =
10718 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10719 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10721 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10722 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10724 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10725 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10726 if (!Subtarget->isLittle())
10727 std::swap (Lo, Hi);
10728 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10729 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10730 return Builder.CreateOr(
10731 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10734 Type *Tys[] = { Addr->getType() };
10735 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10736 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10738 return Builder.CreateTruncOrBitCast(
10739 Builder.CreateCall(Ldrex, Addr),
10740 cast<PointerType>(Addr->getType())->getElementType());
10743 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10745 AtomicOrdering Ord) const {
10746 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10748 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10750 // Since the intrinsics must have legal type, the i64 intrinsics take two
10751 // parameters: "i32, i32". We must marshal Val into the appropriate form
10752 // before the call.
10753 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10754 Intrinsic::ID Int =
10755 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10756 Function *Strex = Intrinsic::getDeclaration(M, Int);
10757 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10759 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10760 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10761 if (!Subtarget->isLittle())
10762 std::swap (Lo, Hi);
10763 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10764 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10767 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10768 Type *Tys[] = { Addr->getType() };
10769 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10771 return Builder.CreateCall2(
10772 Strex, Builder.CreateZExtOrBitCast(
10773 Val, Strex->getFunctionType()->getParamType(0)),
10785 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10786 uint64_t &Members) {
10787 if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10788 for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10789 uint64_t SubMembers = 0;
10790 if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10792 Members += SubMembers;
10794 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10795 uint64_t SubMembers = 0;
10796 if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10798 Members += SubMembers * AT->getNumElements();
10799 } else if (Ty->isFloatTy()) {
10800 if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10804 } else if (Ty->isDoubleTy()) {
10805 if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10809 } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10816 return VT->getBitWidth() == 64;
10818 return VT->getBitWidth() == 128;
10820 switch (VT->getBitWidth()) {
10833 return (Members > 0 && Members <= 4);
10836 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10837 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10838 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10839 if (getEffectiveCallingConv(CallConv, isVarArg) ==
10840 CallingConv::ARM_AAPCS_VFP) {
10841 HABaseType Base = HA_UNKNOWN;
10842 uint64_t Members = 0;
10843 bool result = isHomogeneousAggregate(Ty, Base, Members);
10844 DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");