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/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
52 #define DEBUG_TYPE "arm-isel"
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60 cl::desc("Generate calls via indirect call instructions"),
64 ARMInterworking("arm-interworking", cl::Hidden,
65 cl::desc("Enable / disable ARM interworking (for debugging only)"),
69 class ARMCCState : public CCState {
71 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73 LLVMContext &C, ParmContext PC)
74 : CCState(CC, isVarArg, MF, TM, locs, C) {
75 assert(((PC == Call) || (PC == Prologue)) &&
76 "ARMCCState users must specify whether their context is call"
77 "or prologue generation.");
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85 ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89 MVT PromotedBitwiseVT) {
90 if (VT != PromotedLdStVT) {
91 setOperationAction(ISD::LOAD, VT, Promote);
92 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94 setOperationAction(ISD::STORE, VT, Promote);
95 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98 MVT ElemTy = VT.getVectorElementType();
99 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100 setOperationAction(ISD::SETCC, VT, Custom);
101 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103 if (ElemTy == MVT::i32) {
104 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
115 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
116 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
117 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118 setOperationAction(ISD::SELECT, VT, Expand);
119 setOperationAction(ISD::SELECT_CC, VT, Expand);
120 setOperationAction(ISD::VSELECT, VT, Expand);
121 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122 if (VT.isInteger()) {
123 setOperationAction(ISD::SHL, VT, Custom);
124 setOperationAction(ISD::SRA, VT, Custom);
125 setOperationAction(ISD::SRL, VT, Custom);
128 // Promote all bit-wise operations.
129 if (VT.isInteger() && VT != PromotedBitwiseVT) {
130 setOperationAction(ISD::AND, VT, Promote);
131 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132 setOperationAction(ISD::OR, VT, Promote);
133 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
134 setOperationAction(ISD::XOR, VT, Promote);
135 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138 // Neon does not support vector divide/remainder operations.
139 setOperationAction(ISD::SDIV, VT, Expand);
140 setOperationAction(ISD::UDIV, VT, Expand);
141 setOperationAction(ISD::FDIV, VT, Expand);
142 setOperationAction(ISD::SREM, VT, Expand);
143 setOperationAction(ISD::UREM, VT, Expand);
144 setOperationAction(ISD::FREM, VT, Expand);
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148 addRegisterClass(VT, &ARM::DPRRegClass);
149 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153 addRegisterClass(VT, &ARM::DPairRegClass);
154 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158 if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159 return new TargetLoweringObjectFileMachO();
161 return new ARMElfTargetObjectFile();
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165 : TargetLowering(TM, createTLOF(TM)) {
166 Subtarget = &TM.getSubtarget<ARMSubtarget>();
167 RegInfo = TM.getRegisterInfo();
168 Itins = TM.getInstrItineraryData();
170 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
172 if (Subtarget->isTargetMachO()) {
173 // Uses VFP for Thumb libfuncs if available.
174 if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175 Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
176 // Single-precision floating-point arithmetic.
177 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
182 // Double-precision floating-point arithmetic.
183 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
188 // Single-precision comparisons.
189 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
196 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
198 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
207 // Double-precision comparisons.
208 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
215 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
217 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
226 // Floating-point to integer conversions.
227 // i64 conversions are done via library routines even when generating VFP
228 // instructions, so use the same ones.
229 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
234 // Conversions between floating types.
235 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
238 // Integer to floating-point conversions.
239 // i64 conversions are done via library routines even when generating VFP
240 // instructions, so use the same ones.
241 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242 // e.g., __floatunsidf vs. __floatunssidfvfp.
243 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250 // These libcalls are not available in 32-bit.
251 setLibcallName(RTLIB::SHL_I128, nullptr);
252 setLibcallName(RTLIB::SRL_I128, nullptr);
253 setLibcallName(RTLIB::SRA_I128, nullptr);
255 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256 !Subtarget->isTargetWindows()) {
257 // Double-precision floating-point arithmetic helper functions
258 // RTABI chapter 4.1.2, Table 2
259 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
268 // Double-precision floating-point comparison helper functions
269 // RTABI chapter 4.1.2, Table 3
270 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
283 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
284 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
285 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
286 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
295 // Single-precision floating-point arithmetic helper functions
296 // RTABI chapter 4.1.2, Table 4
297 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
306 // Single-precision floating-point comparison helper functions
307 // RTABI chapter 4.1.2, Table 5
308 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
321 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
322 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
323 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
324 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
333 // Floating-point to integer conversions.
334 // RTABI chapter 4.1.2, Table 6
335 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
352 // Conversions between floating types.
353 // RTABI chapter 4.1.2, Table 7
354 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
356 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
359 // Integer to floating-point conversions.
360 // RTABI chapter 4.1.2, Table 8
361 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
378 // Long long helper functions
379 // RTABI chapter 4.2, Table 9
380 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
381 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
391 // Integer division functions
392 // RTABI chapter 4.3.1
393 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
394 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
398 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
411 // RTABI chapter 4.3.4
412 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
413 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
415 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
420 // Use divmod compiler-rt calls for iOS 5.0 and later.
421 if (Subtarget->getTargetTriple().isiOS() &&
422 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
427 if (Subtarget->isThumb1Only())
428 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
430 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432 !Subtarget->isThumb1Only()) {
433 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434 if (!Subtarget->isFPOnlySP())
435 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
437 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444 setTruncStoreAction((MVT::SimpleValueType)VT,
445 (MVT::SimpleValueType)InnerVT, Expand);
446 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
450 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
451 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
452 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
453 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
456 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
459 if (Subtarget->hasNEON()) {
460 addDRTypeForNEON(MVT::v2f32);
461 addDRTypeForNEON(MVT::v8i8);
462 addDRTypeForNEON(MVT::v4i16);
463 addDRTypeForNEON(MVT::v2i32);
464 addDRTypeForNEON(MVT::v1i64);
466 addQRTypeForNEON(MVT::v4f32);
467 addQRTypeForNEON(MVT::v2f64);
468 addQRTypeForNEON(MVT::v16i8);
469 addQRTypeForNEON(MVT::v8i16);
470 addQRTypeForNEON(MVT::v4i32);
471 addQRTypeForNEON(MVT::v2i64);
473 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474 // neither Neon nor VFP support any arithmetic operations on it.
475 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476 // supported for v4f32.
477 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480 // FIXME: Code duplication: FDIV and FREM are expanded always, see
481 // ARMTargetLowering::addTypeForNEON method for details.
482 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484 // FIXME: Create unittest.
485 // In another words, find a way when "copysign" appears in DAG with vector
487 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488 // FIXME: Code duplication: SETCC has custom operation action, see
489 // ARMTargetLowering::addTypeForNEON method for details.
490 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491 // FIXME: Create unittest for FNEG and for FABS.
492 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
512 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
528 // Mark v2f32 intrinsics.
529 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
545 // Neon does not support some operations on v1i64 and v2i64 types.
546 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547 // Custom handling for some quad-vector types to detect VMULL.
548 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551 // Custom handling for some vector types to avoid expensive expansions
552 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559 // a destination type that is wider than the source, and nor does
560 // it have a FP_TO_[SU]INT instruction with a narrower destination than
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
567 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
568 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
570 // NEON does not have single instruction CTPOP for vectors with element
571 // types wider than 8-bits. However, custom lowering can leverage the
572 // v8i8/v16i8 vcnt instruction.
573 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
574 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
575 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
576 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
578 // NEON only has FMA instructions as of VFP4.
579 if (!Subtarget->hasVFP4()) {
580 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
584 setTargetDAGCombine(ISD::INTRINSIC_VOID);
585 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587 setTargetDAGCombine(ISD::SHL);
588 setTargetDAGCombine(ISD::SRL);
589 setTargetDAGCombine(ISD::SRA);
590 setTargetDAGCombine(ISD::SIGN_EXTEND);
591 setTargetDAGCombine(ISD::ZERO_EXTEND);
592 setTargetDAGCombine(ISD::ANY_EXTEND);
593 setTargetDAGCombine(ISD::SELECT_CC);
594 setTargetDAGCombine(ISD::BUILD_VECTOR);
595 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597 setTargetDAGCombine(ISD::STORE);
598 setTargetDAGCombine(ISD::FP_TO_SINT);
599 setTargetDAGCombine(ISD::FP_TO_UINT);
600 setTargetDAGCombine(ISD::FDIV);
602 // It is legal to extload from v4i8 to v4i16 or v4i32.
603 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604 MVT::v4i16, MVT::v2i16,
606 for (unsigned i = 0; i < 6; ++i) {
607 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
613 // ARM and Thumb2 support UMLAL/SMLAL.
614 if (!Subtarget->isThumb1Only())
615 setTargetDAGCombine(ISD::ADDC);
618 computeRegisterProperties();
620 // ARM does not have f32 extending load.
621 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
623 // ARM does not have i1 sign extending load.
624 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
626 // ARM supports all 4 flavors of integer indexed load / store.
627 if (!Subtarget->isThumb1Only()) {
628 for (unsigned im = (unsigned)ISD::PRE_INC;
629 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630 setIndexedLoadAction(im, MVT::i1, Legal);
631 setIndexedLoadAction(im, MVT::i8, Legal);
632 setIndexedLoadAction(im, MVT::i16, Legal);
633 setIndexedLoadAction(im, MVT::i32, Legal);
634 setIndexedStoreAction(im, MVT::i1, Legal);
635 setIndexedStoreAction(im, MVT::i8, Legal);
636 setIndexedStoreAction(im, MVT::i16, Legal);
637 setIndexedStoreAction(im, MVT::i32, Legal);
641 // i64 operation support.
642 setOperationAction(ISD::MUL, MVT::i64, Expand);
643 setOperationAction(ISD::MULHU, MVT::i32, Expand);
644 if (Subtarget->isThumb1Only()) {
645 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
648 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650 setOperationAction(ISD::MULHS, MVT::i32, Expand);
652 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655 setOperationAction(ISD::SRL, MVT::i64, Custom);
656 setOperationAction(ISD::SRA, MVT::i64, Custom);
658 if (!Subtarget->isThumb1Only()) {
659 // FIXME: We should do this for Thumb1 as well.
660 setOperationAction(ISD::ADDC, MVT::i32, Custom);
661 setOperationAction(ISD::ADDE, MVT::i32, Custom);
662 setOperationAction(ISD::SUBC, MVT::i32, Custom);
663 setOperationAction(ISD::SUBE, MVT::i32, Custom);
666 // ARM does not have ROTL.
667 setOperationAction(ISD::ROTL, MVT::i32, Expand);
668 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
669 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
673 // These just redirect to CTTZ and CTLZ on ARM.
674 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
675 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
677 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
679 // Only ARMv6 has BSWAP.
680 if (!Subtarget->hasV6Ops())
681 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
683 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685 // These are expanded into libcalls if the cpu doesn't have HW divider.
686 setOperationAction(ISD::SDIV, MVT::i32, Expand);
687 setOperationAction(ISD::UDIV, MVT::i32, Expand);
690 // FIXME: Also set divmod for SREM on EABI
691 setOperationAction(ISD::SREM, MVT::i32, Expand);
692 setOperationAction(ISD::UREM, MVT::i32, Expand);
693 // Register based DivRem for AEABI (RTABI 4.2)
694 if (Subtarget->isTargetAEABI()) {
695 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
696 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
700 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
704 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
713 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
716 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
720 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
721 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
722 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
726 setOperationAction(ISD::TRAP, MVT::Other, Legal);
728 // Use the default implementation.
729 setOperationAction(ISD::VASTART, MVT::Other, Custom);
730 setOperationAction(ISD::VAARG, MVT::Other, Expand);
731 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
732 setOperationAction(ISD::VAEND, MVT::Other, Expand);
733 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
734 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
736 if (!Subtarget->isTargetMachO()) {
737 // Non-MachO platforms may return values in these registers via the
738 // personality function.
739 setExceptionPointerRegister(ARM::R0);
740 setExceptionSelectorRegister(ARM::R1);
743 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745 // the default expansion.
746 if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747 // ATOMIC_FENCE needs custom lowering; the others should have been expanded
748 // to ldrex/strex loops already.
749 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
751 // On v8, we have particularly efficient implementations of atomic fences
752 // if they can be combined with nearby atomic loads and stores.
753 if (!Subtarget->hasV8Ops()) {
754 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
755 setInsertFencesForAtomic(true);
758 // If there's anything we can use as a barrier, go through custom lowering
760 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other,
761 Subtarget->hasAnyDataBarrier() ? Custom : Expand);
763 // Set them all for expansion, which will force libcalls.
764 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
765 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
766 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
767 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
768 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
769 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
770 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
771 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
772 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
773 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
774 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
775 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
776 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
777 // Unordered/Monotonic case.
778 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
779 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
782 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
784 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
785 if (!Subtarget->hasV6Ops()) {
786 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
787 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
789 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
791 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
792 !Subtarget->isThumb1Only()) {
793 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
794 // iff target supports vfp2.
795 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
796 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
799 // We want to custom lower some of our intrinsics.
800 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
801 if (Subtarget->isTargetDarwin()) {
802 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
803 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
804 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
807 setOperationAction(ISD::SETCC, MVT::i32, Expand);
808 setOperationAction(ISD::SETCC, MVT::f32, Expand);
809 setOperationAction(ISD::SETCC, MVT::f64, Expand);
810 setOperationAction(ISD::SELECT, MVT::i32, Custom);
811 setOperationAction(ISD::SELECT, MVT::f32, Custom);
812 setOperationAction(ISD::SELECT, MVT::f64, Custom);
813 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
814 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
815 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
817 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
818 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
819 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
820 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
821 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
823 // We don't support sin/cos/fmod/copysign/pow
824 setOperationAction(ISD::FSIN, MVT::f64, Expand);
825 setOperationAction(ISD::FSIN, MVT::f32, Expand);
826 setOperationAction(ISD::FCOS, MVT::f32, Expand);
827 setOperationAction(ISD::FCOS, MVT::f64, Expand);
828 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
829 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
830 setOperationAction(ISD::FREM, MVT::f64, Expand);
831 setOperationAction(ISD::FREM, MVT::f32, Expand);
832 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
833 !Subtarget->isThumb1Only()) {
834 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
835 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
837 setOperationAction(ISD::FPOW, MVT::f64, Expand);
838 setOperationAction(ISD::FPOW, MVT::f32, Expand);
840 if (!Subtarget->hasVFP4()) {
841 setOperationAction(ISD::FMA, MVT::f64, Expand);
842 setOperationAction(ISD::FMA, MVT::f32, Expand);
845 // Various VFP goodness
846 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
847 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
848 if (Subtarget->hasVFP2()) {
849 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
850 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
851 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
852 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
854 // Special handling for half-precision FP.
855 if (!Subtarget->hasFP16()) {
856 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
857 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
861 // Combine sin / cos into one node or libcall if possible.
862 if (Subtarget->hasSinCos()) {
863 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
864 setLibcallName(RTLIB::SINCOS_F64, "sincos");
865 if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
866 // For iOS, we don't want to the normal expansion of a libcall to
867 // sincos. We want to issue a libcall to __sincos_stret.
868 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
869 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
873 // We have target-specific dag combine patterns for the following nodes:
874 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
875 setTargetDAGCombine(ISD::ADD);
876 setTargetDAGCombine(ISD::SUB);
877 setTargetDAGCombine(ISD::MUL);
878 setTargetDAGCombine(ISD::AND);
879 setTargetDAGCombine(ISD::OR);
880 setTargetDAGCombine(ISD::XOR);
882 if (Subtarget->hasV6Ops())
883 setTargetDAGCombine(ISD::SRL);
885 setStackPointerRegisterToSaveRestore(ARM::SP);
887 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888 !Subtarget->hasVFP2())
889 setSchedulingPreference(Sched::RegPressure);
891 setSchedulingPreference(Sched::Hybrid);
893 //// temporary - rewrite interface to use type
894 MaxStoresPerMemset = 8;
895 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
901 // On ARM arguments smaller than 4 bytes are extended, so all arguments
902 // are at least 4 bytes aligned.
903 setMinStackArgumentAlignment(4);
905 // Prefer likely predicted branches to selects on out-of-order cores.
906 PredictableSelectIsExpensive = Subtarget->isLikeA9();
908 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
911 // FIXME: It might make sense to define the representative register class as the
912 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
913 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
914 // SPR's representative would be DPR_VFP2. This should work well if register
915 // pressure tracking were modified such that a register use would increment the
916 // pressure of the register class's representative and all of it's super
917 // classes' representatives transitively. We have not implemented this because
918 // of the difficulty prior to coalescing of modeling operand register classes
919 // due to the common occurrence of cross class copies and subregister insertions
921 std::pair<const TargetRegisterClass*, uint8_t>
922 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
923 const TargetRegisterClass *RRC = nullptr;
925 switch (VT.SimpleTy) {
927 return TargetLowering::findRepresentativeClass(VT);
928 // Use DPR as representative register class for all floating point
929 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
930 // the cost is 1 for both f32 and f64.
931 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
932 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
933 RRC = &ARM::DPRRegClass;
934 // When NEON is used for SP, only half of the register file is available
935 // because operations that define both SP and DP results will be constrained
936 // to the VFP2 class (D0-D15). We currently model this constraint prior to
937 // coalescing by double-counting the SP regs. See the FIXME above.
938 if (Subtarget->useNEONForSinglePrecisionFP())
941 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
942 case MVT::v4f32: case MVT::v2f64:
943 RRC = &ARM::DPRRegClass;
947 RRC = &ARM::DPRRegClass;
951 RRC = &ARM::DPRRegClass;
955 return std::make_pair(RRC, Cost);
958 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
960 default: return nullptr;
961 case ARMISD::Wrapper: return "ARMISD::Wrapper";
962 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
963 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
964 case ARMISD::CALL: return "ARMISD::CALL";
965 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
966 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
967 case ARMISD::tCALL: return "ARMISD::tCALL";
968 case ARMISD::BRCOND: return "ARMISD::BRCOND";
969 case ARMISD::BR_JT: return "ARMISD::BR_JT";
970 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
971 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
972 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
973 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
974 case ARMISD::CMP: return "ARMISD::CMP";
975 case ARMISD::CMN: return "ARMISD::CMN";
976 case ARMISD::CMPZ: return "ARMISD::CMPZ";
977 case ARMISD::CMPFP: return "ARMISD::CMPFP";
978 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
979 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
980 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
982 case ARMISD::CMOV: return "ARMISD::CMOV";
984 case ARMISD::RBIT: return "ARMISD::RBIT";
986 case ARMISD::FTOSI: return "ARMISD::FTOSI";
987 case ARMISD::FTOUI: return "ARMISD::FTOUI";
988 case ARMISD::SITOF: return "ARMISD::SITOF";
989 case ARMISD::UITOF: return "ARMISD::UITOF";
991 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
992 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
993 case ARMISD::RRX: return "ARMISD::RRX";
995 case ARMISD::ADDC: return "ARMISD::ADDC";
996 case ARMISD::ADDE: return "ARMISD::ADDE";
997 case ARMISD::SUBC: return "ARMISD::SUBC";
998 case ARMISD::SUBE: return "ARMISD::SUBE";
1000 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1001 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1003 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1004 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1006 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1008 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1010 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1012 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1014 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1016 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1017 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1018 case ARMISD::VCGE: return "ARMISD::VCGE";
1019 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1020 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1021 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1022 case ARMISD::VCGT: return "ARMISD::VCGT";
1023 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1024 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1025 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1026 case ARMISD::VTST: return "ARMISD::VTST";
1028 case ARMISD::VSHL: return "ARMISD::VSHL";
1029 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1030 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1031 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1032 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1033 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1034 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1035 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1036 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1037 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1038 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1039 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1040 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1041 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1042 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1043 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1044 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1045 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1046 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1047 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1048 case ARMISD::VDUP: return "ARMISD::VDUP";
1049 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1050 case ARMISD::VEXT: return "ARMISD::VEXT";
1051 case ARMISD::VREV64: return "ARMISD::VREV64";
1052 case ARMISD::VREV32: return "ARMISD::VREV32";
1053 case ARMISD::VREV16: return "ARMISD::VREV16";
1054 case ARMISD::VZIP: return "ARMISD::VZIP";
1055 case ARMISD::VUZP: return "ARMISD::VUZP";
1056 case ARMISD::VTRN: return "ARMISD::VTRN";
1057 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1058 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1059 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1060 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1061 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1062 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1063 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1064 case ARMISD::FMAX: return "ARMISD::FMAX";
1065 case ARMISD::FMIN: return "ARMISD::FMIN";
1066 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1067 case ARMISD::VMINNM: return "ARMISD::VMIN";
1068 case ARMISD::BFI: return "ARMISD::BFI";
1069 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1070 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1071 case ARMISD::VBSL: return "ARMISD::VBSL";
1072 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1073 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1074 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1075 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1076 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1077 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1078 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1079 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1080 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1081 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1082 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1083 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1084 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1085 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1086 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1087 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1088 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1089 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1090 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1091 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1095 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1096 if (!VT.isVector()) return getPointerTy();
1097 return VT.changeVectorElementTypeToInteger();
1100 /// getRegClassFor - Return the register class that should be used for the
1101 /// specified value type.
1102 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1103 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1104 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1105 // load / store 4 to 8 consecutive D registers.
1106 if (Subtarget->hasNEON()) {
1107 if (VT == MVT::v4i64)
1108 return &ARM::QQPRRegClass;
1109 if (VT == MVT::v8i64)
1110 return &ARM::QQQQPRRegClass;
1112 return TargetLowering::getRegClassFor(VT);
1115 // Create a fast isel object.
1117 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1118 const TargetLibraryInfo *libInfo) const {
1119 return ARM::createFastISel(funcInfo, libInfo);
1122 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1123 /// be used for loads / stores from the global.
1124 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1125 return (Subtarget->isThumb1Only() ? 127 : 4095);
1128 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1129 unsigned NumVals = N->getNumValues();
1131 return Sched::RegPressure;
1133 for (unsigned i = 0; i != NumVals; ++i) {
1134 EVT VT = N->getValueType(i);
1135 if (VT == MVT::Glue || VT == MVT::Other)
1137 if (VT.isFloatingPoint() || VT.isVector())
1141 if (!N->isMachineOpcode())
1142 return Sched::RegPressure;
1144 // Load are scheduled for latency even if there instruction itinerary
1145 // is not available.
1146 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1147 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1149 if (MCID.getNumDefs() == 0)
1150 return Sched::RegPressure;
1151 if (!Itins->isEmpty() &&
1152 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1155 return Sched::RegPressure;
1158 //===----------------------------------------------------------------------===//
1160 //===----------------------------------------------------------------------===//
1162 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1163 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1165 default: llvm_unreachable("Unknown condition code!");
1166 case ISD::SETNE: return ARMCC::NE;
1167 case ISD::SETEQ: return ARMCC::EQ;
1168 case ISD::SETGT: return ARMCC::GT;
1169 case ISD::SETGE: return ARMCC::GE;
1170 case ISD::SETLT: return ARMCC::LT;
1171 case ISD::SETLE: return ARMCC::LE;
1172 case ISD::SETUGT: return ARMCC::HI;
1173 case ISD::SETUGE: return ARMCC::HS;
1174 case ISD::SETULT: return ARMCC::LO;
1175 case ISD::SETULE: return ARMCC::LS;
1179 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1180 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1181 ARMCC::CondCodes &CondCode2) {
1182 CondCode2 = ARMCC::AL;
1184 default: llvm_unreachable("Unknown FP condition!");
1186 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1188 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1190 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1191 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1192 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1193 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1194 case ISD::SETO: CondCode = ARMCC::VC; break;
1195 case ISD::SETUO: CondCode = ARMCC::VS; break;
1196 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1197 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1198 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1200 case ISD::SETULT: CondCode = ARMCC::LT; break;
1202 case ISD::SETULE: CondCode = ARMCC::LE; break;
1204 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1208 //===----------------------------------------------------------------------===//
1209 // Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1212 #include "ARMGenCallingConv.inc"
1214 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1215 /// given CallingConvention value.
1216 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1218 bool isVarArg) const {
1221 llvm_unreachable("Unsupported calling convention");
1222 case CallingConv::Fast:
1223 if (Subtarget->hasVFP2() && !isVarArg) {
1224 if (!Subtarget->isAAPCS_ABI())
1225 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1226 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1227 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1230 case CallingConv::C: {
1231 // Use target triple & subtarget features to do actual dispatch.
1232 if (!Subtarget->isAAPCS_ABI())
1233 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1234 else if (Subtarget->hasVFP2() &&
1235 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1237 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1240 case CallingConv::ARM_AAPCS_VFP:
1242 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1244 case CallingConv::ARM_AAPCS:
1245 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1246 case CallingConv::ARM_APCS:
1247 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1248 case CallingConv::GHC:
1249 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1253 /// LowerCallResult - Lower the result values of a call into the
1254 /// appropriate copies out of appropriate physical registers.
1256 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1257 CallingConv::ID CallConv, bool isVarArg,
1258 const SmallVectorImpl<ISD::InputArg> &Ins,
1259 SDLoc dl, SelectionDAG &DAG,
1260 SmallVectorImpl<SDValue> &InVals,
1261 bool isThisReturn, SDValue ThisVal) const {
1263 // Assign locations to each value returned by this call.
1264 SmallVector<CCValAssign, 16> RVLocs;
1265 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1266 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1267 CCInfo.AnalyzeCallResult(Ins,
1268 CCAssignFnForNode(CallConv, /* Return*/ true,
1271 // Copy all of the result registers out of their specified physreg.
1272 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1273 CCValAssign VA = RVLocs[i];
1275 // Pass 'this' value directly from the argument to return value, to avoid
1276 // reg unit interference
1277 if (i == 0 && isThisReturn) {
1278 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1279 "unexpected return calling convention register assignment");
1280 InVals.push_back(ThisVal);
1285 if (VA.needsCustom()) {
1286 // Handle f64 or half of a v2f64.
1287 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1289 Chain = Lo.getValue(1);
1290 InFlag = Lo.getValue(2);
1291 VA = RVLocs[++i]; // skip ahead to next loc
1292 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1294 Chain = Hi.getValue(1);
1295 InFlag = Hi.getValue(2);
1296 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1298 if (VA.getLocVT() == MVT::v2f64) {
1299 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1300 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1301 DAG.getConstant(0, MVT::i32));
1303 VA = RVLocs[++i]; // skip ahead to next loc
1304 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1305 Chain = Lo.getValue(1);
1306 InFlag = Lo.getValue(2);
1307 VA = RVLocs[++i]; // skip ahead to next loc
1308 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1309 Chain = Hi.getValue(1);
1310 InFlag = Hi.getValue(2);
1311 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1312 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1313 DAG.getConstant(1, MVT::i32));
1316 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1318 Chain = Val.getValue(1);
1319 InFlag = Val.getValue(2);
1322 switch (VA.getLocInfo()) {
1323 default: llvm_unreachable("Unknown loc info!");
1324 case CCValAssign::Full: break;
1325 case CCValAssign::BCvt:
1326 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1330 InVals.push_back(Val);
1336 /// LowerMemOpCallTo - Store the argument to the stack.
1338 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1339 SDValue StackPtr, SDValue Arg,
1340 SDLoc dl, SelectionDAG &DAG,
1341 const CCValAssign &VA,
1342 ISD::ArgFlagsTy Flags) const {
1343 unsigned LocMemOffset = VA.getLocMemOffset();
1344 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1345 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1346 return DAG.getStore(Chain, dl, Arg, PtrOff,
1347 MachinePointerInfo::getStack(LocMemOffset),
1351 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1352 SDValue Chain, SDValue &Arg,
1353 RegsToPassVector &RegsToPass,
1354 CCValAssign &VA, CCValAssign &NextVA,
1356 SmallVectorImpl<SDValue> &MemOpChains,
1357 ISD::ArgFlagsTy Flags) const {
1359 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1360 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1361 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1363 if (NextVA.isRegLoc())
1364 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1366 assert(NextVA.isMemLoc());
1367 if (!StackPtr.getNode())
1368 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1370 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1376 /// LowerCall - Lowering a call into a callseq_start <-
1377 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1380 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1381 SmallVectorImpl<SDValue> &InVals) const {
1382 SelectionDAG &DAG = CLI.DAG;
1384 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1385 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1386 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1387 SDValue Chain = CLI.Chain;
1388 SDValue Callee = CLI.Callee;
1389 bool &isTailCall = CLI.IsTailCall;
1390 CallingConv::ID CallConv = CLI.CallConv;
1391 bool doesNotRet = CLI.DoesNotReturn;
1392 bool isVarArg = CLI.IsVarArg;
1394 MachineFunction &MF = DAG.getMachineFunction();
1395 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1396 bool isThisReturn = false;
1397 bool isSibCall = false;
1399 // Disable tail calls if they're not supported.
1400 if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1404 // Check if it's really possible to do a tail call.
1405 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1406 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1407 Outs, OutVals, Ins, DAG);
1408 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1409 report_fatal_error("failed to perform tail call elimination on a call "
1410 "site marked musttail");
1411 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1412 // detected sibcalls.
1419 // Analyze operands of the call, assigning locations to each operand.
1420 SmallVector<CCValAssign, 16> ArgLocs;
1421 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1422 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1423 CCInfo.AnalyzeCallOperands(Outs,
1424 CCAssignFnForNode(CallConv, /* Return*/ false,
1427 // Get a count of how many bytes are to be pushed on the stack.
1428 unsigned NumBytes = CCInfo.getNextStackOffset();
1430 // For tail calls, memory operands are available in our caller's stack.
1434 // Adjust the stack pointer for the new arguments...
1435 // These operations are automatically eliminated by the prolog/epilog pass
1437 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1440 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1442 RegsToPassVector RegsToPass;
1443 SmallVector<SDValue, 8> MemOpChains;
1445 // Walk the register/memloc assignments, inserting copies/loads. In the case
1446 // of tail call optimization, arguments are handled later.
1447 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1449 ++i, ++realArgIdx) {
1450 CCValAssign &VA = ArgLocs[i];
1451 SDValue Arg = OutVals[realArgIdx];
1452 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1453 bool isByVal = Flags.isByVal();
1455 // Promote the value if needed.
1456 switch (VA.getLocInfo()) {
1457 default: llvm_unreachable("Unknown loc info!");
1458 case CCValAssign::Full: break;
1459 case CCValAssign::SExt:
1460 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1462 case CCValAssign::ZExt:
1463 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1465 case CCValAssign::AExt:
1466 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1468 case CCValAssign::BCvt:
1469 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1473 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1474 if (VA.needsCustom()) {
1475 if (VA.getLocVT() == MVT::v2f64) {
1476 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1477 DAG.getConstant(0, MVT::i32));
1478 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1479 DAG.getConstant(1, MVT::i32));
1481 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1482 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1484 VA = ArgLocs[++i]; // skip ahead to next loc
1485 if (VA.isRegLoc()) {
1486 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1487 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1489 assert(VA.isMemLoc());
1491 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1492 dl, DAG, VA, Flags));
1495 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1496 StackPtr, MemOpChains, Flags);
1498 } else if (VA.isRegLoc()) {
1499 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1500 assert(VA.getLocVT() == MVT::i32 &&
1501 "unexpected calling convention register assignment");
1502 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1503 "unexpected use of 'returned'");
1504 isThisReturn = true;
1506 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1507 } else if (isByVal) {
1508 assert(VA.isMemLoc());
1509 unsigned offset = 0;
1511 // True if this byval aggregate will be split between registers
1513 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1514 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1516 if (CurByValIdx < ByValArgsCount) {
1518 unsigned RegBegin, RegEnd;
1519 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1521 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1523 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1524 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1525 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1526 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1527 MachinePointerInfo(),
1528 false, false, false,
1529 DAG.InferPtrAlignment(AddArg));
1530 MemOpChains.push_back(Load.getValue(1));
1531 RegsToPass.push_back(std::make_pair(j, Load));
1534 // If parameter size outsides register area, "offset" value
1535 // helps us to calculate stack slot for remained part properly.
1536 offset = RegEnd - RegBegin;
1538 CCInfo.nextInRegsParam();
1541 if (Flags.getByValSize() > 4*offset) {
1542 unsigned LocMemOffset = VA.getLocMemOffset();
1543 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1544 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1546 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1547 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1548 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1550 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1552 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1553 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1554 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1557 } else if (!isSibCall) {
1558 assert(VA.isMemLoc());
1560 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1561 dl, DAG, VA, Flags));
1565 if (!MemOpChains.empty())
1566 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1568 // Build a sequence of copy-to-reg nodes chained together with token chain
1569 // and flag operands which copy the outgoing args into the appropriate regs.
1571 // Tail call byval lowering might overwrite argument registers so in case of
1572 // tail call optimization the copies to registers are lowered later.
1574 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1575 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1576 RegsToPass[i].second, InFlag);
1577 InFlag = Chain.getValue(1);
1580 // For tail calls lower the arguments to the 'real' stack slot.
1582 // Force all the incoming stack arguments to be loaded from the stack
1583 // before any new outgoing arguments are stored to the stack, because the
1584 // outgoing stack slots may alias the incoming argument stack slots, and
1585 // the alias isn't otherwise explicit. This is slightly more conservative
1586 // than necessary, because it means that each store effectively depends
1587 // on every argument instead of just those arguments it would clobber.
1589 // Do not flag preceding copytoreg stuff together with the following stuff.
1591 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1592 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1593 RegsToPass[i].second, InFlag);
1594 InFlag = Chain.getValue(1);
1599 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1600 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1601 // node so that legalize doesn't hack it.
1602 bool isDirect = false;
1603 bool isARMFunc = false;
1604 bool isLocalARMFunc = false;
1605 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1607 if (EnableARMLongCalls) {
1608 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1609 && "long-calls with non-static relocation model!");
1610 // Handle a global address or an external symbol. If it's not one of
1611 // those, the target's already in a register, so we don't need to do
1613 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1614 const GlobalValue *GV = G->getGlobal();
1615 // Create a constant pool entry for the callee address
1616 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1617 ARMConstantPoolValue *CPV =
1618 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1620 // Get the address of the callee into a register
1621 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1622 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1623 Callee = DAG.getLoad(getPointerTy(), dl,
1624 DAG.getEntryNode(), CPAddr,
1625 MachinePointerInfo::getConstantPool(),
1626 false, false, false, 0);
1627 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1628 const char *Sym = S->getSymbol();
1630 // Create a constant pool entry for the callee address
1631 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1632 ARMConstantPoolValue *CPV =
1633 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1634 ARMPCLabelIndex, 0);
1635 // Get the address of the callee into a register
1636 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1637 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1638 Callee = DAG.getLoad(getPointerTy(), dl,
1639 DAG.getEntryNode(), CPAddr,
1640 MachinePointerInfo::getConstantPool(),
1641 false, false, false, 0);
1643 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1644 const GlobalValue *GV = G->getGlobal();
1646 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1647 bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1648 getTargetMachine().getRelocationModel() != Reloc::Static;
1649 isARMFunc = !Subtarget->isThumb() || isStub;
1650 // ARM call to a local ARM function is predicable.
1651 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1652 // tBX takes a register source operand.
1653 if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1654 assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1655 Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1656 DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1658 // On ELF targets for PIC code, direct calls should go through the PLT
1659 unsigned OpFlags = 0;
1660 if (Subtarget->isTargetELF() &&
1661 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1662 OpFlags = ARMII::MO_PLT;
1663 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1665 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1667 bool isStub = Subtarget->isTargetMachO() &&
1668 getTargetMachine().getRelocationModel() != Reloc::Static;
1669 isARMFunc = !Subtarget->isThumb() || isStub;
1670 // tBX takes a register source operand.
1671 const char *Sym = S->getSymbol();
1672 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1673 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1674 ARMConstantPoolValue *CPV =
1675 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1676 ARMPCLabelIndex, 4);
1677 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1678 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1679 Callee = DAG.getLoad(getPointerTy(), dl,
1680 DAG.getEntryNode(), CPAddr,
1681 MachinePointerInfo::getConstantPool(),
1682 false, false, false, 0);
1683 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1684 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1685 getPointerTy(), Callee, PICLabel);
1687 unsigned OpFlags = 0;
1688 // On ELF targets for PIC code, direct calls should go through the PLT
1689 if (Subtarget->isTargetELF() &&
1690 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691 OpFlags = ARMII::MO_PLT;
1692 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1696 // FIXME: handle tail calls differently.
1698 bool HasMinSizeAttr = Subtarget->isMinSize();
1699 if (Subtarget->isThumb()) {
1700 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1701 CallOpc = ARMISD::CALL_NOLINK;
1703 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1705 if (!isDirect && !Subtarget->hasV5TOps())
1706 CallOpc = ARMISD::CALL_NOLINK;
1707 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1708 // Emit regular call when code size is the priority
1710 // "mov lr, pc; b _foo" to avoid confusing the RSP
1711 CallOpc = ARMISD::CALL_NOLINK;
1713 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1716 std::vector<SDValue> Ops;
1717 Ops.push_back(Chain);
1718 Ops.push_back(Callee);
1720 // Add argument registers to the end of the list so that they are known live
1722 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1723 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1724 RegsToPass[i].second.getValueType()));
1726 // Add a register mask operand representing the call-preserved registers.
1728 const uint32_t *Mask;
1729 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1730 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1732 // For 'this' returns, use the R0-preserving mask if applicable
1733 Mask = ARI->getThisReturnPreservedMask(CallConv);
1735 // Set isThisReturn to false if the calling convention is not one that
1736 // allows 'returned' to be modeled in this way, so LowerCallResult does
1737 // not try to pass 'this' straight through
1738 isThisReturn = false;
1739 Mask = ARI->getCallPreservedMask(CallConv);
1742 Mask = ARI->getCallPreservedMask(CallConv);
1744 assert(Mask && "Missing call preserved mask for calling convention");
1745 Ops.push_back(DAG.getRegisterMask(Mask));
1748 if (InFlag.getNode())
1749 Ops.push_back(InFlag);
1751 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1753 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1755 // Returns a chain and a flag for retval copy to use.
1756 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1757 InFlag = Chain.getValue(1);
1759 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1760 DAG.getIntPtrConstant(0, true), InFlag, dl);
1762 InFlag = Chain.getValue(1);
1764 // Handle result values, copying them out of physregs into vregs that we
1766 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1767 InVals, isThisReturn,
1768 isThisReturn ? OutVals[0] : SDValue());
1771 /// HandleByVal - Every parameter *after* a byval parameter is passed
1772 /// on the stack. Remember the next parameter register to allocate,
1773 /// and then confiscate the rest of the parameter registers to insure
1776 ARMTargetLowering::HandleByVal(
1777 CCState *State, unsigned &size, unsigned Align) const {
1778 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1779 assert((State->getCallOrPrologue() == Prologue ||
1780 State->getCallOrPrologue() == Call) &&
1781 "unhandled ParmContext");
1783 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1784 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1785 unsigned AlignInRegs = Align / 4;
1786 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1787 for (unsigned i = 0; i < Waste; ++i)
1788 reg = State->AllocateReg(GPRArgRegs, 4);
1791 unsigned excess = 4 * (ARM::R4 - reg);
1793 // Special case when NSAA != SP and parameter size greater than size of
1794 // all remained GPR regs. In that case we can't split parameter, we must
1795 // send it to stack. We also must set NCRN to R4, so waste all
1796 // remained registers.
1797 const unsigned NSAAOffset = State->getNextStackOffset();
1798 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1799 while (State->AllocateReg(GPRArgRegs, 4))
1804 // First register for byval parameter is the first register that wasn't
1805 // allocated before this method call, so it would be "reg".
1806 // If parameter is small enough to be saved in range [reg, r4), then
1807 // the end (first after last) register would be reg + param-size-in-regs,
1808 // else parameter would be splitted between registers and stack,
1809 // end register would be r4 in this case.
1810 unsigned ByValRegBegin = reg;
1811 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1812 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1813 // Note, first register is allocated in the beginning of function already,
1814 // allocate remained amount of registers we need.
1815 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1816 State->AllocateReg(GPRArgRegs, 4);
1817 // A byval parameter that is split between registers and memory needs its
1818 // size truncated here.
1819 // In the case where the entire structure fits in registers, we set the
1820 // size in memory to zero.
1829 /// MatchingStackOffset - Return true if the given stack call argument is
1830 /// already available in the same position (relatively) of the caller's
1831 /// incoming argument stack.
1833 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1834 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1835 const TargetInstrInfo *TII) {
1836 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1838 if (Arg.getOpcode() == ISD::CopyFromReg) {
1839 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1840 if (!TargetRegisterInfo::isVirtualRegister(VR))
1842 MachineInstr *Def = MRI->getVRegDef(VR);
1845 if (!Flags.isByVal()) {
1846 if (!TII->isLoadFromStackSlot(Def, FI))
1851 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1852 if (Flags.isByVal())
1853 // ByVal argument is passed in as a pointer but it's now being
1854 // dereferenced. e.g.
1855 // define @foo(%struct.X* %A) {
1856 // tail call @bar(%struct.X* byval %A)
1859 SDValue Ptr = Ld->getBasePtr();
1860 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1863 FI = FINode->getIndex();
1867 assert(FI != INT_MAX);
1868 if (!MFI->isFixedObjectIndex(FI))
1870 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1873 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1874 /// for tail call optimization. Targets which want to do tail call
1875 /// optimization should implement this function.
1877 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1878 CallingConv::ID CalleeCC,
1880 bool isCalleeStructRet,
1881 bool isCallerStructRet,
1882 const SmallVectorImpl<ISD::OutputArg> &Outs,
1883 const SmallVectorImpl<SDValue> &OutVals,
1884 const SmallVectorImpl<ISD::InputArg> &Ins,
1885 SelectionDAG& DAG) const {
1886 const Function *CallerF = DAG.getMachineFunction().getFunction();
1887 CallingConv::ID CallerCC = CallerF->getCallingConv();
1888 bool CCMatch = CallerCC == CalleeCC;
1890 // Look for obvious safe cases to perform tail call optimization that do not
1891 // require ABI changes. This is what gcc calls sibcall.
1893 // Do not sibcall optimize vararg calls unless the call site is not passing
1895 if (isVarArg && !Outs.empty())
1898 // Exception-handling functions need a special set of instructions to indicate
1899 // a return to the hardware. Tail-calling another function would probably
1901 if (CallerF->hasFnAttribute("interrupt"))
1904 // Also avoid sibcall optimization if either caller or callee uses struct
1905 // return semantics.
1906 if (isCalleeStructRet || isCallerStructRet)
1909 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1910 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1911 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1912 // support in the assembler and linker to be used. This would need to be
1913 // fixed to fully support tail calls in Thumb1.
1915 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1916 // LR. This means if we need to reload LR, it takes an extra instructions,
1917 // which outweighs the value of the tail call; but here we don't know yet
1918 // whether LR is going to be used. Probably the right approach is to
1919 // generate the tail call here and turn it back into CALL/RET in
1920 // emitEpilogue if LR is used.
1922 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1923 // but we need to make sure there are enough registers; the only valid
1924 // registers are the 4 used for parameters. We don't currently do this
1926 if (Subtarget->isThumb1Only())
1929 // If the calling conventions do not match, then we'd better make sure the
1930 // results are returned in the same way as what the caller expects.
1932 SmallVector<CCValAssign, 16> RVLocs1;
1933 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1934 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1935 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1937 SmallVector<CCValAssign, 16> RVLocs2;
1938 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1939 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1940 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1942 if (RVLocs1.size() != RVLocs2.size())
1944 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1945 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1947 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1949 if (RVLocs1[i].isRegLoc()) {
1950 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1953 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1959 // If Caller's vararg or byval argument has been split between registers and
1960 // stack, do not perform tail call, since part of the argument is in caller's
1962 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1963 getInfo<ARMFunctionInfo>();
1964 if (AFI_Caller->getArgRegsSaveSize())
1967 // If the callee takes no arguments then go on to check the results of the
1969 if (!Outs.empty()) {
1970 // Check if stack adjustment is needed. For now, do not do this if any
1971 // argument is passed on the stack.
1972 SmallVector<CCValAssign, 16> ArgLocs;
1973 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1974 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1975 CCInfo.AnalyzeCallOperands(Outs,
1976 CCAssignFnForNode(CalleeCC, false, isVarArg));
1977 if (CCInfo.getNextStackOffset()) {
1978 MachineFunction &MF = DAG.getMachineFunction();
1980 // Check if the arguments are already laid out in the right way as
1981 // the caller's fixed stack objects.
1982 MachineFrameInfo *MFI = MF.getFrameInfo();
1983 const MachineRegisterInfo *MRI = &MF.getRegInfo();
1984 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1985 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1987 ++i, ++realArgIdx) {
1988 CCValAssign &VA = ArgLocs[i];
1989 EVT RegVT = VA.getLocVT();
1990 SDValue Arg = OutVals[realArgIdx];
1991 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1992 if (VA.getLocInfo() == CCValAssign::Indirect)
1994 if (VA.needsCustom()) {
1995 // f64 and vector types are split into multiple registers or
1996 // register/stack-slot combinations. The types will not match
1997 // the registers; give up on memory f64 refs until we figure
1998 // out what to do about this.
2001 if (!ArgLocs[++i].isRegLoc())
2003 if (RegVT == MVT::v2f64) {
2004 if (!ArgLocs[++i].isRegLoc())
2006 if (!ArgLocs[++i].isRegLoc())
2009 } else if (!VA.isRegLoc()) {
2010 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2022 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2023 MachineFunction &MF, bool isVarArg,
2024 const SmallVectorImpl<ISD::OutputArg> &Outs,
2025 LLVMContext &Context) const {
2026 SmallVector<CCValAssign, 16> RVLocs;
2027 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2028 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2032 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2033 SDLoc DL, SelectionDAG &DAG) {
2034 const MachineFunction &MF = DAG.getMachineFunction();
2035 const Function *F = MF.getFunction();
2037 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2039 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2040 // version of the "preferred return address". These offsets affect the return
2041 // instruction if this is a return from PL1 without hypervisor extensions.
2042 // IRQ/FIQ: +4 "subs pc, lr, #4"
2043 // SWI: 0 "subs pc, lr, #0"
2044 // ABORT: +4 "subs pc, lr, #4"
2045 // UNDEF: +4/+2 "subs pc, lr, #0"
2046 // UNDEF varies depending on where the exception came from ARM or Thumb
2047 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2050 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2053 else if (IntKind == "SWI" || IntKind == "UNDEF")
2056 report_fatal_error("Unsupported interrupt attribute. If present, value "
2057 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2059 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2061 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2065 ARMTargetLowering::LowerReturn(SDValue Chain,
2066 CallingConv::ID CallConv, bool isVarArg,
2067 const SmallVectorImpl<ISD::OutputArg> &Outs,
2068 const SmallVectorImpl<SDValue> &OutVals,
2069 SDLoc dl, SelectionDAG &DAG) const {
2071 // CCValAssign - represent the assignment of the return value to a location.
2072 SmallVector<CCValAssign, 16> RVLocs;
2074 // CCState - Info about the registers and stack slots.
2075 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2076 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2078 // Analyze outgoing return values.
2079 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2083 SmallVector<SDValue, 4> RetOps;
2084 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2086 // Copy the result values into the output registers.
2087 for (unsigned i = 0, realRVLocIdx = 0;
2089 ++i, ++realRVLocIdx) {
2090 CCValAssign &VA = RVLocs[i];
2091 assert(VA.isRegLoc() && "Can only return in registers!");
2093 SDValue Arg = OutVals[realRVLocIdx];
2095 switch (VA.getLocInfo()) {
2096 default: llvm_unreachable("Unknown loc info!");
2097 case CCValAssign::Full: break;
2098 case CCValAssign::BCvt:
2099 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2103 if (VA.needsCustom()) {
2104 if (VA.getLocVT() == MVT::v2f64) {
2105 // Extract the first half and return it in two registers.
2106 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2107 DAG.getConstant(0, MVT::i32));
2108 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2109 DAG.getVTList(MVT::i32, MVT::i32), Half);
2111 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2112 Flag = Chain.getValue(1);
2113 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2114 VA = RVLocs[++i]; // skip ahead to next loc
2115 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2116 HalfGPRs.getValue(1), Flag);
2117 Flag = Chain.getValue(1);
2118 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2119 VA = RVLocs[++i]; // skip ahead to next loc
2121 // Extract the 2nd half and fall through to handle it as an f64 value.
2122 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2123 DAG.getConstant(1, MVT::i32));
2125 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2127 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2128 DAG.getVTList(MVT::i32, MVT::i32), Arg);
2129 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2130 Flag = Chain.getValue(1);
2131 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2132 VA = RVLocs[++i]; // skip ahead to next loc
2133 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2136 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2138 // Guarantee that all emitted copies are
2139 // stuck together, avoiding something bad.
2140 Flag = Chain.getValue(1);
2141 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2144 // Update chain and glue.
2147 RetOps.push_back(Flag);
2149 // CPUs which aren't M-class use a special sequence to return from
2150 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2151 // though we use "subs pc, lr, #N").
2153 // M-class CPUs actually use a normal return sequence with a special
2154 // (hardware-provided) value in LR, so the normal code path works.
2155 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2156 !Subtarget->isMClass()) {
2157 if (Subtarget->isThumb1Only())
2158 report_fatal_error("interrupt attribute is not supported in Thumb1");
2159 return LowerInterruptReturn(RetOps, dl, DAG);
2162 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2165 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2166 if (N->getNumValues() != 1)
2168 if (!N->hasNUsesOfValue(1, 0))
2171 SDValue TCChain = Chain;
2172 SDNode *Copy = *N->use_begin();
2173 if (Copy->getOpcode() == ISD::CopyToReg) {
2174 // If the copy has a glue operand, we conservatively assume it isn't safe to
2175 // perform a tail call.
2176 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2178 TCChain = Copy->getOperand(0);
2179 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2180 SDNode *VMov = Copy;
2181 // f64 returned in a pair of GPRs.
2182 SmallPtrSet<SDNode*, 2> Copies;
2183 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2185 if (UI->getOpcode() != ISD::CopyToReg)
2189 if (Copies.size() > 2)
2192 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2194 SDValue UseChain = UI->getOperand(0);
2195 if (Copies.count(UseChain.getNode()))
2202 } else if (Copy->getOpcode() == ISD::BITCAST) {
2203 // f32 returned in a single GPR.
2204 if (!Copy->hasOneUse())
2206 Copy = *Copy->use_begin();
2207 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2209 TCChain = Copy->getOperand(0);
2214 bool HasRet = false;
2215 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2217 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2218 UI->getOpcode() != ARMISD::INTRET_FLAG)
2230 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2231 if (!Subtarget->supportsTailCall())
2234 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2237 return !Subtarget->isThumb1Only();
2240 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2241 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2242 // one of the above mentioned nodes. It has to be wrapped because otherwise
2243 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2244 // be used to form addressing mode. These wrapped nodes will be selected
2246 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2247 EVT PtrVT = Op.getValueType();
2248 // FIXME there is no actual debug info here
2250 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2252 if (CP->isMachineConstantPoolEntry())
2253 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2254 CP->getAlignment());
2256 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2257 CP->getAlignment());
2258 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2261 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2262 return MachineJumpTableInfo::EK_Inline;
2265 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2266 SelectionDAG &DAG) const {
2267 MachineFunction &MF = DAG.getMachineFunction();
2268 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2269 unsigned ARMPCLabelIndex = 0;
2271 EVT PtrVT = getPointerTy();
2272 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2273 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2275 if (RelocM == Reloc::Static) {
2276 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2278 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2279 ARMPCLabelIndex = AFI->createPICLabelUId();
2280 ARMConstantPoolValue *CPV =
2281 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2282 ARMCP::CPBlockAddress, PCAdj);
2283 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2285 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2286 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2287 MachinePointerInfo::getConstantPool(),
2288 false, false, false, 0);
2289 if (RelocM == Reloc::Static)
2291 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2292 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2295 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2297 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2298 SelectionDAG &DAG) const {
2300 EVT PtrVT = getPointerTy();
2301 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2302 MachineFunction &MF = DAG.getMachineFunction();
2303 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2304 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2305 ARMConstantPoolValue *CPV =
2306 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2307 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2308 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2309 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2310 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2311 MachinePointerInfo::getConstantPool(),
2312 false, false, false, 0);
2313 SDValue Chain = Argument.getValue(1);
2315 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2316 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2318 // call __tls_get_addr.
2321 Entry.Node = Argument;
2322 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2323 Args.push_back(Entry);
2324 // FIXME: is there useful debug info available here?
2325 TargetLowering::CallLoweringInfo CLI(Chain,
2326 (Type *) Type::getInt32Ty(*DAG.getContext()),
2327 false, false, false, false,
2328 0, CallingConv::C, /*isTailCall=*/false,
2329 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2330 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2331 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2332 return CallResult.first;
2335 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2336 // "local exec" model.
2338 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2340 TLSModel::Model model) const {
2341 const GlobalValue *GV = GA->getGlobal();
2344 SDValue Chain = DAG.getEntryNode();
2345 EVT PtrVT = getPointerTy();
2346 // Get the Thread Pointer
2347 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2349 if (model == TLSModel::InitialExec) {
2350 MachineFunction &MF = DAG.getMachineFunction();
2351 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2352 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2353 // Initial exec model.
2354 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2355 ARMConstantPoolValue *CPV =
2356 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2357 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2359 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2360 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2361 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2362 MachinePointerInfo::getConstantPool(),
2363 false, false, false, 0);
2364 Chain = Offset.getValue(1);
2366 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2367 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2369 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2370 MachinePointerInfo::getConstantPool(),
2371 false, false, false, 0);
2374 assert(model == TLSModel::LocalExec);
2375 ARMConstantPoolValue *CPV =
2376 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2377 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2378 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2379 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2380 MachinePointerInfo::getConstantPool(),
2381 false, false, false, 0);
2384 // The address of the thread local variable is the add of the thread
2385 // pointer with the offset of the variable.
2386 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2390 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2391 // TODO: implement the "local dynamic" model
2392 assert(Subtarget->isTargetELF() &&
2393 "TLS not implemented for non-ELF targets");
2394 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2396 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2399 case TLSModel::GeneralDynamic:
2400 case TLSModel::LocalDynamic:
2401 return LowerToTLSGeneralDynamicModel(GA, DAG);
2402 case TLSModel::InitialExec:
2403 case TLSModel::LocalExec:
2404 return LowerToTLSExecModels(GA, DAG, model);
2406 llvm_unreachable("bogus TLS model");
2409 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2410 SelectionDAG &DAG) const {
2411 EVT PtrVT = getPointerTy();
2413 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2414 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2415 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2416 ARMConstantPoolValue *CPV =
2417 ARMConstantPoolConstant::Create(GV,
2418 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2419 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2420 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2421 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2423 MachinePointerInfo::getConstantPool(),
2424 false, false, false, 0);
2425 SDValue Chain = Result.getValue(1);
2426 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2427 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2429 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2430 MachinePointerInfo::getGOT(),
2431 false, false, false, 0);
2435 // If we have T2 ops, we can materialize the address directly via movt/movw
2436 // pair. This is always cheaper.
2437 if (Subtarget->useMovt()) {
2439 // FIXME: Once remat is capable of dealing with instructions with register
2440 // operands, expand this into two nodes.
2441 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2442 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2444 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2445 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2446 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2447 MachinePointerInfo::getConstantPool(),
2448 false, false, false, 0);
2452 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2453 SelectionDAG &DAG) const {
2454 EVT PtrVT = getPointerTy();
2456 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2457 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2459 if (Subtarget->useMovt())
2462 // FIXME: Once remat is capable of dealing with instructions with register
2463 // operands, expand this into multiple nodes
2465 RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2467 SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2468 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2470 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2471 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2472 MachinePointerInfo::getGOT(), false, false, false, 0);
2476 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2477 SelectionDAG &DAG) const {
2478 assert(Subtarget->isTargetELF() &&
2479 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2480 MachineFunction &MF = DAG.getMachineFunction();
2481 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2482 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2483 EVT PtrVT = getPointerTy();
2485 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2486 ARMConstantPoolValue *CPV =
2487 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2488 ARMPCLabelIndex, PCAdj);
2489 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2490 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2491 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2492 MachinePointerInfo::getConstantPool(),
2493 false, false, false, 0);
2494 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2495 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2499 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2501 SDValue Val = DAG.getConstant(0, MVT::i32);
2502 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2503 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2504 Op.getOperand(1), Val);
2508 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2510 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2511 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2515 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2516 const ARMSubtarget *Subtarget) const {
2517 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2520 default: return SDValue(); // Don't custom lower most intrinsics.
2521 case Intrinsic::arm_thread_pointer: {
2522 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2523 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2525 case Intrinsic::eh_sjlj_lsda: {
2526 MachineFunction &MF = DAG.getMachineFunction();
2527 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2528 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2529 EVT PtrVT = getPointerTy();
2530 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2532 unsigned PCAdj = (RelocM != Reloc::PIC_)
2533 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2534 ARMConstantPoolValue *CPV =
2535 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2536 ARMCP::CPLSDA, PCAdj);
2537 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2538 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2540 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2541 MachinePointerInfo::getConstantPool(),
2542 false, false, false, 0);
2544 if (RelocM == Reloc::PIC_) {
2545 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2546 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2550 case Intrinsic::arm_neon_vmulls:
2551 case Intrinsic::arm_neon_vmullu: {
2552 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2553 ? ARMISD::VMULLs : ARMISD::VMULLu;
2554 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2555 Op.getOperand(1), Op.getOperand(2));
2560 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2561 const ARMSubtarget *Subtarget) {
2562 // FIXME: handle "fence singlethread" more efficiently.
2564 if (!Subtarget->hasDataBarrier()) {
2565 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2566 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2568 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2569 "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2570 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2571 DAG.getConstant(0, MVT::i32));
2574 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2575 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2576 unsigned Domain = ARM_MB::ISH;
2577 if (Subtarget->isMClass()) {
2578 // Only a full system barrier exists in the M-class architectures.
2579 Domain = ARM_MB::SY;
2580 } else if (Subtarget->isSwift() && Ord == Release) {
2581 // Swift happens to implement ISHST barriers in a way that's compatible with
2582 // Release semantics but weaker than ISH so we'd be fools not to use
2583 // it. Beware: other processors probably don't!
2584 Domain = ARM_MB::ISHST;
2587 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2588 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2589 DAG.getConstant(Domain, MVT::i32));
2592 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2593 const ARMSubtarget *Subtarget) {
2594 // ARM pre v5TE and Thumb1 does not have preload instructions.
2595 if (!(Subtarget->isThumb2() ||
2596 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2597 // Just preserve the chain.
2598 return Op.getOperand(0);
2601 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2603 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2604 // ARMv7 with MP extension has PLDW.
2605 return Op.getOperand(0);
2607 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2608 if (Subtarget->isThumb()) {
2610 isRead = ~isRead & 1;
2611 isData = ~isData & 1;
2614 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2615 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2616 DAG.getConstant(isData, MVT::i32));
2619 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2620 MachineFunction &MF = DAG.getMachineFunction();
2621 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2623 // vastart just stores the address of the VarArgsFrameIndex slot into the
2624 // memory location argument.
2626 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2627 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2628 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2629 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2630 MachinePointerInfo(SV), false, false, 0);
2634 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2635 SDValue &Root, SelectionDAG &DAG,
2637 MachineFunction &MF = DAG.getMachineFunction();
2638 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2640 const TargetRegisterClass *RC;
2641 if (AFI->isThumb1OnlyFunction())
2642 RC = &ARM::tGPRRegClass;
2644 RC = &ARM::GPRRegClass;
2646 // Transform the arguments stored in physical registers into virtual ones.
2647 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2648 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2651 if (NextVA.isMemLoc()) {
2652 MachineFrameInfo *MFI = MF.getFrameInfo();
2653 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2655 // Create load node to retrieve arguments from the stack.
2656 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2657 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2658 MachinePointerInfo::getFixedStack(FI),
2659 false, false, false, 0);
2661 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2662 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2665 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2669 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2670 unsigned InRegsParamRecordIdx,
2672 unsigned &ArgRegsSize,
2673 unsigned &ArgRegsSaveSize)
2676 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2677 unsigned RBegin, REnd;
2678 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2679 NumGPRs = REnd - RBegin;
2681 unsigned int firstUnalloced;
2682 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2683 sizeof(GPRArgRegs) /
2684 sizeof(GPRArgRegs[0]));
2685 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2688 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2689 ArgRegsSize = NumGPRs * 4;
2691 // If parameter is split between stack and GPRs...
2692 if (NumGPRs && Align > 4 &&
2693 (ArgRegsSize < ArgSize ||
2694 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2695 // Add padding for part of param recovered from GPRs. For example,
2696 // if Align == 8, its last byte must be at address K*8 - 1.
2697 // We need to do it, since remained (stack) part of parameter has
2698 // stack alignment, and we need to "attach" "GPRs head" without gaps
2701 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2702 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2704 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2706 OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2707 ArgRegsSaveSize = ArgRegsSize + Padding;
2709 // We don't need to extend regs save size for byval parameters if they
2710 // are passed via GPRs only.
2711 ArgRegsSaveSize = ArgRegsSize;
2714 // The remaining GPRs hold either the beginning of variable-argument
2715 // data, or the beginning of an aggregate passed by value (usually
2716 // byval). Either way, we allocate stack slots adjacent to the data
2717 // provided by our caller, and store the unallocated registers there.
2718 // If this is a variadic function, the va_list pointer will begin with
2719 // these values; otherwise, this reassembles a (byval) structure that
2720 // was split between registers and memory.
2721 // Return: The frame index registers were stored into.
2723 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2724 SDLoc dl, SDValue &Chain,
2725 const Value *OrigArg,
2726 unsigned InRegsParamRecordIdx,
2727 unsigned OffsetFromOrigArg,
2731 unsigned ByValStoreOffset,
2732 unsigned TotalArgRegsSaveSize) const {
2734 // Currently, two use-cases possible:
2735 // Case #1. Non-var-args function, and we meet first byval parameter.
2736 // Setup first unallocated register as first byval register;
2737 // eat all remained registers
2738 // (these two actions are performed by HandleByVal method).
2739 // Then, here, we initialize stack frame with
2740 // "store-reg" instructions.
2741 // Case #2. Var-args function, that doesn't contain byval parameters.
2742 // The same: eat all remained unallocated registers,
2743 // initialize stack frame.
2745 MachineFunction &MF = DAG.getMachineFunction();
2746 MachineFrameInfo *MFI = MF.getFrameInfo();
2747 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2748 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2749 unsigned RBegin, REnd;
2750 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2751 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2752 firstRegToSaveIndex = RBegin - ARM::R0;
2753 lastRegToSaveIndex = REnd - ARM::R0;
2755 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2756 (GPRArgRegs, array_lengthof(GPRArgRegs));
2757 lastRegToSaveIndex = 4;
2760 unsigned ArgRegsSize, ArgRegsSaveSize;
2761 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2762 ArgRegsSize, ArgRegsSaveSize);
2764 // Store any by-val regs to their spots on the stack so that they may be
2765 // loaded by deferencing the result of formal parameter pointer or va_next.
2766 // Note: once stack area for byval/varargs registers
2767 // was initialized, it can't be initialized again.
2768 if (ArgRegsSaveSize) {
2769 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2772 assert(AFI->getStoredByValParamsPadding() == 0 &&
2773 "The only parameter may be padded.");
2774 AFI->setStoredByValParamsPadding(Padding);
2777 int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2780 (int64_t)TotalArgRegsSaveSize,
2782 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2784 MFI->CreateFixedObject(Padding,
2785 ArgOffset + ByValStoreOffset -
2786 (int64_t)ArgRegsSaveSize,
2790 SmallVector<SDValue, 4> MemOps;
2791 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2792 ++firstRegToSaveIndex, ++i) {
2793 const TargetRegisterClass *RC;
2794 if (AFI->isThumb1OnlyFunction())
2795 RC = &ARM::tGPRRegClass;
2797 RC = &ARM::GPRRegClass;
2799 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2800 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2802 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2803 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2805 MemOps.push_back(Store);
2806 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2807 DAG.getConstant(4, getPointerTy()));
2810 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2812 if (!MemOps.empty())
2813 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2817 // We cannot allocate a zero-byte object for the first variadic argument,
2818 // so just make up a size.
2821 // This will point to the next argument passed via stack.
2822 return MFI->CreateFixedObject(
2823 ArgSize, ArgOffset, !ForceMutable);
2827 // Setup stack frame, the va_list pointer will start from.
2829 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2830 SDLoc dl, SDValue &Chain,
2832 unsigned TotalArgRegsSaveSize,
2833 bool ForceMutable) const {
2834 MachineFunction &MF = DAG.getMachineFunction();
2835 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2837 // Try to store any remaining integer argument regs
2838 // to their spots on the stack so that they may be loaded by deferencing
2839 // the result of va_next.
2840 // If there is no regs to be stored, just point address after last
2841 // argument passed via stack.
2843 StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2844 CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2845 0, TotalArgRegsSaveSize);
2847 AFI->setVarArgsFrameIndex(FrameIndex);
2851 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2852 CallingConv::ID CallConv, bool isVarArg,
2853 const SmallVectorImpl<ISD::InputArg>
2855 SDLoc dl, SelectionDAG &DAG,
2856 SmallVectorImpl<SDValue> &InVals)
2858 MachineFunction &MF = DAG.getMachineFunction();
2859 MachineFrameInfo *MFI = MF.getFrameInfo();
2861 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2863 // Assign locations to all of the incoming arguments.
2864 SmallVector<CCValAssign, 16> ArgLocs;
2865 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2866 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2867 CCInfo.AnalyzeFormalArguments(Ins,
2868 CCAssignFnForNode(CallConv, /* Return*/ false,
2871 SmallVector<SDValue, 16> ArgValues;
2872 int lastInsIndex = -1;
2874 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2875 unsigned CurArgIdx = 0;
2877 // Initially ArgRegsSaveSize is zero.
2878 // Then we increase this value each time we meet byval parameter.
2879 // We also increase this value in case of varargs function.
2880 AFI->setArgRegsSaveSize(0);
2882 unsigned ByValStoreOffset = 0;
2883 unsigned TotalArgRegsSaveSize = 0;
2884 unsigned ArgRegsSaveSizeMaxAlign = 4;
2886 // Calculate the amount of stack space that we need to allocate to store
2887 // byval and variadic arguments that are passed in registers.
2888 // We need to know this before we allocate the first byval or variadic
2889 // argument, as they will be allocated a stack slot below the CFA (Canonical
2890 // Frame Address, the stack pointer at entry to the function).
2891 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892 CCValAssign &VA = ArgLocs[i];
2893 if (VA.isMemLoc()) {
2894 int index = VA.getValNo();
2895 if (index != lastInsIndex) {
2896 ISD::ArgFlagsTy Flags = Ins[index].Flags;
2897 if (Flags.isByVal()) {
2898 unsigned ExtraArgRegsSize;
2899 unsigned ExtraArgRegsSaveSize;
2900 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2901 Flags.getByValSize(),
2902 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2904 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2905 if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2906 ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2907 CCInfo.nextInRegsParam();
2909 lastInsIndex = index;
2913 CCInfo.rewindByValRegsInfo();
2916 unsigned ExtraArgRegsSize;
2917 unsigned ExtraArgRegsSaveSize;
2918 computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2919 ExtraArgRegsSize, ExtraArgRegsSaveSize);
2920 TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2922 // If the arg regs save area contains N-byte aligned values, the
2923 // bottom of it must be at least N-byte aligned.
2924 TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2925 TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2927 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2928 CCValAssign &VA = ArgLocs[i];
2929 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2930 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2931 // Arguments stored in registers.
2932 if (VA.isRegLoc()) {
2933 EVT RegVT = VA.getLocVT();
2935 if (VA.needsCustom()) {
2936 // f64 and vector types are split up into multiple registers or
2937 // combinations of registers and stack slots.
2938 if (VA.getLocVT() == MVT::v2f64) {
2939 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2941 VA = ArgLocs[++i]; // skip ahead to next loc
2943 if (VA.isMemLoc()) {
2944 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2945 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2946 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2947 MachinePointerInfo::getFixedStack(FI),
2948 false, false, false, 0);
2950 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2953 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2954 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2955 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2956 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2957 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2959 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2962 const TargetRegisterClass *RC;
2964 if (RegVT == MVT::f32)
2965 RC = &ARM::SPRRegClass;
2966 else if (RegVT == MVT::f64)
2967 RC = &ARM::DPRRegClass;
2968 else if (RegVT == MVT::v2f64)
2969 RC = &ARM::QPRRegClass;
2970 else if (RegVT == MVT::i32)
2971 RC = AFI->isThumb1OnlyFunction() ?
2972 (const TargetRegisterClass*)&ARM::tGPRRegClass :
2973 (const TargetRegisterClass*)&ARM::GPRRegClass;
2975 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2977 // Transform the arguments in physical registers into virtual ones.
2978 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2979 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2982 // If this is an 8 or 16-bit value, it is really passed promoted
2983 // to 32 bits. Insert an assert[sz]ext to capture this, then
2984 // truncate to the right size.
2985 switch (VA.getLocInfo()) {
2986 default: llvm_unreachable("Unknown loc info!");
2987 case CCValAssign::Full: break;
2988 case CCValAssign::BCvt:
2989 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2991 case CCValAssign::SExt:
2992 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2993 DAG.getValueType(VA.getValVT()));
2994 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2996 case CCValAssign::ZExt:
2997 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2998 DAG.getValueType(VA.getValVT()));
2999 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3003 InVals.push_back(ArgValue);
3005 } else { // VA.isRegLoc()
3008 assert(VA.isMemLoc());
3009 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3011 int index = ArgLocs[i].getValNo();
3013 // Some Ins[] entries become multiple ArgLoc[] entries.
3014 // Process them only once.
3015 if (index != lastInsIndex)
3017 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3018 // FIXME: For now, all byval parameter objects are marked mutable.
3019 // This can be changed with more analysis.
3020 // In case of tail call optimization mark all arguments mutable.
3021 // Since they could be overwritten by lowering of arguments in case of
3023 if (Flags.isByVal()) {
3024 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3026 ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3027 int FrameIndex = StoreByValRegs(
3028 CCInfo, DAG, dl, Chain, CurOrigArg,
3030 Ins[VA.getValNo()].PartOffset,
3031 VA.getLocMemOffset(),
3032 Flags.getByValSize(),
3033 true /*force mutable frames*/,
3035 TotalArgRegsSaveSize);
3036 ByValStoreOffset += Flags.getByValSize();
3037 ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3038 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3039 CCInfo.nextInRegsParam();
3041 unsigned FIOffset = VA.getLocMemOffset();
3042 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3045 // Create load nodes to retrieve arguments from the stack.
3046 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3047 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3048 MachinePointerInfo::getFixedStack(FI),
3049 false, false, false, 0));
3051 lastInsIndex = index;
3058 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3059 CCInfo.getNextStackOffset(),
3060 TotalArgRegsSaveSize);
3062 AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3067 /// isFloatingPointZero - Return true if this is +0.0.
3068 static bool isFloatingPointZero(SDValue Op) {
3069 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3070 return CFP->getValueAPF().isPosZero();
3071 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3072 // Maybe this has already been legalized into the constant pool?
3073 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3074 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3075 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3076 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3077 return CFP->getValueAPF().isPosZero();
3083 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3084 /// the given operands.
3086 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3087 SDValue &ARMcc, SelectionDAG &DAG,
3089 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3090 unsigned C = RHSC->getZExtValue();
3091 if (!isLegalICmpImmediate(C)) {
3092 // Constant does not fit, try adjusting it by one?
3097 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3098 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3099 RHS = DAG.getConstant(C-1, MVT::i32);
3104 if (C != 0 && isLegalICmpImmediate(C-1)) {
3105 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3106 RHS = DAG.getConstant(C-1, MVT::i32);
3111 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3112 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3113 RHS = DAG.getConstant(C+1, MVT::i32);
3118 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3119 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3120 RHS = DAG.getConstant(C+1, MVT::i32);
3127 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3128 ARMISD::NodeType CompareType;
3131 CompareType = ARMISD::CMP;
3136 CompareType = ARMISD::CMPZ;
3139 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3140 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3143 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3145 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3148 if (!isFloatingPointZero(RHS))
3149 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3151 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3152 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3155 /// duplicateCmp - Glue values can have only one use, so this function
3156 /// duplicates a comparison node.
3158 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3159 unsigned Opc = Cmp.getOpcode();
3161 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3162 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3164 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3165 Cmp = Cmp.getOperand(0);
3166 Opc = Cmp.getOpcode();
3167 if (Opc == ARMISD::CMPFP)
3168 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3170 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3171 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3173 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3176 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3177 SDValue Cond = Op.getOperand(0);
3178 SDValue SelectTrue = Op.getOperand(1);
3179 SDValue SelectFalse = Op.getOperand(2);
3184 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3185 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3187 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3188 const ConstantSDNode *CMOVTrue =
3189 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3190 const ConstantSDNode *CMOVFalse =
3191 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3193 if (CMOVTrue && CMOVFalse) {
3194 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3195 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3199 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3201 False = SelectFalse;
3202 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3207 if (True.getNode() && False.getNode()) {
3208 EVT VT = Op.getValueType();
3209 SDValue ARMcc = Cond.getOperand(2);
3210 SDValue CCR = Cond.getOperand(3);
3211 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3212 assert(True.getValueType() == VT);
3213 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3218 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3219 // undefined bits before doing a full-word comparison with zero.
3220 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3221 DAG.getConstant(1, Cond.getValueType()));
3223 return DAG.getSelectCC(dl, Cond,
3224 DAG.getConstant(0, Cond.getValueType()),
3225 SelectTrue, SelectFalse, ISD::SETNE);
3228 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3229 if (CC == ISD::SETNE)
3231 return ISD::getSetCCInverse(CC, true);
3234 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3235 bool &swpCmpOps, bool &swpVselOps) {
3236 // Start by selecting the GE condition code for opcodes that return true for
3238 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3240 CondCode = ARMCC::GE;
3242 // and GT for opcodes that return false for 'equality'.
3243 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3245 CondCode = ARMCC::GT;
3247 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3248 // to swap the compare operands.
3249 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3253 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3254 // If we have an unordered opcode, we need to swap the operands to the VSEL
3255 // instruction (effectively negating the condition).
3257 // This also has the effect of swapping which one of 'less' or 'greater'
3258 // returns true, so we also swap the compare operands. It also switches
3259 // whether we return true for 'equality', so we compensate by picking the
3260 // opposite condition code to our original choice.
3261 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3262 CC == ISD::SETUGT) {
3263 swpCmpOps = !swpCmpOps;
3264 swpVselOps = !swpVselOps;
3265 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3268 // 'ordered' is 'anything but unordered', so use the VS condition code and
3269 // swap the VSEL operands.
3270 if (CC == ISD::SETO) {
3271 CondCode = ARMCC::VS;
3275 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3276 // code and swap the VSEL operands.
3277 if (CC == ISD::SETUNE) {
3278 CondCode = ARMCC::EQ;
3283 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3284 EVT VT = Op.getValueType();
3285 SDValue LHS = Op.getOperand(0);
3286 SDValue RHS = Op.getOperand(1);
3287 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3288 SDValue TrueVal = Op.getOperand(2);
3289 SDValue FalseVal = Op.getOperand(3);
3292 if (LHS.getValueType() == MVT::i32) {
3293 // Try to generate VSEL on ARMv8.
3294 // The VSEL instruction can't use all the usual ARM condition
3295 // codes: it only has two bits to select the condition code, so it's
3296 // constrained to use only GE, GT, VS and EQ.
3298 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3299 // swap the operands of the previous compare instruction (effectively
3300 // inverting the compare condition, swapping 'less' and 'greater') and
3301 // sometimes need to swap the operands to the VSEL (which inverts the
3302 // condition in the sense of firing whenever the previous condition didn't)
3303 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3304 TrueVal.getValueType() == MVT::f64)) {
3305 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3306 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3307 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3308 CC = getInverseCCForVSEL(CC);
3309 std::swap(TrueVal, FalseVal);
3314 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3315 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3316 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3320 ARMCC::CondCodes CondCode, CondCode2;
3321 FPCCToARMCC(CC, CondCode, CondCode2);
3323 // Try to generate VSEL on ARMv8.
3324 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3325 TrueVal.getValueType() == MVT::f64)) {
3326 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3327 // same operands, as follows:
3328 // c = fcmp [ogt, olt, ugt, ult] a, b
3330 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3331 // handled differently than the original code sequence.
3332 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3334 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3335 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3336 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3337 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3340 bool swpCmpOps = false;
3341 bool swpVselOps = false;
3342 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3344 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3345 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3347 std::swap(LHS, RHS);
3349 std::swap(TrueVal, FalseVal);
3353 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3354 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3355 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3356 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3358 if (CondCode2 != ARMCC::AL) {
3359 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3360 // FIXME: Needs another CMP because flag can have but one use.
3361 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3362 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3363 Result, TrueVal, ARMcc2, CCR, Cmp2);
3368 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3369 /// to morph to an integer compare sequence.
3370 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3371 const ARMSubtarget *Subtarget) {
3372 SDNode *N = Op.getNode();
3373 if (!N->hasOneUse())
3374 // Otherwise it requires moving the value from fp to integer registers.
3376 if (!N->getNumValues())
3378 EVT VT = Op.getValueType();
3379 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3380 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3381 // vmrs are very slow, e.g. cortex-a8.
3384 if (isFloatingPointZero(Op)) {
3388 return ISD::isNormalLoad(N);
3391 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3392 if (isFloatingPointZero(Op))
3393 return DAG.getConstant(0, MVT::i32);
3395 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3396 return DAG.getLoad(MVT::i32, SDLoc(Op),
3397 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3398 Ld->isVolatile(), Ld->isNonTemporal(),
3399 Ld->isInvariant(), Ld->getAlignment());
3401 llvm_unreachable("Unknown VFP cmp argument!");
3404 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3405 SDValue &RetVal1, SDValue &RetVal2) {
3406 if (isFloatingPointZero(Op)) {
3407 RetVal1 = DAG.getConstant(0, MVT::i32);
3408 RetVal2 = DAG.getConstant(0, MVT::i32);
3412 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3413 SDValue Ptr = Ld->getBasePtr();
3414 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3415 Ld->getChain(), Ptr,
3416 Ld->getPointerInfo(),
3417 Ld->isVolatile(), Ld->isNonTemporal(),
3418 Ld->isInvariant(), Ld->getAlignment());
3420 EVT PtrType = Ptr.getValueType();
3421 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3422 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3423 PtrType, Ptr, DAG.getConstant(4, PtrType));
3424 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3425 Ld->getChain(), NewPtr,
3426 Ld->getPointerInfo().getWithOffset(4),
3427 Ld->isVolatile(), Ld->isNonTemporal(),
3428 Ld->isInvariant(), NewAlign);
3432 llvm_unreachable("Unknown VFP cmp argument!");
3435 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3436 /// f32 and even f64 comparisons to integer ones.
3438 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3439 SDValue Chain = Op.getOperand(0);
3440 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3441 SDValue LHS = Op.getOperand(2);
3442 SDValue RHS = Op.getOperand(3);
3443 SDValue Dest = Op.getOperand(4);
3446 bool LHSSeenZero = false;
3447 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3448 bool RHSSeenZero = false;
3449 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3450 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3451 // If unsafe fp math optimization is enabled and there are no other uses of
3452 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3453 // to an integer comparison.
3454 if (CC == ISD::SETOEQ)
3456 else if (CC == ISD::SETUNE)
3459 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3461 if (LHS.getValueType() == MVT::f32) {
3462 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3463 bitcastf32Toi32(LHS, DAG), Mask);
3464 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3465 bitcastf32Toi32(RHS, DAG), Mask);
3466 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3467 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3468 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3469 Chain, Dest, ARMcc, CCR, Cmp);
3474 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3475 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3476 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3477 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3478 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3479 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3480 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3481 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3482 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3488 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3489 SDValue Chain = Op.getOperand(0);
3490 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3491 SDValue LHS = Op.getOperand(2);
3492 SDValue RHS = Op.getOperand(3);
3493 SDValue Dest = Op.getOperand(4);
3496 if (LHS.getValueType() == MVT::i32) {
3498 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3499 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3500 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3501 Chain, Dest, ARMcc, CCR, Cmp);
3504 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3506 if (getTargetMachine().Options.UnsafeFPMath &&
3507 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3508 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3509 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3510 if (Result.getNode())
3514 ARMCC::CondCodes CondCode, CondCode2;
3515 FPCCToARMCC(CC, CondCode, CondCode2);
3517 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3518 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3519 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3520 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3521 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3522 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3523 if (CondCode2 != ARMCC::AL) {
3524 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3525 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3526 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3531 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3532 SDValue Chain = Op.getOperand(0);
3533 SDValue Table = Op.getOperand(1);
3534 SDValue Index = Op.getOperand(2);
3537 EVT PTy = getPointerTy();
3538 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3539 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3540 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3541 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3542 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3543 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3544 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3545 if (Subtarget->isThumb2()) {
3546 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3547 // which does another jump to the destination. This also makes it easier
3548 // to translate it to TBB / TBH later.
3549 // FIXME: This might not work if the function is extremely large.
3550 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3551 Addr, Op.getOperand(2), JTI, UId);
3553 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3554 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3555 MachinePointerInfo::getJumpTable(),
3556 false, false, false, 0);
3557 Chain = Addr.getValue(1);
3558 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3559 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3561 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3562 MachinePointerInfo::getJumpTable(),
3563 false, false, false, 0);
3564 Chain = Addr.getValue(1);
3565 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3569 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3570 EVT VT = Op.getValueType();
3573 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3574 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3576 return DAG.UnrollVectorOp(Op.getNode());
3579 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3580 "Invalid type for custom lowering!");
3581 if (VT != MVT::v4i16)
3582 return DAG.UnrollVectorOp(Op.getNode());
3584 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3585 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3588 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3589 EVT VT = Op.getValueType();
3591 return LowerVectorFP_TO_INT(Op, DAG);
3596 switch (Op.getOpcode()) {
3597 default: llvm_unreachable("Invalid opcode!");
3598 case ISD::FP_TO_SINT:
3599 Opc = ARMISD::FTOSI;
3601 case ISD::FP_TO_UINT:
3602 Opc = ARMISD::FTOUI;
3605 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3606 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3609 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3610 EVT VT = Op.getValueType();
3613 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3614 if (VT.getVectorElementType() == MVT::f32)
3616 return DAG.UnrollVectorOp(Op.getNode());
3619 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3620 "Invalid type for custom lowering!");
3621 if (VT != MVT::v4f32)
3622 return DAG.UnrollVectorOp(Op.getNode());
3626 switch (Op.getOpcode()) {
3627 default: llvm_unreachable("Invalid opcode!");
3628 case ISD::SINT_TO_FP:
3629 CastOpc = ISD::SIGN_EXTEND;
3630 Opc = ISD::SINT_TO_FP;
3632 case ISD::UINT_TO_FP:
3633 CastOpc = ISD::ZERO_EXTEND;
3634 Opc = ISD::UINT_TO_FP;
3638 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3639 return DAG.getNode(Opc, dl, VT, Op);
3642 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3643 EVT VT = Op.getValueType();
3645 return LowerVectorINT_TO_FP(Op, DAG);
3650 switch (Op.getOpcode()) {
3651 default: llvm_unreachable("Invalid opcode!");
3652 case ISD::SINT_TO_FP:
3653 Opc = ARMISD::SITOF;
3655 case ISD::UINT_TO_FP:
3656 Opc = ARMISD::UITOF;
3660 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3661 return DAG.getNode(Opc, dl, VT, Op);
3664 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3665 // Implement fcopysign with a fabs and a conditional fneg.
3666 SDValue Tmp0 = Op.getOperand(0);
3667 SDValue Tmp1 = Op.getOperand(1);
3669 EVT VT = Op.getValueType();
3670 EVT SrcVT = Tmp1.getValueType();
3671 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3672 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3673 bool UseNEON = !InGPR && Subtarget->hasNEON();
3676 // Use VBSL to copy the sign bit.
3677 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3678 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3679 DAG.getTargetConstant(EncodedVal, MVT::i32));
3680 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3682 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3683 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3684 DAG.getConstant(32, MVT::i32));
3685 else /*if (VT == MVT::f32)*/
3686 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3687 if (SrcVT == MVT::f32) {
3688 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3690 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3691 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3692 DAG.getConstant(32, MVT::i32));
3693 } else if (VT == MVT::f32)
3694 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3695 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3696 DAG.getConstant(32, MVT::i32));
3697 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3698 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3700 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3702 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3703 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3704 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3706 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3707 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3708 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3709 if (VT == MVT::f32) {
3710 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3711 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3712 DAG.getConstant(0, MVT::i32));
3714 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3720 // Bitcast operand 1 to i32.
3721 if (SrcVT == MVT::f64)
3722 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3724 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3726 // Or in the signbit with integer operations.
3727 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3728 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3729 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3730 if (VT == MVT::f32) {
3731 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3732 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3733 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3734 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3737 // f64: Or the high part with signbit and then combine two parts.
3738 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3740 SDValue Lo = Tmp0.getValue(0);
3741 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3742 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3743 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3746 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3747 MachineFunction &MF = DAG.getMachineFunction();
3748 MachineFrameInfo *MFI = MF.getFrameInfo();
3749 MFI->setReturnAddressIsTaken(true);
3751 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3754 EVT VT = Op.getValueType();
3756 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3758 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3759 SDValue Offset = DAG.getConstant(4, MVT::i32);
3760 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3761 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3762 MachinePointerInfo(), false, false, false, 0);
3765 // Return LR, which contains the return address. Mark it an implicit live-in.
3766 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3767 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3770 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3771 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3772 MFI->setFrameAddressIsTaken(true);
3774 EVT VT = Op.getValueType();
3775 SDLoc dl(Op); // FIXME probably not meaningful
3776 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3777 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3778 ? ARM::R7 : ARM::R11;
3779 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3781 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3782 MachinePointerInfo(),
3783 false, false, false, 0);
3787 /// ExpandBITCAST - If the target supports VFP, this function is called to
3788 /// expand a bit convert where either the source or destination type is i64 to
3789 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3790 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3791 /// vectors), since the legalizer won't know what to do with that.
3792 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3793 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3795 SDValue Op = N->getOperand(0);
3797 // This function is only supposed to be called for i64 types, either as the
3798 // source or destination of the bit convert.
3799 EVT SrcVT = Op.getValueType();
3800 EVT DstVT = N->getValueType(0);
3801 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3802 "ExpandBITCAST called for non-i64 type");
3804 // Turn i64->f64 into VMOVDRR.
3805 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3806 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3807 DAG.getConstant(0, MVT::i32));
3808 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3809 DAG.getConstant(1, MVT::i32));
3810 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3811 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3814 // Turn f64->i64 into VMOVRRD.
3815 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3816 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3817 DAG.getVTList(MVT::i32, MVT::i32), Op);
3818 // Merge the pieces into a single i64 value.
3819 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3825 /// getZeroVector - Returns a vector of specified type with all zero elements.
3826 /// Zero vectors are used to represent vector negation and in those cases
3827 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3828 /// not support i64 elements, so sometimes the zero vectors will need to be
3829 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3831 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3832 assert(VT.isVector() && "Expected a vector type");
3833 // The canonical modified immediate encoding of a zero vector is....0!
3834 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3835 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3836 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3837 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3840 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3841 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3842 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3843 SelectionDAG &DAG) const {
3844 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3845 EVT VT = Op.getValueType();
3846 unsigned VTBits = VT.getSizeInBits();
3848 SDValue ShOpLo = Op.getOperand(0);
3849 SDValue ShOpHi = Op.getOperand(1);
3850 SDValue ShAmt = Op.getOperand(2);
3852 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3854 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3856 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3857 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3858 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3859 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3860 DAG.getConstant(VTBits, MVT::i32));
3861 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3862 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3863 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3865 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3866 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3868 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3869 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3872 SDValue Ops[2] = { Lo, Hi };
3873 return DAG.getMergeValues(Ops, 2, dl);
3876 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3877 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3878 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3879 SelectionDAG &DAG) const {
3880 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3881 EVT VT = Op.getValueType();
3882 unsigned VTBits = VT.getSizeInBits();
3884 SDValue ShOpLo = Op.getOperand(0);
3885 SDValue ShOpHi = Op.getOperand(1);
3886 SDValue ShAmt = Op.getOperand(2);
3889 assert(Op.getOpcode() == ISD::SHL_PARTS);
3890 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3891 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3892 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3893 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3894 DAG.getConstant(VTBits, MVT::i32));
3895 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3896 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3898 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3899 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3900 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3902 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3903 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3906 SDValue Ops[2] = { Lo, Hi };
3907 return DAG.getMergeValues(Ops, 2, dl);
3910 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3911 SelectionDAG &DAG) const {
3912 // The rounding mode is in bits 23:22 of the FPSCR.
3913 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3914 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3915 // so that the shift + and get folded into a bitfield extract.
3917 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3918 DAG.getConstant(Intrinsic::arm_get_fpscr,
3920 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3921 DAG.getConstant(1U << 22, MVT::i32));
3922 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3923 DAG.getConstant(22, MVT::i32));
3924 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3925 DAG.getConstant(3, MVT::i32));
3928 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3929 const ARMSubtarget *ST) {
3930 EVT VT = N->getValueType(0);
3933 if (!ST->hasV6T2Ops())
3936 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3937 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3940 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3941 /// for each 16-bit element from operand, repeated. The basic idea is to
3942 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3944 /// Trace for v4i16:
3945 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3946 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3947 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3948 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3949 /// [b0 b1 b2 b3 b4 b5 b6 b7]
3950 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
3951 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3952 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
3953 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3954 EVT VT = N->getValueType(0);
3957 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3958 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3959 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3960 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3961 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3962 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3965 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3966 /// bit-count for each 16-bit element from the operand. We need slightly
3967 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3968 /// 64/128-bit registers.
3970 /// Trace for v4i16:
3971 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
3972 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3973 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
3974 /// v4i16:Extracted = [k0 k1 k2 k3 ]
3975 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
3976 EVT VT = N->getValueType(0);
3979 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
3980 if (VT.is64BitVector()) {
3981 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
3982 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
3983 DAG.getIntPtrConstant(0));
3985 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
3986 BitCounts, DAG.getIntPtrConstant(0));
3987 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
3991 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
3992 /// bit-count for each 32-bit element from the operand. The idea here is
3993 /// to split the vector into 16-bit elements, leverage the 16-bit count
3994 /// routine, and then combine the results.
3996 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
3997 /// input = [v0 v1 ] (vi: 32-bit elements)
3998 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
3999 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4000 /// vrev: N0 = [k1 k0 k3 k2 ]
4002 /// N1 =+[k1 k0 k3 k2 ]
4004 /// N2 =+[k1 k3 k0 k2 ]
4006 /// Extended =+[k1 k3 k0 k2 ]
4008 /// Extracted=+[k1 k3 ]
4010 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4011 EVT VT = N->getValueType(0);
4014 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4016 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4017 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4018 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4019 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4020 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4022 if (VT.is64BitVector()) {
4023 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4024 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4025 DAG.getIntPtrConstant(0));
4027 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4028 DAG.getIntPtrConstant(0));
4029 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4033 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4034 const ARMSubtarget *ST) {
4035 EVT VT = N->getValueType(0);
4037 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4038 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4039 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4040 "Unexpected type for custom ctpop lowering");
4042 if (VT.getVectorElementType() == MVT::i32)
4043 return lowerCTPOP32BitElements(N, DAG);
4045 return lowerCTPOP16BitElements(N, DAG);
4048 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4049 const ARMSubtarget *ST) {
4050 EVT VT = N->getValueType(0);
4056 // Lower vector shifts on NEON to use VSHL.
4057 assert(ST->hasNEON() && "unexpected vector shift");
4059 // Left shifts translate directly to the vshiftu intrinsic.
4060 if (N->getOpcode() == ISD::SHL)
4061 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4062 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4063 N->getOperand(0), N->getOperand(1));
4065 assert((N->getOpcode() == ISD::SRA ||
4066 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4068 // NEON uses the same intrinsics for both left and right shifts. For
4069 // right shifts, the shift amounts are negative, so negate the vector of
4071 EVT ShiftVT = N->getOperand(1).getValueType();
4072 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4073 getZeroVector(ShiftVT, DAG, dl),
4075 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4076 Intrinsic::arm_neon_vshifts :
4077 Intrinsic::arm_neon_vshiftu);
4078 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4079 DAG.getConstant(vshiftInt, MVT::i32),
4080 N->getOperand(0), NegatedCount);
4083 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4084 const ARMSubtarget *ST) {
4085 EVT VT = N->getValueType(0);
4088 // We can get here for a node like i32 = ISD::SHL i32, i64
4092 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4093 "Unknown shift to lower!");
4095 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4096 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4097 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4100 // If we are in thumb mode, we don't have RRX.
4101 if (ST->isThumb1Only()) return SDValue();
4103 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4104 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4105 DAG.getConstant(0, MVT::i32));
4106 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4107 DAG.getConstant(1, MVT::i32));
4109 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4110 // captures the result into a carry flag.
4111 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4112 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4114 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4115 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4117 // Merge the pieces into a single i64 value.
4118 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4121 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4122 SDValue TmpOp0, TmpOp1;
4123 bool Invert = false;
4127 SDValue Op0 = Op.getOperand(0);
4128 SDValue Op1 = Op.getOperand(1);
4129 SDValue CC = Op.getOperand(2);
4130 EVT VT = Op.getValueType();
4131 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4134 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4135 switch (SetCCOpcode) {
4136 default: llvm_unreachable("Illegal FP comparison");
4138 case ISD::SETNE: Invert = true; // Fallthrough
4140 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4142 case ISD::SETLT: Swap = true; // Fallthrough
4144 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4146 case ISD::SETLE: Swap = true; // Fallthrough
4148 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4149 case ISD::SETUGE: Swap = true; // Fallthrough
4150 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4151 case ISD::SETUGT: Swap = true; // Fallthrough
4152 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4153 case ISD::SETUEQ: Invert = true; // Fallthrough
4155 // Expand this to (OLT | OGT).
4159 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4160 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4162 case ISD::SETUO: Invert = true; // Fallthrough
4164 // Expand this to (OLT | OGE).
4168 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4169 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4173 // Integer comparisons.
4174 switch (SetCCOpcode) {
4175 default: llvm_unreachable("Illegal integer comparison");
4176 case ISD::SETNE: Invert = true;
4177 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4178 case ISD::SETLT: Swap = true;
4179 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4180 case ISD::SETLE: Swap = true;
4181 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4182 case ISD::SETULT: Swap = true;
4183 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4184 case ISD::SETULE: Swap = true;
4185 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4188 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4189 if (Opc == ARMISD::VCEQ) {
4192 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4194 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4197 // Ignore bitconvert.
4198 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4199 AndOp = AndOp.getOperand(0);
4201 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4203 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4204 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4211 std::swap(Op0, Op1);
4213 // If one of the operands is a constant vector zero, attempt to fold the
4214 // comparison to a specialized compare-against-zero form.
4216 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4218 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4219 if (Opc == ARMISD::VCGE)
4220 Opc = ARMISD::VCLEZ;
4221 else if (Opc == ARMISD::VCGT)
4222 Opc = ARMISD::VCLTZ;
4227 if (SingleOp.getNode()) {
4230 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4232 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4234 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4236 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4238 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4240 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4243 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4247 Result = DAG.getNOT(dl, Result, VT);
4252 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4253 /// valid vector constant for a NEON instruction with a "modified immediate"
4254 /// operand (e.g., VMOV). If so, return the encoded value.
4255 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4256 unsigned SplatBitSize, SelectionDAG &DAG,
4257 EVT &VT, bool is128Bits, NEONModImmType type) {
4258 unsigned OpCmode, Imm;
4260 // SplatBitSize is set to the smallest size that splats the vector, so a
4261 // zero vector will always have SplatBitSize == 8. However, NEON modified
4262 // immediate instructions others than VMOV do not support the 8-bit encoding
4263 // of a zero vector, and the default encoding of zero is supposed to be the
4268 switch (SplatBitSize) {
4270 if (type != VMOVModImm)
4272 // Any 1-byte value is OK. Op=0, Cmode=1110.
4273 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4276 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4280 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4281 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4282 if ((SplatBits & ~0xff) == 0) {
4283 // Value = 0x00nn: Op=x, Cmode=100x.
4288 if ((SplatBits & ~0xff00) == 0) {
4289 // Value = 0xnn00: Op=x, Cmode=101x.
4291 Imm = SplatBits >> 8;
4297 // NEON's 32-bit VMOV supports splat values where:
4298 // * only one byte is nonzero, or
4299 // * the least significant byte is 0xff and the second byte is nonzero, or
4300 // * the least significant 2 bytes are 0xff and the third is nonzero.
4301 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4302 if ((SplatBits & ~0xff) == 0) {
4303 // Value = 0x000000nn: Op=x, Cmode=000x.
4308 if ((SplatBits & ~0xff00) == 0) {
4309 // Value = 0x0000nn00: Op=x, Cmode=001x.
4311 Imm = SplatBits >> 8;
4314 if ((SplatBits & ~0xff0000) == 0) {
4315 // Value = 0x00nn0000: Op=x, Cmode=010x.
4317 Imm = SplatBits >> 16;
4320 if ((SplatBits & ~0xff000000) == 0) {
4321 // Value = 0xnn000000: Op=x, Cmode=011x.
4323 Imm = SplatBits >> 24;
4327 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4328 if (type == OtherModImm) return SDValue();
4330 if ((SplatBits & ~0xffff) == 0 &&
4331 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4332 // Value = 0x0000nnff: Op=x, Cmode=1100.
4334 Imm = SplatBits >> 8;
4338 if ((SplatBits & ~0xffffff) == 0 &&
4339 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4340 // Value = 0x00nnffff: Op=x, Cmode=1101.
4342 Imm = SplatBits >> 16;
4346 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4347 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4348 // VMOV.I32. A (very) minor optimization would be to replicate the value
4349 // and fall through here to test for a valid 64-bit splat. But, then the
4350 // caller would also need to check and handle the change in size.
4354 if (type != VMOVModImm)
4356 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4357 uint64_t BitMask = 0xff;
4359 unsigned ImmMask = 1;
4361 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4362 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4365 } else if ((SplatBits & BitMask) != 0) {
4371 // Op=1, Cmode=1110.
4373 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4378 llvm_unreachable("unexpected size for isNEONModifiedImm");
4381 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4382 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4385 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4386 const ARMSubtarget *ST) const {
4390 bool IsDouble = Op.getValueType() == MVT::f64;
4391 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4393 // Try splatting with a VMOV.f32...
4394 APFloat FPVal = CFP->getValueAPF();
4395 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4398 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4399 // We have code in place to select a valid ConstantFP already, no need to
4404 // It's a float and we are trying to use NEON operations where
4405 // possible. Lower it to a splat followed by an extract.
4407 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4408 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4410 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4411 DAG.getConstant(0, MVT::i32));
4414 // The rest of our options are NEON only, make sure that's allowed before
4416 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4420 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4422 // It wouldn't really be worth bothering for doubles except for one very
4423 // important value, which does happen to match: 0.0. So make sure we don't do
4425 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4428 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4429 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4431 if (NewVal != SDValue()) {
4433 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4436 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4438 // It's a float: cast and extract a vector element.
4439 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4441 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4442 DAG.getConstant(0, MVT::i32));
4445 // Finally, try a VMVN.i32
4446 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4448 if (NewVal != SDValue()) {
4450 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4453 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4455 // It's a float: cast and extract a vector element.
4456 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4458 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4459 DAG.getConstant(0, MVT::i32));
4465 // check if an VEXT instruction can handle the shuffle mask when the
4466 // vector sources of the shuffle are the same.
4467 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4468 unsigned NumElts = VT.getVectorNumElements();
4470 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4476 // If this is a VEXT shuffle, the immediate value is the index of the first
4477 // element. The other shuffle indices must be the successive elements after
4479 unsigned ExpectedElt = Imm;
4480 for (unsigned i = 1; i < NumElts; ++i) {
4481 // Increment the expected index. If it wraps around, just follow it
4482 // back to index zero and keep going.
4484 if (ExpectedElt == NumElts)
4487 if (M[i] < 0) continue; // ignore UNDEF indices
4488 if (ExpectedElt != static_cast<unsigned>(M[i]))
4496 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4497 bool &ReverseVEXT, unsigned &Imm) {
4498 unsigned NumElts = VT.getVectorNumElements();
4499 ReverseVEXT = false;
4501 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4507 // If this is a VEXT shuffle, the immediate value is the index of the first
4508 // element. The other shuffle indices must be the successive elements after
4510 unsigned ExpectedElt = Imm;
4511 for (unsigned i = 1; i < NumElts; ++i) {
4512 // Increment the expected index. If it wraps around, it may still be
4513 // a VEXT but the source vectors must be swapped.
4515 if (ExpectedElt == NumElts * 2) {
4520 if (M[i] < 0) continue; // ignore UNDEF indices
4521 if (ExpectedElt != static_cast<unsigned>(M[i]))
4525 // Adjust the index value if the source operands will be swapped.
4532 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4533 /// instruction with the specified blocksize. (The order of the elements
4534 /// within each block of the vector is reversed.)
4535 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4536 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4537 "Only possible block sizes for VREV are: 16, 32, 64");
4539 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4543 unsigned NumElts = VT.getVectorNumElements();
4544 unsigned BlockElts = M[0] + 1;
4545 // If the first shuffle index is UNDEF, be optimistic.
4547 BlockElts = BlockSize / EltSz;
4549 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4552 for (unsigned i = 0; i < NumElts; ++i) {
4553 if (M[i] < 0) continue; // ignore UNDEF indices
4554 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4561 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4562 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4563 // range, then 0 is placed into the resulting vector. So pretty much any mask
4564 // of 8 elements can work here.
4565 return VT == MVT::v8i8 && M.size() == 8;
4568 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4569 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4573 unsigned NumElts = VT.getVectorNumElements();
4574 WhichResult = (M[0] == 0 ? 0 : 1);
4575 for (unsigned i = 0; i < NumElts; i += 2) {
4576 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4577 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4583 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4584 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4585 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4586 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4587 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4591 unsigned NumElts = VT.getVectorNumElements();
4592 WhichResult = (M[0] == 0 ? 0 : 1);
4593 for (unsigned i = 0; i < NumElts; i += 2) {
4594 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4595 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4601 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4602 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4606 unsigned NumElts = VT.getVectorNumElements();
4607 WhichResult = (M[0] == 0 ? 0 : 1);
4608 for (unsigned i = 0; i != NumElts; ++i) {
4609 if (M[i] < 0) continue; // ignore UNDEF indices
4610 if ((unsigned) M[i] != 2 * i + WhichResult)
4614 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4615 if (VT.is64BitVector() && EltSz == 32)
4621 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4622 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4623 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4624 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4625 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4629 unsigned Half = VT.getVectorNumElements() / 2;
4630 WhichResult = (M[0] == 0 ? 0 : 1);
4631 for (unsigned j = 0; j != 2; ++j) {
4632 unsigned Idx = WhichResult;
4633 for (unsigned i = 0; i != Half; ++i) {
4634 int MIdx = M[i + j * Half];
4635 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4641 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4642 if (VT.is64BitVector() && EltSz == 32)
4648 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4649 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4653 unsigned NumElts = VT.getVectorNumElements();
4654 WhichResult = (M[0] == 0 ? 0 : 1);
4655 unsigned Idx = WhichResult * NumElts / 2;
4656 for (unsigned i = 0; i != NumElts; i += 2) {
4657 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4658 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4663 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4664 if (VT.is64BitVector() && EltSz == 32)
4670 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4671 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4672 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4673 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4674 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4678 unsigned NumElts = VT.getVectorNumElements();
4679 WhichResult = (M[0] == 0 ? 0 : 1);
4680 unsigned Idx = WhichResult * NumElts / 2;
4681 for (unsigned i = 0; i != NumElts; i += 2) {
4682 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4683 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4688 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4689 if (VT.is64BitVector() && EltSz == 32)
4695 /// \return true if this is a reverse operation on an vector.
4696 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4697 unsigned NumElts = VT.getVectorNumElements();
4698 // Make sure the mask has the right size.
4699 if (NumElts != M.size())
4702 // Look for <15, ..., 3, -1, 1, 0>.
4703 for (unsigned i = 0; i != NumElts; ++i)
4704 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4710 // If N is an integer constant that can be moved into a register in one
4711 // instruction, return an SDValue of such a constant (will become a MOV
4712 // instruction). Otherwise return null.
4713 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4714 const ARMSubtarget *ST, SDLoc dl) {
4716 if (!isa<ConstantSDNode>(N))
4718 Val = cast<ConstantSDNode>(N)->getZExtValue();
4720 if (ST->isThumb1Only()) {
4721 if (Val <= 255 || ~Val <= 255)
4722 return DAG.getConstant(Val, MVT::i32);
4724 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4725 return DAG.getConstant(Val, MVT::i32);
4730 // If this is a case we can't handle, return null and let the default
4731 // expansion code take care of it.
4732 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4733 const ARMSubtarget *ST) const {
4734 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4736 EVT VT = Op.getValueType();
4738 APInt SplatBits, SplatUndef;
4739 unsigned SplatBitSize;
4741 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4742 if (SplatBitSize <= 64) {
4743 // Check if an immediate VMOV works.
4745 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4746 SplatUndef.getZExtValue(), SplatBitSize,
4747 DAG, VmovVT, VT.is128BitVector(),
4749 if (Val.getNode()) {
4750 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4751 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4754 // Try an immediate VMVN.
4755 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4756 Val = isNEONModifiedImm(NegatedImm,
4757 SplatUndef.getZExtValue(), SplatBitSize,
4758 DAG, VmovVT, VT.is128BitVector(),
4760 if (Val.getNode()) {
4761 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4762 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4765 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4766 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4767 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4769 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4770 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4776 // Scan through the operands to see if only one value is used.
4778 // As an optimisation, even if more than one value is used it may be more
4779 // profitable to splat with one value then change some lanes.
4781 // Heuristically we decide to do this if the vector has a "dominant" value,
4782 // defined as splatted to more than half of the lanes.
4783 unsigned NumElts = VT.getVectorNumElements();
4784 bool isOnlyLowElement = true;
4785 bool usesOnlyOneValue = true;
4786 bool hasDominantValue = false;
4787 bool isConstant = true;
4789 // Map of the number of times a particular SDValue appears in the
4791 DenseMap<SDValue, unsigned> ValueCounts;
4793 for (unsigned i = 0; i < NumElts; ++i) {
4794 SDValue V = Op.getOperand(i);
4795 if (V.getOpcode() == ISD::UNDEF)
4798 isOnlyLowElement = false;
4799 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4802 ValueCounts.insert(std::make_pair(V, 0));
4803 unsigned &Count = ValueCounts[V];
4805 // Is this value dominant? (takes up more than half of the lanes)
4806 if (++Count > (NumElts / 2)) {
4807 hasDominantValue = true;
4811 if (ValueCounts.size() != 1)
4812 usesOnlyOneValue = false;
4813 if (!Value.getNode() && ValueCounts.size() > 0)
4814 Value = ValueCounts.begin()->first;
4816 if (ValueCounts.size() == 0)
4817 return DAG.getUNDEF(VT);
4819 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4820 // Keep going if we are hitting this case.
4821 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4822 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4824 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4826 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4827 // i32 and try again.
4828 if (hasDominantValue && EltSize <= 32) {
4832 // If we are VDUPing a value that comes directly from a vector, that will
4833 // cause an unnecessary move to and from a GPR, where instead we could
4834 // just use VDUPLANE. We can only do this if the lane being extracted
4835 // is at a constant index, as the VDUP from lane instructions only have
4836 // constant-index forms.
4837 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4838 isa<ConstantSDNode>(Value->getOperand(1))) {
4839 // We need to create a new undef vector to use for the VDUPLANE if the
4840 // size of the vector from which we get the value is different than the
4841 // size of the vector that we need to create. We will insert the element
4842 // such that the register coalescer will remove unnecessary copies.
4843 if (VT != Value->getOperand(0).getValueType()) {
4844 ConstantSDNode *constIndex;
4845 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4846 assert(constIndex && "The index is not a constant!");
4847 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4848 VT.getVectorNumElements();
4849 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4850 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4851 Value, DAG.getConstant(index, MVT::i32)),
4852 DAG.getConstant(index, MVT::i32));
4854 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4855 Value->getOperand(0), Value->getOperand(1));
4857 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4859 if (!usesOnlyOneValue) {
4860 // The dominant value was splatted as 'N', but we now have to insert
4861 // all differing elements.
4862 for (unsigned I = 0; I < NumElts; ++I) {
4863 if (Op.getOperand(I) == Value)
4865 SmallVector<SDValue, 3> Ops;
4867 Ops.push_back(Op.getOperand(I));
4868 Ops.push_back(DAG.getConstant(I, MVT::i32));
4869 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4874 if (VT.getVectorElementType().isFloatingPoint()) {
4875 SmallVector<SDValue, 8> Ops;
4876 for (unsigned i = 0; i < NumElts; ++i)
4877 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4879 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4880 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
4881 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4883 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4885 if (usesOnlyOneValue) {
4886 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4887 if (isConstant && Val.getNode())
4888 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4892 // If all elements are constants and the case above didn't get hit, fall back
4893 // to the default expansion, which will generate a load from the constant
4898 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4900 SDValue shuffle = ReconstructShuffle(Op, DAG);
4901 if (shuffle != SDValue())
4905 // Vectors with 32- or 64-bit elements can be built by directly assigning
4906 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4907 // will be legalized.
4908 if (EltSize >= 32) {
4909 // Do the expansion with floating-point types, since that is what the VFP
4910 // registers are defined to use, and since i64 is not legal.
4911 EVT EltVT = EVT::getFloatingPointVT(EltSize);
4912 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4913 SmallVector<SDValue, 8> Ops;
4914 for (unsigned i = 0; i < NumElts; ++i)
4915 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4916 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
4917 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4920 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4921 // know the default expansion would otherwise fall back on something even
4922 // worse. For a vector with one or two non-undef values, that's
4923 // scalar_to_vector for the elements followed by a shuffle (provided the
4924 // shuffle is valid for the target) and materialization element by element
4925 // on the stack followed by a load for everything else.
4926 if (!isConstant && !usesOnlyOneValue) {
4927 SDValue Vec = DAG.getUNDEF(VT);
4928 for (unsigned i = 0 ; i < NumElts; ++i) {
4929 SDValue V = Op.getOperand(i);
4930 if (V.getOpcode() == ISD::UNDEF)
4932 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4933 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4941 // Gather data to see if the operation can be modelled as a
4942 // shuffle in combination with VEXTs.
4943 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4944 SelectionDAG &DAG) const {
4946 EVT VT = Op.getValueType();
4947 unsigned NumElts = VT.getVectorNumElements();
4949 SmallVector<SDValue, 2> SourceVecs;
4950 SmallVector<unsigned, 2> MinElts;
4951 SmallVector<unsigned, 2> MaxElts;
4953 for (unsigned i = 0; i < NumElts; ++i) {
4954 SDValue V = Op.getOperand(i);
4955 if (V.getOpcode() == ISD::UNDEF)
4957 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4958 // A shuffle can only come from building a vector from various
4959 // elements of other vectors.
4961 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4962 VT.getVectorElementType()) {
4963 // This code doesn't know how to handle shuffles where the vector
4964 // element types do not match (this happens because type legalization
4965 // promotes the return type of EXTRACT_VECTOR_ELT).
4966 // FIXME: It might be appropriate to extend this code to handle
4967 // mismatched types.
4971 // Record this extraction against the appropriate vector if possible...
4972 SDValue SourceVec = V.getOperand(0);
4973 // If the element number isn't a constant, we can't effectively
4974 // analyze what's going on.
4975 if (!isa<ConstantSDNode>(V.getOperand(1)))
4977 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4978 bool FoundSource = false;
4979 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4980 if (SourceVecs[j] == SourceVec) {
4981 if (MinElts[j] > EltNo)
4983 if (MaxElts[j] < EltNo)
4990 // Or record a new source if not...
4992 SourceVecs.push_back(SourceVec);
4993 MinElts.push_back(EltNo);
4994 MaxElts.push_back(EltNo);
4998 // Currently only do something sane when at most two source vectors
5000 if (SourceVecs.size() > 2)
5003 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5004 int VEXTOffsets[2] = {0, 0};
5006 // This loop extracts the usage patterns of the source vectors
5007 // and prepares appropriate SDValues for a shuffle if possible.
5008 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5009 if (SourceVecs[i].getValueType() == VT) {
5010 // No VEXT necessary
5011 ShuffleSrcs[i] = SourceVecs[i];
5014 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5015 // It probably isn't worth padding out a smaller vector just to
5016 // break it down again in a shuffle.
5020 // Since only 64-bit and 128-bit vectors are legal on ARM and
5021 // we've eliminated the other cases...
5022 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5023 "unexpected vector sizes in ReconstructShuffle");
5025 if (MaxElts[i] - MinElts[i] >= NumElts) {
5026 // Span too large for a VEXT to cope
5030 if (MinElts[i] >= NumElts) {
5031 // The extraction can just take the second half
5032 VEXTOffsets[i] = NumElts;
5033 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5035 DAG.getIntPtrConstant(NumElts));
5036 } else if (MaxElts[i] < NumElts) {
5037 // The extraction can just take the first half
5039 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5041 DAG.getIntPtrConstant(0));
5043 // An actual VEXT is needed
5044 VEXTOffsets[i] = MinElts[i];
5045 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5047 DAG.getIntPtrConstant(0));
5048 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5050 DAG.getIntPtrConstant(NumElts));
5051 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5052 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5056 SmallVector<int, 8> Mask;
5058 for (unsigned i = 0; i < NumElts; ++i) {
5059 SDValue Entry = Op.getOperand(i);
5060 if (Entry.getOpcode() == ISD::UNDEF) {
5065 SDValue ExtractVec = Entry.getOperand(0);
5066 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5067 .getOperand(1))->getSExtValue();
5068 if (ExtractVec == SourceVecs[0]) {
5069 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5071 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5075 // Final check before we try to produce nonsense...
5076 if (isShuffleMaskLegal(Mask, VT))
5077 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5083 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5084 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5085 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5086 /// are assumed to be legal.
5088 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5090 if (VT.getVectorNumElements() == 4 &&
5091 (VT.is128BitVector() || VT.is64BitVector())) {
5092 unsigned PFIndexes[4];
5093 for (unsigned i = 0; i != 4; ++i) {
5097 PFIndexes[i] = M[i];
5100 // Compute the index in the perfect shuffle table.
5101 unsigned PFTableIndex =
5102 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5103 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5104 unsigned Cost = (PFEntry >> 30);
5111 unsigned Imm, WhichResult;
5113 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5114 return (EltSize >= 32 ||
5115 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5116 isVREVMask(M, VT, 64) ||
5117 isVREVMask(M, VT, 32) ||
5118 isVREVMask(M, VT, 16) ||
5119 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5120 isVTBLMask(M, VT) ||
5121 isVTRNMask(M, VT, WhichResult) ||
5122 isVUZPMask(M, VT, WhichResult) ||
5123 isVZIPMask(M, VT, WhichResult) ||
5124 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5125 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5126 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5127 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5130 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5131 /// the specified operations to build the shuffle.
5132 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5133 SDValue RHS, SelectionDAG &DAG,
5135 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5136 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5137 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5140 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5149 OP_VUZPL, // VUZP, left result
5150 OP_VUZPR, // VUZP, right result
5151 OP_VZIPL, // VZIP, left result
5152 OP_VZIPR, // VZIP, right result
5153 OP_VTRNL, // VTRN, left result
5154 OP_VTRNR // VTRN, right result
5157 if (OpNum == OP_COPY) {
5158 if (LHSID == (1*9+2)*9+3) return LHS;
5159 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5163 SDValue OpLHS, OpRHS;
5164 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5165 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5166 EVT VT = OpLHS.getValueType();
5169 default: llvm_unreachable("Unknown shuffle opcode!");
5171 // VREV divides the vector in half and swaps within the half.
5172 if (VT.getVectorElementType() == MVT::i32 ||
5173 VT.getVectorElementType() == MVT::f32)
5174 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5175 // vrev <4 x i16> -> VREV32
5176 if (VT.getVectorElementType() == MVT::i16)
5177 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5178 // vrev <4 x i8> -> VREV16
5179 assert(VT.getVectorElementType() == MVT::i8);
5180 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5185 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5186 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5190 return DAG.getNode(ARMISD::VEXT, dl, VT,
5192 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5195 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5196 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5199 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5200 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5203 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5204 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5208 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5209 ArrayRef<int> ShuffleMask,
5210 SelectionDAG &DAG) {
5211 // Check to see if we can use the VTBL instruction.
5212 SDValue V1 = Op.getOperand(0);
5213 SDValue V2 = Op.getOperand(1);
5216 SmallVector<SDValue, 8> VTBLMask;
5217 for (ArrayRef<int>::iterator
5218 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5219 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5221 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5222 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5223 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5225 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5226 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5229 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5230 SelectionDAG &DAG) {
5232 SDValue OpLHS = Op.getOperand(0);
5233 EVT VT = OpLHS.getValueType();
5235 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5236 "Expect an v8i16/v16i8 type");
5237 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5238 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5239 // extract the first 8 bytes into the top double word and the last 8 bytes
5240 // into the bottom double word. The v8i16 case is similar.
5241 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5242 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5243 DAG.getConstant(ExtractNum, MVT::i32));
5246 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5247 SDValue V1 = Op.getOperand(0);
5248 SDValue V2 = Op.getOperand(1);
5250 EVT VT = Op.getValueType();
5251 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5253 // Convert shuffles that are directly supported on NEON to target-specific
5254 // DAG nodes, instead of keeping them as shuffles and matching them again
5255 // during code selection. This is more efficient and avoids the possibility
5256 // of inconsistencies between legalization and selection.
5257 // FIXME: floating-point vectors should be canonicalized to integer vectors
5258 // of the same time so that they get CSEd properly.
5259 ArrayRef<int> ShuffleMask = SVN->getMask();
5261 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5262 if (EltSize <= 32) {
5263 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5264 int Lane = SVN->getSplatIndex();
5265 // If this is undef splat, generate it via "just" vdup, if possible.
5266 if (Lane == -1) Lane = 0;
5268 // Test if V1 is a SCALAR_TO_VECTOR.
5269 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5270 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5272 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5273 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5275 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5276 !isa<ConstantSDNode>(V1.getOperand(0))) {
5277 bool IsScalarToVector = true;
5278 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5279 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5280 IsScalarToVector = false;
5283 if (IsScalarToVector)
5284 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5286 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5287 DAG.getConstant(Lane, MVT::i32));
5292 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5295 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5296 DAG.getConstant(Imm, MVT::i32));
5299 if (isVREVMask(ShuffleMask, VT, 64))
5300 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5301 if (isVREVMask(ShuffleMask, VT, 32))
5302 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5303 if (isVREVMask(ShuffleMask, VT, 16))
5304 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5306 if (V2->getOpcode() == ISD::UNDEF &&
5307 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5308 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5309 DAG.getConstant(Imm, MVT::i32));
5312 // Check for Neon shuffles that modify both input vectors in place.
5313 // If both results are used, i.e., if there are two shuffles with the same
5314 // source operands and with masks corresponding to both results of one of
5315 // these operations, DAG memoization will ensure that a single node is
5316 // used for both shuffles.
5317 unsigned WhichResult;
5318 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5319 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5320 V1, V2).getValue(WhichResult);
5321 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5322 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5323 V1, V2).getValue(WhichResult);
5324 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5325 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5326 V1, V2).getValue(WhichResult);
5328 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5329 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5330 V1, V1).getValue(WhichResult);
5331 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5332 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5333 V1, V1).getValue(WhichResult);
5334 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5335 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5336 V1, V1).getValue(WhichResult);
5339 // If the shuffle is not directly supported and it has 4 elements, use
5340 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5341 unsigned NumElts = VT.getVectorNumElements();
5343 unsigned PFIndexes[4];
5344 for (unsigned i = 0; i != 4; ++i) {
5345 if (ShuffleMask[i] < 0)
5348 PFIndexes[i] = ShuffleMask[i];
5351 // Compute the index in the perfect shuffle table.
5352 unsigned PFTableIndex =
5353 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5354 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5355 unsigned Cost = (PFEntry >> 30);
5358 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5361 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5362 if (EltSize >= 32) {
5363 // Do the expansion with floating-point types, since that is what the VFP
5364 // registers are defined to use, and since i64 is not legal.
5365 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5366 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5367 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5368 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5369 SmallVector<SDValue, 8> Ops;
5370 for (unsigned i = 0; i < NumElts; ++i) {
5371 if (ShuffleMask[i] < 0)
5372 Ops.push_back(DAG.getUNDEF(EltVT));
5374 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5375 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5376 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5379 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5380 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5383 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5384 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5386 if (VT == MVT::v8i8) {
5387 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5388 if (NewOp.getNode())
5395 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5396 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5397 SDValue Lane = Op.getOperand(2);
5398 if (!isa<ConstantSDNode>(Lane))
5404 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5405 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5406 SDValue Lane = Op.getOperand(1);
5407 if (!isa<ConstantSDNode>(Lane))
5410 SDValue Vec = Op.getOperand(0);
5411 if (Op.getValueType() == MVT::i32 &&
5412 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5414 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5420 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5421 // The only time a CONCAT_VECTORS operation can have legal types is when
5422 // two 64-bit vectors are concatenated to a 128-bit vector.
5423 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5424 "unexpected CONCAT_VECTORS");
5426 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5427 SDValue Op0 = Op.getOperand(0);
5428 SDValue Op1 = Op.getOperand(1);
5429 if (Op0.getOpcode() != ISD::UNDEF)
5430 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5431 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5432 DAG.getIntPtrConstant(0));
5433 if (Op1.getOpcode() != ISD::UNDEF)
5434 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5435 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5436 DAG.getIntPtrConstant(1));
5437 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5440 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5441 /// element has been zero/sign-extended, depending on the isSigned parameter,
5442 /// from an integer type half its size.
5443 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5445 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5446 EVT VT = N->getValueType(0);
5447 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5448 SDNode *BVN = N->getOperand(0).getNode();
5449 if (BVN->getValueType(0) != MVT::v4i32 ||
5450 BVN->getOpcode() != ISD::BUILD_VECTOR)
5452 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5453 unsigned HiElt = 1 - LoElt;
5454 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5455 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5456 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5457 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5458 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5461 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5462 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5465 if (Hi0->isNullValue() && Hi1->isNullValue())
5471 if (N->getOpcode() != ISD::BUILD_VECTOR)
5474 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5475 SDNode *Elt = N->getOperand(i).getNode();
5476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5477 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5478 unsigned HalfSize = EltSize / 2;
5480 if (!isIntN(HalfSize, C->getSExtValue()))
5483 if (!isUIntN(HalfSize, C->getZExtValue()))
5494 /// isSignExtended - Check if a node is a vector value that is sign-extended
5495 /// or a constant BUILD_VECTOR with sign-extended elements.
5496 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5497 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5499 if (isExtendedBUILD_VECTOR(N, DAG, true))
5504 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5505 /// or a constant BUILD_VECTOR with zero-extended elements.
5506 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5507 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5509 if (isExtendedBUILD_VECTOR(N, DAG, false))
5514 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5515 if (OrigVT.getSizeInBits() >= 64)
5518 assert(OrigVT.isSimple() && "Expecting a simple value type");
5520 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5521 switch (OrigSimpleTy) {
5522 default: llvm_unreachable("Unexpected Vector Type");
5531 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5532 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5533 /// We insert the required extension here to get the vector to fill a D register.
5534 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5537 unsigned ExtOpcode) {
5538 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5539 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5540 // 64-bits we need to insert a new extension so that it will be 64-bits.
5541 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5542 if (OrigTy.getSizeInBits() >= 64)
5545 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5546 EVT NewVT = getExtensionTo64Bits(OrigTy);
5548 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5551 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5552 /// does not do any sign/zero extension. If the original vector is less
5553 /// than 64 bits, an appropriate extension will be added after the load to
5554 /// reach a total size of 64 bits. We have to add the extension separately
5555 /// because ARM does not have a sign/zero extending load for vectors.
5556 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5557 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5559 // The load already has the right type.
5560 if (ExtendedTy == LD->getMemoryVT())
5561 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5562 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5563 LD->isNonTemporal(), LD->isInvariant(),
5564 LD->getAlignment());
5566 // We need to create a zextload/sextload. We cannot just create a load
5567 // followed by a zext/zext node because LowerMUL is also run during normal
5568 // operation legalization where we can't create illegal types.
5569 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5570 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5571 LD->getMemoryVT(), LD->isVolatile(),
5572 LD->isNonTemporal(), LD->getAlignment());
5575 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5576 /// extending load, or BUILD_VECTOR with extended elements, return the
5577 /// unextended value. The unextended vector should be 64 bits so that it can
5578 /// be used as an operand to a VMULL instruction. If the original vector size
5579 /// before extension is less than 64 bits we add a an extension to resize
5580 /// the vector to 64 bits.
5581 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5582 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5583 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5584 N->getOperand(0)->getValueType(0),
5588 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5589 return SkipLoadExtensionForVMULL(LD, DAG);
5591 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5592 // have been legalized as a BITCAST from v4i32.
5593 if (N->getOpcode() == ISD::BITCAST) {
5594 SDNode *BVN = N->getOperand(0).getNode();
5595 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5596 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5597 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5598 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5599 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5601 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5602 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5603 EVT VT = N->getValueType(0);
5604 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5605 unsigned NumElts = VT.getVectorNumElements();
5606 MVT TruncVT = MVT::getIntegerVT(EltSize);
5607 SmallVector<SDValue, 8> Ops;
5608 for (unsigned i = 0; i != NumElts; ++i) {
5609 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5610 const APInt &CInt = C->getAPIntValue();
5611 // Element types smaller than 32 bits are not legal, so use i32 elements.
5612 // The values are implicitly truncated so sext vs. zext doesn't matter.
5613 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5615 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5616 MVT::getVectorVT(TruncVT, NumElts), Ops);
5619 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5620 unsigned Opcode = N->getOpcode();
5621 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5622 SDNode *N0 = N->getOperand(0).getNode();
5623 SDNode *N1 = N->getOperand(1).getNode();
5624 return N0->hasOneUse() && N1->hasOneUse() &&
5625 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5630 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5631 unsigned Opcode = N->getOpcode();
5632 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5633 SDNode *N0 = N->getOperand(0).getNode();
5634 SDNode *N1 = N->getOperand(1).getNode();
5635 return N0->hasOneUse() && N1->hasOneUse() &&
5636 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5641 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5642 // Multiplications are only custom-lowered for 128-bit vectors so that
5643 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5644 EVT VT = Op.getValueType();
5645 assert(VT.is128BitVector() && VT.isInteger() &&
5646 "unexpected type for custom-lowering ISD::MUL");
5647 SDNode *N0 = Op.getOperand(0).getNode();
5648 SDNode *N1 = Op.getOperand(1).getNode();
5649 unsigned NewOpc = 0;
5651 bool isN0SExt = isSignExtended(N0, DAG);
5652 bool isN1SExt = isSignExtended(N1, DAG);
5653 if (isN0SExt && isN1SExt)
5654 NewOpc = ARMISD::VMULLs;
5656 bool isN0ZExt = isZeroExtended(N0, DAG);
5657 bool isN1ZExt = isZeroExtended(N1, DAG);
5658 if (isN0ZExt && isN1ZExt)
5659 NewOpc = ARMISD::VMULLu;
5660 else if (isN1SExt || isN1ZExt) {
5661 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5662 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5663 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5664 NewOpc = ARMISD::VMULLs;
5666 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5667 NewOpc = ARMISD::VMULLu;
5669 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5671 NewOpc = ARMISD::VMULLu;
5677 if (VT == MVT::v2i64)
5678 // Fall through to expand this. It is not legal.
5681 // Other vector multiplications are legal.
5686 // Legalize to a VMULL instruction.
5689 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5691 Op0 = SkipExtensionForVMULL(N0, DAG);
5692 assert(Op0.getValueType().is64BitVector() &&
5693 Op1.getValueType().is64BitVector() &&
5694 "unexpected types for extended operands to VMULL");
5695 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5698 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5699 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5706 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5707 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5708 EVT Op1VT = Op1.getValueType();
5709 return DAG.getNode(N0->getOpcode(), DL, VT,
5710 DAG.getNode(NewOpc, DL, VT,
5711 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5712 DAG.getNode(NewOpc, DL, VT,
5713 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5717 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5719 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5720 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5721 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5722 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5723 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5724 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5725 // Get reciprocal estimate.
5726 // float4 recip = vrecpeq_f32(yf);
5727 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5728 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5729 // Because char has a smaller range than uchar, we can actually get away
5730 // without any newton steps. This requires that we use a weird bias
5731 // of 0xb000, however (again, this has been exhaustively tested).
5732 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5733 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5734 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5735 Y = DAG.getConstant(0xb000, MVT::i32);
5736 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5737 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5738 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5739 // Convert back to short.
5740 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5741 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5746 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5748 // Convert to float.
5749 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5750 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5751 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5752 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5753 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5754 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5756 // Use reciprocal estimate and one refinement step.
5757 // float4 recip = vrecpeq_f32(yf);
5758 // recip *= vrecpsq_f32(yf, recip);
5759 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5760 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5761 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5762 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5764 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5765 // Because short has a smaller range than ushort, we can actually get away
5766 // with only a single newton step. This requires that we use a weird bias
5767 // of 89, however (again, this has been exhaustively tested).
5768 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5769 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5770 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5771 N1 = DAG.getConstant(0x89, MVT::i32);
5772 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5773 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5774 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5775 // Convert back to integer and return.
5776 // return vmovn_s32(vcvt_s32_f32(result));
5777 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5778 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5782 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5783 EVT VT = Op.getValueType();
5784 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5785 "unexpected type for custom-lowering ISD::SDIV");
5788 SDValue N0 = Op.getOperand(0);
5789 SDValue N1 = Op.getOperand(1);
5792 if (VT == MVT::v8i8) {
5793 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5794 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5796 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5797 DAG.getIntPtrConstant(4));
5798 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5799 DAG.getIntPtrConstant(4));
5800 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5801 DAG.getIntPtrConstant(0));
5802 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5803 DAG.getIntPtrConstant(0));
5805 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5806 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5808 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5809 N0 = LowerCONCAT_VECTORS(N0, DAG);
5811 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5814 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5817 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5818 EVT VT = Op.getValueType();
5819 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5820 "unexpected type for custom-lowering ISD::UDIV");
5823 SDValue N0 = Op.getOperand(0);
5824 SDValue N1 = Op.getOperand(1);
5827 if (VT == MVT::v8i8) {
5828 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5829 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5831 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5832 DAG.getIntPtrConstant(4));
5833 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5834 DAG.getIntPtrConstant(4));
5835 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5836 DAG.getIntPtrConstant(0));
5837 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5838 DAG.getIntPtrConstant(0));
5840 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5841 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5843 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5844 N0 = LowerCONCAT_VECTORS(N0, DAG);
5846 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5847 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5852 // v4i16 sdiv ... Convert to float.
5853 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5854 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5855 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5856 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5857 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5858 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5860 // Use reciprocal estimate and two refinement steps.
5861 // float4 recip = vrecpeq_f32(yf);
5862 // recip *= vrecpsq_f32(yf, recip);
5863 // recip *= vrecpsq_f32(yf, recip);
5864 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5865 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5866 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5867 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5869 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5870 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5871 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5873 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5874 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5875 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5876 // and that it will never cause us to return an answer too large).
5877 // float4 result = as_float4(as_int4(xf*recip) + 2);
5878 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5879 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5880 N1 = DAG.getConstant(2, MVT::i32);
5881 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5882 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5883 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5884 // Convert back to integer and return.
5885 // return vmovn_u32(vcvt_s32_f32(result));
5886 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5887 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5891 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5892 EVT VT = Op.getNode()->getValueType(0);
5893 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5896 bool ExtraOp = false;
5897 switch (Op.getOpcode()) {
5898 default: llvm_unreachable("Invalid code");
5899 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5900 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5901 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5902 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5906 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5908 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5909 Op.getOperand(1), Op.getOperand(2));
5912 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5913 assert(Subtarget->isTargetDarwin());
5915 // For iOS, we want to call an alternative entry point: __sincos_stret,
5916 // return values are passed via sret.
5918 SDValue Arg = Op.getOperand(0);
5919 EVT ArgVT = Arg.getValueType();
5920 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5922 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5925 // Pair of floats / doubles used to pass the result.
5926 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5928 // Create stack object for sret.
5929 const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5930 const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5931 int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5932 SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5938 Entry.Ty = RetTy->getPointerTo();
5939 Entry.isSExt = false;
5940 Entry.isZExt = false;
5941 Entry.isSRet = true;
5942 Args.push_back(Entry);
5946 Entry.isSExt = false;
5947 Entry.isZExt = false;
5948 Args.push_back(Entry);
5950 const char *LibcallName = (ArgVT == MVT::f64)
5951 ? "__sincos_stret" : "__sincosf_stret";
5952 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5955 CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5956 false, false, false, false, 0,
5957 CallingConv::C, /*isTaillCall=*/false,
5958 /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5959 Callee, Args, DAG, dl);
5960 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5962 SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5963 MachinePointerInfo(), false, false, false, 0);
5965 // Address of cos field.
5966 SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5967 DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5968 SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5969 MachinePointerInfo(), false, false, false, 0);
5971 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5972 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5973 LoadSin.getValue(0), LoadCos.getValue(0));
5976 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5977 // Monotonic load/store is legal for all targets
5978 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5981 // Acquire/Release load/store is not legal for targets without a
5982 // dmb or equivalent available.
5986 static void ReplaceREADCYCLECOUNTER(SDNode *N,
5987 SmallVectorImpl<SDValue> &Results,
5989 const ARMSubtarget *Subtarget) {
5991 SDValue Cycles32, OutChain;
5993 if (Subtarget->hasPerfMon()) {
5994 // Under Power Management extensions, the cycle-count is:
5995 // mrc p15, #0, <Rt>, c9, c13, #0
5996 SDValue Ops[] = { N->getOperand(0), // Chain
5997 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
5998 DAG.getConstant(15, MVT::i32),
5999 DAG.getConstant(0, MVT::i32),
6000 DAG.getConstant(9, MVT::i32),
6001 DAG.getConstant(13, MVT::i32),
6002 DAG.getConstant(0, MVT::i32)
6005 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6006 DAG.getVTList(MVT::i32, MVT::Other), Ops);
6007 OutChain = Cycles32.getValue(1);
6009 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6010 // there are older ARM CPUs that have implementation-specific ways of
6011 // obtaining this information (FIXME!).
6012 Cycles32 = DAG.getConstant(0, MVT::i32);
6013 OutChain = DAG.getEntryNode();
6017 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6018 Cycles32, DAG.getConstant(0, MVT::i32));
6019 Results.push_back(Cycles64);
6020 Results.push_back(OutChain);
6023 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6024 switch (Op.getOpcode()) {
6025 default: llvm_unreachable("Don't know how to custom lower this!");
6026 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6027 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6028 case ISD::GlobalAddress:
6029 return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6030 LowerGlobalAddressELF(Op, DAG);
6031 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6032 case ISD::SELECT: return LowerSELECT(Op, DAG);
6033 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6034 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6035 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6036 case ISD::VASTART: return LowerVASTART(Op, DAG);
6037 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6038 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6039 case ISD::SINT_TO_FP:
6040 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6041 case ISD::FP_TO_SINT:
6042 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6043 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6044 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6045 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6046 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6047 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6048 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6049 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6051 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6054 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6055 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6056 case ISD::SRL_PARTS:
6057 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6058 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6059 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6060 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6061 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6062 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6063 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6064 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6065 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6066 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6067 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6068 case ISD::MUL: return LowerMUL(Op, DAG);
6069 case ISD::SDIV: return LowerSDIV(Op, DAG);
6070 case ISD::UDIV: return LowerUDIV(Op, DAG);
6074 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6075 case ISD::ATOMIC_LOAD:
6076 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6077 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
6079 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6083 /// ReplaceNodeResults - Replace the results of node with an illegal result
6084 /// type with new values built out of custom code.
6085 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6086 SmallVectorImpl<SDValue>&Results,
6087 SelectionDAG &DAG) const {
6089 switch (N->getOpcode()) {
6091 llvm_unreachable("Don't know how to custom expand this!");
6093 Res = ExpandBITCAST(N, DAG);
6097 Res = Expand64BitShift(N, DAG, Subtarget);
6099 case ISD::READCYCLECOUNTER:
6100 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6104 Results.push_back(Res);
6107 //===----------------------------------------------------------------------===//
6108 // ARM Scheduler Hooks
6109 //===----------------------------------------------------------------------===//
6111 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6112 /// registers the function context.
6113 void ARMTargetLowering::
6114 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6115 MachineBasicBlock *DispatchBB, int FI) const {
6116 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6117 DebugLoc dl = MI->getDebugLoc();
6118 MachineFunction *MF = MBB->getParent();
6119 MachineRegisterInfo *MRI = &MF->getRegInfo();
6120 MachineConstantPool *MCP = MF->getConstantPool();
6121 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6122 const Function *F = MF->getFunction();
6124 bool isThumb = Subtarget->isThumb();
6125 bool isThumb2 = Subtarget->isThumb2();
6127 unsigned PCLabelId = AFI->createPICLabelUId();
6128 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6129 ARMConstantPoolValue *CPV =
6130 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6131 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6133 const TargetRegisterClass *TRC = isThumb ?
6134 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6135 (const TargetRegisterClass*)&ARM::GPRRegClass;
6137 // Grab constant pool and fixed stack memory operands.
6138 MachineMemOperand *CPMMO =
6139 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6140 MachineMemOperand::MOLoad, 4, 4);
6142 MachineMemOperand *FIMMOSt =
6143 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6144 MachineMemOperand::MOStore, 4, 4);
6146 // Load the address of the dispatch MBB into the jump buffer.
6148 // Incoming value: jbuf
6149 // ldr.n r5, LCPI1_1
6152 // str r5, [$jbuf, #+4] ; &jbuf[1]
6153 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6154 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6155 .addConstantPoolIndex(CPI)
6156 .addMemOperand(CPMMO));
6157 // Set the low bit because of thumb mode.
6158 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6160 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6161 .addReg(NewVReg1, RegState::Kill)
6163 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6164 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6165 .addReg(NewVReg2, RegState::Kill)
6167 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6168 .addReg(NewVReg3, RegState::Kill)
6170 .addImm(36) // &jbuf[1] :: pc
6171 .addMemOperand(FIMMOSt));
6172 } else if (isThumb) {
6173 // Incoming value: jbuf
6174 // ldr.n r1, LCPI1_4
6178 // add r2, $jbuf, #+4 ; &jbuf[1]
6180 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6181 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6182 .addConstantPoolIndex(CPI)
6183 .addMemOperand(CPMMO));
6184 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6185 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6186 .addReg(NewVReg1, RegState::Kill)
6188 // Set the low bit because of thumb mode.
6189 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6190 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6191 .addReg(ARM::CPSR, RegState::Define)
6193 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6194 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6195 .addReg(ARM::CPSR, RegState::Define)
6196 .addReg(NewVReg2, RegState::Kill)
6197 .addReg(NewVReg3, RegState::Kill));
6198 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6199 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6201 .addImm(36)); // &jbuf[1] :: pc
6202 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6203 .addReg(NewVReg4, RegState::Kill)
6204 .addReg(NewVReg5, RegState::Kill)
6206 .addMemOperand(FIMMOSt));
6208 // Incoming value: jbuf
6211 // str r1, [$jbuf, #+4] ; &jbuf[1]
6212 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6213 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6214 .addConstantPoolIndex(CPI)
6216 .addMemOperand(CPMMO));
6217 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6218 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6219 .addReg(NewVReg1, RegState::Kill)
6220 .addImm(PCLabelId));
6221 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6222 .addReg(NewVReg2, RegState::Kill)
6224 .addImm(36) // &jbuf[1] :: pc
6225 .addMemOperand(FIMMOSt));
6229 MachineBasicBlock *ARMTargetLowering::
6230 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6231 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6232 DebugLoc dl = MI->getDebugLoc();
6233 MachineFunction *MF = MBB->getParent();
6234 MachineRegisterInfo *MRI = &MF->getRegInfo();
6235 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6236 MachineFrameInfo *MFI = MF->getFrameInfo();
6237 int FI = MFI->getFunctionContextIndex();
6239 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6240 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6241 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6243 // Get a mapping of the call site numbers to all of the landing pads they're
6245 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6246 unsigned MaxCSNum = 0;
6247 MachineModuleInfo &MMI = MF->getMMI();
6248 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6250 if (!BB->isLandingPad()) continue;
6252 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6254 for (MachineBasicBlock::iterator
6255 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6256 if (!II->isEHLabel()) continue;
6258 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6259 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6261 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6262 for (SmallVectorImpl<unsigned>::iterator
6263 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6264 CSI != CSE; ++CSI) {
6265 CallSiteNumToLPad[*CSI].push_back(BB);
6266 MaxCSNum = std::max(MaxCSNum, *CSI);
6272 // Get an ordered list of the machine basic blocks for the jump table.
6273 std::vector<MachineBasicBlock*> LPadList;
6274 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6275 LPadList.reserve(CallSiteNumToLPad.size());
6276 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6277 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6278 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6279 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6280 LPadList.push_back(*II);
6281 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6285 assert(!LPadList.empty() &&
6286 "No landing pad destinations for the dispatch jump table!");
6288 // Create the jump table and associated information.
6289 MachineJumpTableInfo *JTI =
6290 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6291 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6292 unsigned UId = AFI->createJumpTableUId();
6293 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6295 // Create the MBBs for the dispatch code.
6297 // Shove the dispatch's address into the return slot in the function context.
6298 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6299 DispatchBB->setIsLandingPad();
6301 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6302 unsigned trap_opcode;
6303 if (Subtarget->isThumb())
6304 trap_opcode = ARM::tTRAP;
6306 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6308 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6309 DispatchBB->addSuccessor(TrapBB);
6311 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6312 DispatchBB->addSuccessor(DispContBB);
6315 MF->insert(MF->end(), DispatchBB);
6316 MF->insert(MF->end(), DispContBB);
6317 MF->insert(MF->end(), TrapBB);
6319 // Insert code into the entry block that creates and registers the function
6321 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6323 MachineMemOperand *FIMMOLd =
6324 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6325 MachineMemOperand::MOLoad |
6326 MachineMemOperand::MOVolatile, 4, 4);
6328 MachineInstrBuilder MIB;
6329 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6331 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6332 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6334 // Add a register mask with no preserved registers. This results in all
6335 // registers being marked as clobbered.
6336 MIB.addRegMask(RI.getNoPreservedMask());
6338 unsigned NumLPads = LPadList.size();
6339 if (Subtarget->isThumb2()) {
6340 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6341 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6344 .addMemOperand(FIMMOLd));
6346 if (NumLPads < 256) {
6347 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6349 .addImm(LPadList.size()));
6351 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6352 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6353 .addImm(NumLPads & 0xFFFF));
6355 unsigned VReg2 = VReg1;
6356 if ((NumLPads & 0xFFFF0000) != 0) {
6357 VReg2 = MRI->createVirtualRegister(TRC);
6358 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6360 .addImm(NumLPads >> 16));
6363 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6368 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6373 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6374 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6375 .addJumpTableIndex(MJTI)
6378 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6381 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6382 .addReg(NewVReg3, RegState::Kill)
6384 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6386 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6387 .addReg(NewVReg4, RegState::Kill)
6389 .addJumpTableIndex(MJTI)
6391 } else if (Subtarget->isThumb()) {
6392 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6393 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6396 .addMemOperand(FIMMOLd));
6398 if (NumLPads < 256) {
6399 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6403 MachineConstantPool *ConstantPool = MF->getConstantPool();
6404 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6405 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6407 // MachineConstantPool wants an explicit alignment.
6408 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6410 Align = getDataLayout()->getTypeAllocSize(C->getType());
6411 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6413 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6414 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6415 .addReg(VReg1, RegState::Define)
6416 .addConstantPoolIndex(Idx));
6417 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6422 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6427 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6428 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6429 .addReg(ARM::CPSR, RegState::Define)
6433 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6434 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6435 .addJumpTableIndex(MJTI)
6438 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6439 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6440 .addReg(ARM::CPSR, RegState::Define)
6441 .addReg(NewVReg2, RegState::Kill)
6444 MachineMemOperand *JTMMOLd =
6445 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6446 MachineMemOperand::MOLoad, 4, 4);
6448 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6449 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6450 .addReg(NewVReg4, RegState::Kill)
6452 .addMemOperand(JTMMOLd));
6454 unsigned NewVReg6 = NewVReg5;
6455 if (RelocM == Reloc::PIC_) {
6456 NewVReg6 = MRI->createVirtualRegister(TRC);
6457 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6458 .addReg(ARM::CPSR, RegState::Define)
6459 .addReg(NewVReg5, RegState::Kill)
6463 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6464 .addReg(NewVReg6, RegState::Kill)
6465 .addJumpTableIndex(MJTI)
6468 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6469 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6472 .addMemOperand(FIMMOLd));
6474 if (NumLPads < 256) {
6475 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6478 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6479 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6480 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6481 .addImm(NumLPads & 0xFFFF));
6483 unsigned VReg2 = VReg1;
6484 if ((NumLPads & 0xFFFF0000) != 0) {
6485 VReg2 = MRI->createVirtualRegister(TRC);
6486 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6488 .addImm(NumLPads >> 16));
6491 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6495 MachineConstantPool *ConstantPool = MF->getConstantPool();
6496 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6497 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6499 // MachineConstantPool wants an explicit alignment.
6500 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6502 Align = getDataLayout()->getTypeAllocSize(C->getType());
6503 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6505 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6506 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6507 .addReg(VReg1, RegState::Define)
6508 .addConstantPoolIndex(Idx)
6510 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6512 .addReg(VReg1, RegState::Kill));
6515 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6520 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6522 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6524 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6525 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6526 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6527 .addJumpTableIndex(MJTI)
6530 MachineMemOperand *JTMMOLd =
6531 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6532 MachineMemOperand::MOLoad, 4, 4);
6533 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6535 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6536 .addReg(NewVReg3, RegState::Kill)
6539 .addMemOperand(JTMMOLd));
6541 if (RelocM == Reloc::PIC_) {
6542 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6543 .addReg(NewVReg5, RegState::Kill)
6545 .addJumpTableIndex(MJTI)
6548 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6549 .addReg(NewVReg5, RegState::Kill)
6550 .addJumpTableIndex(MJTI)
6555 // Add the jump table entries as successors to the MBB.
6556 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6557 for (std::vector<MachineBasicBlock*>::iterator
6558 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6559 MachineBasicBlock *CurMBB = *I;
6560 if (SeenMBBs.insert(CurMBB))
6561 DispContBB->addSuccessor(CurMBB);
6564 // N.B. the order the invoke BBs are processed in doesn't matter here.
6565 const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6566 SmallVector<MachineBasicBlock*, 64> MBBLPads;
6567 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6568 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6569 MachineBasicBlock *BB = *I;
6571 // Remove the landing pad successor from the invoke block and replace it
6572 // with the new dispatch block.
6573 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6575 while (!Successors.empty()) {
6576 MachineBasicBlock *SMBB = Successors.pop_back_val();
6577 if (SMBB->isLandingPad()) {
6578 BB->removeSuccessor(SMBB);
6579 MBBLPads.push_back(SMBB);
6583 BB->addSuccessor(DispatchBB);
6585 // Find the invoke call and mark all of the callee-saved registers as
6586 // 'implicit defined' so that they're spilled. This prevents code from
6587 // moving instructions to before the EH block, where they will never be
6589 for (MachineBasicBlock::reverse_iterator
6590 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6591 if (!II->isCall()) continue;
6593 DenseMap<unsigned, bool> DefRegs;
6594 for (MachineInstr::mop_iterator
6595 OI = II->operands_begin(), OE = II->operands_end();
6597 if (!OI->isReg()) continue;
6598 DefRegs[OI->getReg()] = true;
6601 MachineInstrBuilder MIB(*MF, &*II);
6603 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6604 unsigned Reg = SavedRegs[i];
6605 if (Subtarget->isThumb2() &&
6606 !ARM::tGPRRegClass.contains(Reg) &&
6607 !ARM::hGPRRegClass.contains(Reg))
6609 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6611 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6614 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6621 // Mark all former landing pads as non-landing pads. The dispatch is the only
6623 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6624 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6625 (*I)->setIsLandingPad(false);
6627 // The instruction is gone now.
6628 MI->eraseFromParent();
6634 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6635 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6636 E = MBB->succ_end(); I != E; ++I)
6639 llvm_unreachable("Expecting a BB with two successors!");
6642 /// Return the load opcode for a given load size. If load size >= 8,
6643 /// neon opcode will be returned.
6644 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6646 return LdSize == 16 ? ARM::VLD1q32wb_fixed
6647 : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6649 return LdSize == 4 ? ARM::tLDRi
6650 : LdSize == 2 ? ARM::tLDRHi
6651 : LdSize == 1 ? ARM::tLDRBi : 0;
6653 return LdSize == 4 ? ARM::t2LDR_POST
6654 : LdSize == 2 ? ARM::t2LDRH_POST
6655 : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6656 return LdSize == 4 ? ARM::LDR_POST_IMM
6657 : LdSize == 2 ? ARM::LDRH_POST
6658 : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6661 /// Return the store opcode for a given store size. If store size >= 8,
6662 /// neon opcode will be returned.
6663 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6665 return StSize == 16 ? ARM::VST1q32wb_fixed
6666 : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6668 return StSize == 4 ? ARM::tSTRi
6669 : StSize == 2 ? ARM::tSTRHi
6670 : StSize == 1 ? ARM::tSTRBi : 0;
6672 return StSize == 4 ? ARM::t2STR_POST
6673 : StSize == 2 ? ARM::t2STRH_POST
6674 : StSize == 1 ? ARM::t2STRB_POST : 0;
6675 return StSize == 4 ? ARM::STR_POST_IMM
6676 : StSize == 2 ? ARM::STRH_POST
6677 : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6680 /// Emit a post-increment load operation with given size. The instructions
6681 /// will be added to BB at Pos.
6682 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6683 const TargetInstrInfo *TII, DebugLoc dl,
6684 unsigned LdSize, unsigned Data, unsigned AddrIn,
6685 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6686 unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6687 assert(LdOpc != 0 && "Should have a load opcode");
6689 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6690 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6692 } else if (IsThumb1) {
6693 // load + update AddrIn
6694 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6695 .addReg(AddrIn).addImm(0));
6696 MachineInstrBuilder MIB =
6697 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6698 MIB = AddDefaultT1CC(MIB);
6699 MIB.addReg(AddrIn).addImm(LdSize);
6700 AddDefaultPred(MIB);
6701 } else if (IsThumb2) {
6702 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6703 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6706 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6707 .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6708 .addReg(0).addImm(LdSize));
6712 /// Emit a post-increment store operation with given size. The instructions
6713 /// will be added to BB at Pos.
6714 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6715 const TargetInstrInfo *TII, DebugLoc dl,
6716 unsigned StSize, unsigned Data, unsigned AddrIn,
6717 unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6718 unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6719 assert(StOpc != 0 && "Should have a store opcode");
6721 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6722 .addReg(AddrIn).addImm(0).addReg(Data));
6723 } else if (IsThumb1) {
6724 // store + update AddrIn
6725 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6726 .addReg(AddrIn).addImm(0));
6727 MachineInstrBuilder MIB =
6728 BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6729 MIB = AddDefaultT1CC(MIB);
6730 MIB.addReg(AddrIn).addImm(StSize);
6731 AddDefaultPred(MIB);
6732 } else if (IsThumb2) {
6733 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6734 .addReg(Data).addReg(AddrIn).addImm(StSize));
6736 AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6737 .addReg(Data).addReg(AddrIn).addReg(0)
6743 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6744 MachineBasicBlock *BB) const {
6745 // This pseudo instruction has 3 operands: dst, src, size
6746 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6747 // Otherwise, we will generate unrolled scalar copies.
6748 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6749 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6750 MachineFunction::iterator It = BB;
6753 unsigned dest = MI->getOperand(0).getReg();
6754 unsigned src = MI->getOperand(1).getReg();
6755 unsigned SizeVal = MI->getOperand(2).getImm();
6756 unsigned Align = MI->getOperand(3).getImm();
6757 DebugLoc dl = MI->getDebugLoc();
6759 MachineFunction *MF = BB->getParent();
6760 MachineRegisterInfo &MRI = MF->getRegInfo();
6761 unsigned UnitSize = 0;
6762 const TargetRegisterClass *TRC = nullptr;
6763 const TargetRegisterClass *VecTRC = nullptr;
6765 bool IsThumb1 = Subtarget->isThumb1Only();
6766 bool IsThumb2 = Subtarget->isThumb2();
6770 } else if (Align & 2) {
6773 // Check whether we can use NEON instructions.
6774 if (!MF->getFunction()->getAttributes().
6775 hasAttribute(AttributeSet::FunctionIndex,
6776 Attribute::NoImplicitFloat) &&
6777 Subtarget->hasNEON()) {
6778 if ((Align % 16 == 0) && SizeVal >= 16)
6780 else if ((Align % 8 == 0) && SizeVal >= 8)
6783 // Can't use NEON instructions.
6788 // Select the correct opcode and register class for unit size load/store
6789 bool IsNeon = UnitSize >= 8;
6790 TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6791 : (const TargetRegisterClass *)&ARM::GPRRegClass;
6793 VecTRC = UnitSize == 16
6794 ? (const TargetRegisterClass *)&ARM::DPairRegClass
6796 ? (const TargetRegisterClass *)&ARM::DPRRegClass
6799 unsigned BytesLeft = SizeVal % UnitSize;
6800 unsigned LoopSize = SizeVal - BytesLeft;
6802 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6803 // Use LDR and STR to copy.
6804 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6805 // [destOut] = STR_POST(scratch, destIn, UnitSize)
6806 unsigned srcIn = src;
6807 unsigned destIn = dest;
6808 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6809 unsigned srcOut = MRI.createVirtualRegister(TRC);
6810 unsigned destOut = MRI.createVirtualRegister(TRC);
6811 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6812 emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6813 IsThumb1, IsThumb2);
6814 emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6815 IsThumb1, IsThumb2);
6820 // Handle the leftover bytes with LDRB and STRB.
6821 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6822 // [destOut] = STRB_POST(scratch, destIn, 1)
6823 for (unsigned i = 0; i < BytesLeft; i++) {
6824 unsigned srcOut = MRI.createVirtualRegister(TRC);
6825 unsigned destOut = MRI.createVirtualRegister(TRC);
6826 unsigned scratch = MRI.createVirtualRegister(TRC);
6827 emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6828 IsThumb1, IsThumb2);
6829 emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6830 IsThumb1, IsThumb2);
6834 MI->eraseFromParent(); // The instruction is gone now.
6838 // Expand the pseudo op to a loop.
6841 // movw varEnd, # --> with thumb2
6843 // ldrcp varEnd, idx --> without thumb2
6844 // fallthrough --> loopMBB
6846 // PHI varPhi, varEnd, varLoop
6847 // PHI srcPhi, src, srcLoop
6848 // PHI destPhi, dst, destLoop
6849 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6850 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6851 // subs varLoop, varPhi, #UnitSize
6853 // fallthrough --> exitMBB
6855 // epilogue to handle left-over bytes
6856 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6857 // [destOut] = STRB_POST(scratch, destLoop, 1)
6858 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6859 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6860 MF->insert(It, loopMBB);
6861 MF->insert(It, exitMBB);
6863 // Transfer the remainder of BB and its successor edges to exitMBB.
6864 exitMBB->splice(exitMBB->begin(), BB,
6865 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6866 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6868 // Load an immediate to varEnd.
6869 unsigned varEnd = MRI.createVirtualRegister(TRC);
6871 unsigned Vtmp = varEnd;
6872 if ((LoopSize & 0xFFFF0000) != 0)
6873 Vtmp = MRI.createVirtualRegister(TRC);
6874 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6875 .addImm(LoopSize & 0xFFFF));
6877 if ((LoopSize & 0xFFFF0000) != 0)
6878 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6879 .addReg(Vtmp).addImm(LoopSize >> 16));
6881 MachineConstantPool *ConstantPool = MF->getConstantPool();
6882 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6883 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6885 // MachineConstantPool wants an explicit alignment.
6886 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6888 Align = getDataLayout()->getTypeAllocSize(C->getType());
6889 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6892 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6893 varEnd, RegState::Define).addConstantPoolIndex(Idx));
6895 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6896 varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6898 BB->addSuccessor(loopMBB);
6900 // Generate the loop body:
6901 // varPhi = PHI(varLoop, varEnd)
6902 // srcPhi = PHI(srcLoop, src)
6903 // destPhi = PHI(destLoop, dst)
6904 MachineBasicBlock *entryBB = BB;
6906 unsigned varLoop = MRI.createVirtualRegister(TRC);
6907 unsigned varPhi = MRI.createVirtualRegister(TRC);
6908 unsigned srcLoop = MRI.createVirtualRegister(TRC);
6909 unsigned srcPhi = MRI.createVirtualRegister(TRC);
6910 unsigned destLoop = MRI.createVirtualRegister(TRC);
6911 unsigned destPhi = MRI.createVirtualRegister(TRC);
6913 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6914 .addReg(varLoop).addMBB(loopMBB)
6915 .addReg(varEnd).addMBB(entryBB);
6916 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6917 .addReg(srcLoop).addMBB(loopMBB)
6918 .addReg(src).addMBB(entryBB);
6919 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6920 .addReg(destLoop).addMBB(loopMBB)
6921 .addReg(dest).addMBB(entryBB);
6923 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6924 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6925 unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6926 emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6927 IsThumb1, IsThumb2);
6928 emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6929 IsThumb1, IsThumb2);
6931 // Decrement loop variable by UnitSize.
6933 MachineInstrBuilder MIB =
6934 BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6935 MIB = AddDefaultT1CC(MIB);
6936 MIB.addReg(varPhi).addImm(UnitSize);
6937 AddDefaultPred(MIB);
6939 MachineInstrBuilder MIB =
6940 BuildMI(*BB, BB->end(), dl,
6941 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6942 AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6943 MIB->getOperand(5).setReg(ARM::CPSR);
6944 MIB->getOperand(5).setIsDef(true);
6946 BuildMI(*BB, BB->end(), dl,
6947 TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6948 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6950 // loopMBB can loop back to loopMBB or fall through to exitMBB.
6951 BB->addSuccessor(loopMBB);
6952 BB->addSuccessor(exitMBB);
6954 // Add epilogue to handle BytesLeft.
6956 MachineInstr *StartOfExit = exitMBB->begin();
6958 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6959 // [destOut] = STRB_POST(scratch, destLoop, 1)
6960 unsigned srcIn = srcLoop;
6961 unsigned destIn = destLoop;
6962 for (unsigned i = 0; i < BytesLeft; i++) {
6963 unsigned srcOut = MRI.createVirtualRegister(TRC);
6964 unsigned destOut = MRI.createVirtualRegister(TRC);
6965 unsigned scratch = MRI.createVirtualRegister(TRC);
6966 emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
6967 IsThumb1, IsThumb2);
6968 emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
6969 IsThumb1, IsThumb2);
6974 MI->eraseFromParent(); // The instruction is gone now.
6979 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6980 MachineBasicBlock *BB) const {
6981 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6982 DebugLoc dl = MI->getDebugLoc();
6983 bool isThumb2 = Subtarget->isThumb2();
6984 switch (MI->getOpcode()) {
6987 llvm_unreachable("Unexpected instr type to insert");
6989 // The Thumb2 pre-indexed stores have the same MI operands, they just
6990 // define them differently in the .td files from the isel patterns, so
6991 // they need pseudos.
6992 case ARM::t2STR_preidx:
6993 MI->setDesc(TII->get(ARM::t2STR_PRE));
6995 case ARM::t2STRB_preidx:
6996 MI->setDesc(TII->get(ARM::t2STRB_PRE));
6998 case ARM::t2STRH_preidx:
6999 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7002 case ARM::STRi_preidx:
7003 case ARM::STRBi_preidx: {
7004 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7005 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7006 // Decode the offset.
7007 unsigned Offset = MI->getOperand(4).getImm();
7008 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7009 Offset = ARM_AM::getAM2Offset(Offset);
7013 MachineMemOperand *MMO = *MI->memoperands_begin();
7014 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7015 .addOperand(MI->getOperand(0)) // Rn_wb
7016 .addOperand(MI->getOperand(1)) // Rt
7017 .addOperand(MI->getOperand(2)) // Rn
7018 .addImm(Offset) // offset (skip GPR==zero_reg)
7019 .addOperand(MI->getOperand(5)) // pred
7020 .addOperand(MI->getOperand(6))
7021 .addMemOperand(MMO);
7022 MI->eraseFromParent();
7025 case ARM::STRr_preidx:
7026 case ARM::STRBr_preidx:
7027 case ARM::STRH_preidx: {
7029 switch (MI->getOpcode()) {
7030 default: llvm_unreachable("unexpected opcode!");
7031 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7032 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7033 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7035 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7036 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7037 MIB.addOperand(MI->getOperand(i));
7038 MI->eraseFromParent();
7042 case ARM::tMOVCCr_pseudo: {
7043 // To "insert" a SELECT_CC instruction, we actually have to insert the
7044 // diamond control-flow pattern. The incoming instruction knows the
7045 // destination vreg to set, the condition code register to branch on, the
7046 // true/false values to select between, and a branch opcode to use.
7047 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7048 MachineFunction::iterator It = BB;
7054 // cmpTY ccX, r1, r2
7056 // fallthrough --> copy0MBB
7057 MachineBasicBlock *thisMBB = BB;
7058 MachineFunction *F = BB->getParent();
7059 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7060 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7061 F->insert(It, copy0MBB);
7062 F->insert(It, sinkMBB);
7064 // Transfer the remainder of BB and its successor edges to sinkMBB.
7065 sinkMBB->splice(sinkMBB->begin(), BB,
7066 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7067 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7069 BB->addSuccessor(copy0MBB);
7070 BB->addSuccessor(sinkMBB);
7072 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7073 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7076 // %FalseValue = ...
7077 // # fallthrough to sinkMBB
7080 // Update machine-CFG edges
7081 BB->addSuccessor(sinkMBB);
7084 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7087 BuildMI(*BB, BB->begin(), dl,
7088 TII->get(ARM::PHI), MI->getOperand(0).getReg())
7089 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7090 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7092 MI->eraseFromParent(); // The pseudo instruction is gone now.
7097 case ARM::BCCZi64: {
7098 // If there is an unconditional branch to the other successor, remove it.
7099 BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7101 // Compare both parts that make up the double comparison separately for
7103 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7105 unsigned LHS1 = MI->getOperand(1).getReg();
7106 unsigned LHS2 = MI->getOperand(2).getReg();
7108 AddDefaultPred(BuildMI(BB, dl,
7109 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7110 .addReg(LHS1).addImm(0));
7111 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7112 .addReg(LHS2).addImm(0)
7113 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7115 unsigned RHS1 = MI->getOperand(3).getReg();
7116 unsigned RHS2 = MI->getOperand(4).getReg();
7117 AddDefaultPred(BuildMI(BB, dl,
7118 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7119 .addReg(LHS1).addReg(RHS1));
7120 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7121 .addReg(LHS2).addReg(RHS2)
7122 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7125 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7126 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7127 if (MI->getOperand(0).getImm() == ARMCC::NE)
7128 std::swap(destMBB, exitMBB);
7130 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7131 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7133 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7135 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7137 MI->eraseFromParent(); // The pseudo instruction is gone now.
7141 case ARM::Int_eh_sjlj_setjmp:
7142 case ARM::Int_eh_sjlj_setjmp_nofp:
7143 case ARM::tInt_eh_sjlj_setjmp:
7144 case ARM::t2Int_eh_sjlj_setjmp:
7145 case ARM::t2Int_eh_sjlj_setjmp_nofp:
7146 EmitSjLjDispatchBlock(MI, BB);
7151 // To insert an ABS instruction, we have to insert the
7152 // diamond control-flow pattern. The incoming instruction knows the
7153 // source vreg to test against 0, the destination vreg to set,
7154 // the condition code register to branch on, the
7155 // true/false values to select between, and a branch opcode to use.
7160 // BCC (branch to SinkBB if V0 >= 0)
7161 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
7162 // SinkBB: V1 = PHI(V2, V3)
7163 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7164 MachineFunction::iterator BBI = BB;
7166 MachineFunction *Fn = BB->getParent();
7167 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7168 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7169 Fn->insert(BBI, RSBBB);
7170 Fn->insert(BBI, SinkBB);
7172 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7173 unsigned int ABSDstReg = MI->getOperand(0).getReg();
7174 bool isThumb2 = Subtarget->isThumb2();
7175 MachineRegisterInfo &MRI = Fn->getRegInfo();
7176 // In Thumb mode S must not be specified if source register is the SP or
7177 // PC and if destination register is the SP, so restrict register class
7178 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7179 (const TargetRegisterClass*)&ARM::rGPRRegClass :
7180 (const TargetRegisterClass*)&ARM::GPRRegClass);
7182 // Transfer the remainder of BB and its successor edges to sinkMBB.
7183 SinkBB->splice(SinkBB->begin(), BB,
7184 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7185 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7187 BB->addSuccessor(RSBBB);
7188 BB->addSuccessor(SinkBB);
7190 // fall through to SinkMBB
7191 RSBBB->addSuccessor(SinkBB);
7193 // insert a cmp at the end of BB
7194 AddDefaultPred(BuildMI(BB, dl,
7195 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7196 .addReg(ABSSrcReg).addImm(0));
7198 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7200 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7201 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7203 // insert rsbri in RSBBB
7204 // Note: BCC and rsbri will be converted into predicated rsbmi
7205 // by if-conversion pass
7206 BuildMI(*RSBBB, RSBBB->begin(), dl,
7207 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7208 .addReg(ABSSrcReg, RegState::Kill)
7209 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7211 // insert PHI in SinkBB,
7212 // reuse ABSDstReg to not change uses of ABS instruction
7213 BuildMI(*SinkBB, SinkBB->begin(), dl,
7214 TII->get(ARM::PHI), ABSDstReg)
7215 .addReg(NewRsbDstReg).addMBB(RSBBB)
7216 .addReg(ABSSrcReg).addMBB(BB);
7218 // remove ABS instruction
7219 MI->eraseFromParent();
7221 // return last added BB
7224 case ARM::COPY_STRUCT_BYVAL_I32:
7226 return EmitStructByval(MI, BB);
7230 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7231 SDNode *Node) const {
7232 if (!MI->hasPostISelHook()) {
7233 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7234 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7238 const MCInstrDesc *MCID = &MI->getDesc();
7239 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7240 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7241 // operand is still set to noreg. If needed, set the optional operand's
7242 // register to CPSR, and remove the redundant implicit def.
7244 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7246 // Rename pseudo opcodes.
7247 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7249 const ARMBaseInstrInfo *TII =
7250 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7251 MCID = &TII->get(NewOpc);
7253 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7254 "converted opcode should be the same except for cc_out");
7258 // Add the optional cc_out operand
7259 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7261 unsigned ccOutIdx = MCID->getNumOperands() - 1;
7263 // Any ARM instruction that sets the 's' bit should specify an optional
7264 // "cc_out" operand in the last operand position.
7265 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7266 assert(!NewOpc && "Optional cc_out operand required");
7269 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7270 // since we already have an optional CPSR def.
7271 bool definesCPSR = false;
7272 bool deadCPSR = false;
7273 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7275 const MachineOperand &MO = MI->getOperand(i);
7276 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7280 MI->RemoveOperand(i);
7285 assert(!NewOpc && "Optional cc_out operand required");
7288 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7290 assert(!MI->getOperand(ccOutIdx).getReg() &&
7291 "expect uninitialized optional cc_out operand");
7295 // If this instruction was defined with an optional CPSR def and its dag node
7296 // had a live implicit CPSR def, then activate the optional CPSR def.
7297 MachineOperand &MO = MI->getOperand(ccOutIdx);
7298 MO.setReg(ARM::CPSR);
7302 //===----------------------------------------------------------------------===//
7303 // ARM Optimization Hooks
7304 //===----------------------------------------------------------------------===//
7306 // Helper function that checks if N is a null or all ones constant.
7307 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7308 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7311 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7314 // Return true if N is conditionally 0 or all ones.
7315 // Detects these expressions where cc is an i1 value:
7317 // (select cc 0, y) [AllOnes=0]
7318 // (select cc y, 0) [AllOnes=0]
7319 // (zext cc) [AllOnes=0]
7320 // (sext cc) [AllOnes=0/1]
7321 // (select cc -1, y) [AllOnes=1]
7322 // (select cc y, -1) [AllOnes=1]
7324 // Invert is set when N is the null/all ones constant when CC is false.
7325 // OtherOp is set to the alternative value of N.
7326 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7327 SDValue &CC, bool &Invert,
7329 SelectionDAG &DAG) {
7330 switch (N->getOpcode()) {
7331 default: return false;
7333 CC = N->getOperand(0);
7334 SDValue N1 = N->getOperand(1);
7335 SDValue N2 = N->getOperand(2);
7336 if (isZeroOrAllOnes(N1, AllOnes)) {
7341 if (isZeroOrAllOnes(N2, AllOnes)) {
7348 case ISD::ZERO_EXTEND:
7349 // (zext cc) can never be the all ones value.
7353 case ISD::SIGN_EXTEND: {
7354 EVT VT = N->getValueType(0);
7355 CC = N->getOperand(0);
7356 if (CC.getValueType() != MVT::i1)
7360 // When looking for an AllOnes constant, N is an sext, and the 'other'
7362 OtherOp = DAG.getConstant(0, VT);
7363 else if (N->getOpcode() == ISD::ZERO_EXTEND)
7364 // When looking for a 0 constant, N can be zext or sext.
7365 OtherOp = DAG.getConstant(1, VT);
7367 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7373 // Combine a constant select operand into its use:
7375 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7376 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7377 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
7378 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7379 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
7381 // The transform is rejected if the select doesn't have a constant operand that
7382 // is null, or all ones when AllOnes is set.
7384 // Also recognize sext/zext from i1:
7386 // (add (zext cc), x) -> (select cc (add x, 1), x)
7387 // (add (sext cc), x) -> (select cc (add x, -1), x)
7389 // These transformations eventually create predicated instructions.
7391 // @param N The node to transform.
7392 // @param Slct The N operand that is a select.
7393 // @param OtherOp The other N operand (x above).
7394 // @param DCI Context.
7395 // @param AllOnes Require the select constant to be all ones instead of null.
7396 // @returns The new node, or SDValue() on failure.
7398 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7399 TargetLowering::DAGCombinerInfo &DCI,
7400 bool AllOnes = false) {
7401 SelectionDAG &DAG = DCI.DAG;
7402 EVT VT = N->getValueType(0);
7403 SDValue NonConstantVal;
7406 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7407 NonConstantVal, DAG))
7410 // Slct is now know to be the desired identity constant when CC is true.
7411 SDValue TrueVal = OtherOp;
7412 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7413 OtherOp, NonConstantVal);
7414 // Unless SwapSelectOps says CC should be false.
7416 std::swap(TrueVal, FalseVal);
7418 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7419 CCOp, TrueVal, FalseVal);
7422 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7424 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7425 TargetLowering::DAGCombinerInfo &DCI) {
7426 SDValue N0 = N->getOperand(0);
7427 SDValue N1 = N->getOperand(1);
7428 if (N0.getNode()->hasOneUse()) {
7429 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7430 if (Result.getNode())
7433 if (N1.getNode()->hasOneUse()) {
7434 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7435 if (Result.getNode())
7441 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7442 // (only after legalization).
7443 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7444 TargetLowering::DAGCombinerInfo &DCI,
7445 const ARMSubtarget *Subtarget) {
7447 // Only perform optimization if after legalize, and if NEON is available. We
7448 // also expected both operands to be BUILD_VECTORs.
7449 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7450 || N0.getOpcode() != ISD::BUILD_VECTOR
7451 || N1.getOpcode() != ISD::BUILD_VECTOR)
7454 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7455 EVT VT = N->getValueType(0);
7456 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7459 // Check that the vector operands are of the right form.
7460 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7461 // operands, where N is the size of the formed vector.
7462 // Each EXTRACT_VECTOR should have the same input vector and odd or even
7463 // index such that we have a pair wise add pattern.
7465 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7466 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7468 SDValue Vec = N0->getOperand(0)->getOperand(0);
7469 SDNode *V = Vec.getNode();
7470 unsigned nextIndex = 0;
7472 // For each operands to the ADD which are BUILD_VECTORs,
7473 // check to see if each of their operands are an EXTRACT_VECTOR with
7474 // the same vector and appropriate index.
7475 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7476 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7477 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7479 SDValue ExtVec0 = N0->getOperand(i);
7480 SDValue ExtVec1 = N1->getOperand(i);
7482 // First operand is the vector, verify its the same.
7483 if (V != ExtVec0->getOperand(0).getNode() ||
7484 V != ExtVec1->getOperand(0).getNode())
7487 // Second is the constant, verify its correct.
7488 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7489 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7491 // For the constant, we want to see all the even or all the odd.
7492 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7493 || C1->getZExtValue() != nextIndex+1)
7502 // Create VPADDL node.
7503 SelectionDAG &DAG = DCI.DAG;
7504 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7506 // Build operand list.
7507 SmallVector<SDValue, 8> Ops;
7508 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7509 TLI.getPointerTy()));
7511 // Input is the vector.
7514 // Get widened type and narrowed type.
7516 unsigned numElem = VT.getVectorNumElements();
7518 EVT inputLaneType = Vec.getValueType().getVectorElementType();
7519 switch (inputLaneType.getSimpleVT().SimpleTy) {
7520 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7521 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7522 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7524 llvm_unreachable("Invalid vector element type for padd optimization.");
7527 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7528 unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7529 return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7532 static SDValue findMUL_LOHI(SDValue V) {
7533 if (V->getOpcode() == ISD::UMUL_LOHI ||
7534 V->getOpcode() == ISD::SMUL_LOHI)
7539 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7540 TargetLowering::DAGCombinerInfo &DCI,
7541 const ARMSubtarget *Subtarget) {
7543 if (Subtarget->isThumb1Only()) return SDValue();
7545 // Only perform the checks after legalize when the pattern is available.
7546 if (DCI.isBeforeLegalize()) return SDValue();
7548 // Look for multiply add opportunities.
7549 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7550 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7551 // a glue link from the first add to the second add.
7552 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7553 // a S/UMLAL instruction.
7556 // \ / \ [no multiline comment]
7562 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7563 SDValue AddcOp0 = AddcNode->getOperand(0);
7564 SDValue AddcOp1 = AddcNode->getOperand(1);
7566 // Check if the two operands are from the same mul_lohi node.
7567 if (AddcOp0.getNode() == AddcOp1.getNode())
7570 assert(AddcNode->getNumValues() == 2 &&
7571 AddcNode->getValueType(0) == MVT::i32 &&
7572 "Expect ADDC with two result values. First: i32");
7574 // Check that we have a glued ADDC node.
7575 if (AddcNode->getValueType(1) != MVT::Glue)
7578 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7579 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7580 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7581 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7582 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7585 // Look for the glued ADDE.
7586 SDNode* AddeNode = AddcNode->getGluedUser();
7590 // Make sure it is really an ADDE.
7591 if (AddeNode->getOpcode() != ISD::ADDE)
7594 assert(AddeNode->getNumOperands() == 3 &&
7595 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7596 "ADDE node has the wrong inputs");
7598 // Check for the triangle shape.
7599 SDValue AddeOp0 = AddeNode->getOperand(0);
7600 SDValue AddeOp1 = AddeNode->getOperand(1);
7602 // Make sure that the ADDE operands are not coming from the same node.
7603 if (AddeOp0.getNode() == AddeOp1.getNode())
7606 // Find the MUL_LOHI node walking up ADDE's operands.
7607 bool IsLeftOperandMUL = false;
7608 SDValue MULOp = findMUL_LOHI(AddeOp0);
7609 if (MULOp == SDValue())
7610 MULOp = findMUL_LOHI(AddeOp1);
7612 IsLeftOperandMUL = true;
7613 if (MULOp == SDValue())
7616 // Figure out the right opcode.
7617 unsigned Opc = MULOp->getOpcode();
7618 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7620 // Figure out the high and low input values to the MLAL node.
7621 SDValue* HiMul = &MULOp;
7622 SDValue* HiAdd = nullptr;
7623 SDValue* LoMul = nullptr;
7624 SDValue* LowAdd = nullptr;
7626 if (IsLeftOperandMUL)
7632 if (AddcOp0->getOpcode() == Opc) {
7636 if (AddcOp1->getOpcode() == Opc) {
7644 if (LoMul->getNode() != HiMul->getNode())
7647 // Create the merged node.
7648 SelectionDAG &DAG = DCI.DAG;
7650 // Build operand list.
7651 SmallVector<SDValue, 8> Ops;
7652 Ops.push_back(LoMul->getOperand(0));
7653 Ops.push_back(LoMul->getOperand(1));
7654 Ops.push_back(*LowAdd);
7655 Ops.push_back(*HiAdd);
7657 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
7658 DAG.getVTList(MVT::i32, MVT::i32), Ops);
7660 // Replace the ADDs' nodes uses by the MLA node's values.
7661 SDValue HiMLALResult(MLALNode.getNode(), 1);
7662 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7664 SDValue LoMLALResult(MLALNode.getNode(), 0);
7665 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7667 // Return original node to notify the driver to stop replacing.
7668 SDValue resNode(AddcNode, 0);
7672 /// PerformADDCCombine - Target-specific dag combine transform from
7673 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7674 static SDValue PerformADDCCombine(SDNode *N,
7675 TargetLowering::DAGCombinerInfo &DCI,
7676 const ARMSubtarget *Subtarget) {
7678 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7682 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7683 /// operands N0 and N1. This is a helper for PerformADDCombine that is
7684 /// called with the default operands, and if that fails, with commuted
7686 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7687 TargetLowering::DAGCombinerInfo &DCI,
7688 const ARMSubtarget *Subtarget){
7690 // Attempt to create vpaddl for this add.
7691 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7692 if (Result.getNode())
7695 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7696 if (N0.getNode()->hasOneUse()) {
7697 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7698 if (Result.getNode()) return Result;
7703 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7705 static SDValue PerformADDCombine(SDNode *N,
7706 TargetLowering::DAGCombinerInfo &DCI,
7707 const ARMSubtarget *Subtarget) {
7708 SDValue N0 = N->getOperand(0);
7709 SDValue N1 = N->getOperand(1);
7711 // First try with the default operand order.
7712 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7713 if (Result.getNode())
7716 // If that didn't work, try again with the operands commuted.
7717 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7720 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7722 static SDValue PerformSUBCombine(SDNode *N,
7723 TargetLowering::DAGCombinerInfo &DCI) {
7724 SDValue N0 = N->getOperand(0);
7725 SDValue N1 = N->getOperand(1);
7727 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7728 if (N1.getNode()->hasOneUse()) {
7729 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7730 if (Result.getNode()) return Result;
7736 /// PerformVMULCombine
7737 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7738 /// special multiplier accumulator forwarding.
7744 // However, for (A + B) * (A + B),
7751 static SDValue PerformVMULCombine(SDNode *N,
7752 TargetLowering::DAGCombinerInfo &DCI,
7753 const ARMSubtarget *Subtarget) {
7754 if (!Subtarget->hasVMLxForwarding())
7757 SelectionDAG &DAG = DCI.DAG;
7758 SDValue N0 = N->getOperand(0);
7759 SDValue N1 = N->getOperand(1);
7760 unsigned Opcode = N0.getOpcode();
7761 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7762 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7763 Opcode = N1.getOpcode();
7764 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7765 Opcode != ISD::FADD && Opcode != ISD::FSUB)
7773 EVT VT = N->getValueType(0);
7775 SDValue N00 = N0->getOperand(0);
7776 SDValue N01 = N0->getOperand(1);
7777 return DAG.getNode(Opcode, DL, VT,
7778 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7779 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7782 static SDValue PerformMULCombine(SDNode *N,
7783 TargetLowering::DAGCombinerInfo &DCI,
7784 const ARMSubtarget *Subtarget) {
7785 SelectionDAG &DAG = DCI.DAG;
7787 if (Subtarget->isThumb1Only())
7790 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7793 EVT VT = N->getValueType(0);
7794 if (VT.is64BitVector() || VT.is128BitVector())
7795 return PerformVMULCombine(N, DCI, Subtarget);
7799 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7803 int64_t MulAmt = C->getSExtValue();
7804 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7806 ShiftAmt = ShiftAmt & (32 - 1);
7807 SDValue V = N->getOperand(0);
7811 MulAmt >>= ShiftAmt;
7814 if (isPowerOf2_32(MulAmt - 1)) {
7815 // (mul x, 2^N + 1) => (add (shl x, N), x)
7816 Res = DAG.getNode(ISD::ADD, DL, VT,
7818 DAG.getNode(ISD::SHL, DL, VT,
7820 DAG.getConstant(Log2_32(MulAmt - 1),
7822 } else if (isPowerOf2_32(MulAmt + 1)) {
7823 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7824 Res = DAG.getNode(ISD::SUB, DL, VT,
7825 DAG.getNode(ISD::SHL, DL, VT,
7827 DAG.getConstant(Log2_32(MulAmt + 1),
7833 uint64_t MulAmtAbs = -MulAmt;
7834 if (isPowerOf2_32(MulAmtAbs + 1)) {
7835 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7836 Res = DAG.getNode(ISD::SUB, DL, VT,
7838 DAG.getNode(ISD::SHL, DL, VT,
7840 DAG.getConstant(Log2_32(MulAmtAbs + 1),
7842 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7843 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7844 Res = DAG.getNode(ISD::ADD, DL, VT,
7846 DAG.getNode(ISD::SHL, DL, VT,
7848 DAG.getConstant(Log2_32(MulAmtAbs-1),
7850 Res = DAG.getNode(ISD::SUB, DL, VT,
7851 DAG.getConstant(0, MVT::i32),Res);
7858 Res = DAG.getNode(ISD::SHL, DL, VT,
7859 Res, DAG.getConstant(ShiftAmt, MVT::i32));
7861 // Do not add new nodes to DAG combiner worklist.
7862 DCI.CombineTo(N, Res, false);
7866 static SDValue PerformANDCombine(SDNode *N,
7867 TargetLowering::DAGCombinerInfo &DCI,
7868 const ARMSubtarget *Subtarget) {
7870 // Attempt to use immediate-form VBIC
7871 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7873 EVT VT = N->getValueType(0);
7874 SelectionDAG &DAG = DCI.DAG;
7876 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7879 APInt SplatBits, SplatUndef;
7880 unsigned SplatBitSize;
7883 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7884 if (SplatBitSize <= 64) {
7886 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7887 SplatUndef.getZExtValue(), SplatBitSize,
7888 DAG, VbicVT, VT.is128BitVector(),
7890 if (Val.getNode()) {
7892 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7893 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7894 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7899 if (!Subtarget->isThumb1Only()) {
7900 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7901 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7902 if (Result.getNode())
7909 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7910 static SDValue PerformORCombine(SDNode *N,
7911 TargetLowering::DAGCombinerInfo &DCI,
7912 const ARMSubtarget *Subtarget) {
7913 // Attempt to use immediate-form VORR
7914 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7916 EVT VT = N->getValueType(0);
7917 SelectionDAG &DAG = DCI.DAG;
7919 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7922 APInt SplatBits, SplatUndef;
7923 unsigned SplatBitSize;
7925 if (BVN && Subtarget->hasNEON() &&
7926 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7927 if (SplatBitSize <= 64) {
7929 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7930 SplatUndef.getZExtValue(), SplatBitSize,
7931 DAG, VorrVT, VT.is128BitVector(),
7933 if (Val.getNode()) {
7935 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7936 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7937 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7942 if (!Subtarget->isThumb1Only()) {
7943 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7944 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7945 if (Result.getNode())
7949 // The code below optimizes (or (and X, Y), Z).
7950 // The AND operand needs to have a single user to make these optimizations
7952 SDValue N0 = N->getOperand(0);
7953 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7955 SDValue N1 = N->getOperand(1);
7957 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7958 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7959 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7961 unsigned SplatBitSize;
7964 APInt SplatBits0, SplatBits1;
7965 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7966 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7967 // Ensure that the second operand of both ands are constants
7968 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7969 HasAnyUndefs) && !HasAnyUndefs) {
7970 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7971 HasAnyUndefs) && !HasAnyUndefs) {
7972 // Ensure that the bit width of the constants are the same and that
7973 // the splat arguments are logical inverses as per the pattern we
7974 // are trying to simplify.
7975 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
7976 SplatBits0 == ~SplatBits1) {
7977 // Canonicalize the vector type to make instruction selection
7979 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7980 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7984 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7990 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7993 // BFI is only available on V6T2+
7994 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7998 // 1) or (and A, mask), val => ARMbfi A, val, mask
7999 // iff (val & mask) == val
8001 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8002 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8003 // && mask == ~mask2
8004 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8005 // && ~mask == mask2
8006 // (i.e., copy a bitfield value into another bitfield of the same width)
8011 SDValue N00 = N0.getOperand(0);
8013 // The value and the mask need to be constants so we can verify this is
8014 // actually a bitfield set. If the mask is 0xffff, we can do better
8015 // via a movt instruction, so don't use BFI in that case.
8016 SDValue MaskOp = N0.getOperand(1);
8017 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8020 unsigned Mask = MaskC->getZExtValue();
8024 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8027 unsigned Val = N1C->getZExtValue();
8028 if ((Val & ~Mask) != Val)
8031 if (ARM::isBitFieldInvertedMask(Mask)) {
8032 Val >>= countTrailingZeros(~Mask);
8034 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8035 DAG.getConstant(Val, MVT::i32),
8036 DAG.getConstant(Mask, MVT::i32));
8038 // Do not add new nodes to DAG combiner worklist.
8039 DCI.CombineTo(N, Res, false);
8042 } else if (N1.getOpcode() == ISD::AND) {
8043 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8044 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8047 unsigned Mask2 = N11C->getZExtValue();
8049 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8051 if (ARM::isBitFieldInvertedMask(Mask) &&
8053 // The pack halfword instruction works better for masks that fit it,
8054 // so use that when it's available.
8055 if (Subtarget->hasT2ExtractPack() &&
8056 (Mask == 0xffff || Mask == 0xffff0000))
8059 unsigned amt = countTrailingZeros(Mask2);
8060 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8061 DAG.getConstant(amt, MVT::i32));
8062 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8063 DAG.getConstant(Mask, MVT::i32));
8064 // Do not add new nodes to DAG combiner worklist.
8065 DCI.CombineTo(N, Res, false);
8067 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8069 // The pack halfword instruction works better for masks that fit it,
8070 // so use that when it's available.
8071 if (Subtarget->hasT2ExtractPack() &&
8072 (Mask2 == 0xffff || Mask2 == 0xffff0000))
8075 unsigned lsb = countTrailingZeros(Mask);
8076 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8077 DAG.getConstant(lsb, MVT::i32));
8078 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8079 DAG.getConstant(Mask2, MVT::i32));
8080 // Do not add new nodes to DAG combiner worklist.
8081 DCI.CombineTo(N, Res, false);
8086 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8087 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8088 ARM::isBitFieldInvertedMask(~Mask)) {
8089 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8090 // where lsb(mask) == #shamt and masked bits of B are known zero.
8091 SDValue ShAmt = N00.getOperand(1);
8092 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8093 unsigned LSB = countTrailingZeros(Mask);
8097 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8098 DAG.getConstant(~Mask, MVT::i32));
8100 // Do not add new nodes to DAG combiner worklist.
8101 DCI.CombineTo(N, Res, false);
8107 static SDValue PerformXORCombine(SDNode *N,
8108 TargetLowering::DAGCombinerInfo &DCI,
8109 const ARMSubtarget *Subtarget) {
8110 EVT VT = N->getValueType(0);
8111 SelectionDAG &DAG = DCI.DAG;
8113 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8116 if (!Subtarget->isThumb1Only()) {
8117 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8118 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8119 if (Result.getNode())
8126 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8127 /// the bits being cleared by the AND are not demanded by the BFI.
8128 static SDValue PerformBFICombine(SDNode *N,
8129 TargetLowering::DAGCombinerInfo &DCI) {
8130 SDValue N1 = N->getOperand(1);
8131 if (N1.getOpcode() == ISD::AND) {
8132 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8135 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8136 unsigned LSB = countTrailingZeros(~InvMask);
8137 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8138 unsigned Mask = (1 << Width)-1;
8139 unsigned Mask2 = N11C->getZExtValue();
8140 if ((Mask & (~Mask2)) == 0)
8141 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8142 N->getOperand(0), N1.getOperand(0),
8148 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8149 /// ARMISD::VMOVRRD.
8150 static SDValue PerformVMOVRRDCombine(SDNode *N,
8151 TargetLowering::DAGCombinerInfo &DCI) {
8152 // vmovrrd(vmovdrr x, y) -> x,y
8153 SDValue InDouble = N->getOperand(0);
8154 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8155 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8157 // vmovrrd(load f64) -> (load i32), (load i32)
8158 SDNode *InNode = InDouble.getNode();
8159 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8160 InNode->getValueType(0) == MVT::f64 &&
8161 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8162 !cast<LoadSDNode>(InNode)->isVolatile()) {
8163 // TODO: Should this be done for non-FrameIndex operands?
8164 LoadSDNode *LD = cast<LoadSDNode>(InNode);
8166 SelectionDAG &DAG = DCI.DAG;
8168 SDValue BasePtr = LD->getBasePtr();
8169 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8170 LD->getPointerInfo(), LD->isVolatile(),
8171 LD->isNonTemporal(), LD->isInvariant(),
8172 LD->getAlignment());
8174 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8175 DAG.getConstant(4, MVT::i32));
8176 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8177 LD->getPointerInfo(), LD->isVolatile(),
8178 LD->isNonTemporal(), LD->isInvariant(),
8179 std::min(4U, LD->getAlignment() / 2));
8181 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8182 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8183 DCI.RemoveFromWorklist(LD);
8191 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8192 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
8193 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8194 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8195 SDValue Op0 = N->getOperand(0);
8196 SDValue Op1 = N->getOperand(1);
8197 if (Op0.getOpcode() == ISD::BITCAST)
8198 Op0 = Op0.getOperand(0);
8199 if (Op1.getOpcode() == ISD::BITCAST)
8200 Op1 = Op1.getOperand(0);
8201 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8202 Op0.getNode() == Op1.getNode() &&
8203 Op0.getResNo() == 0 && Op1.getResNo() == 1)
8204 return DAG.getNode(ISD::BITCAST, SDLoc(N),
8205 N->getValueType(0), Op0.getOperand(0));
8209 /// PerformSTORECombine - Target-specific dag combine xforms for
8211 static SDValue PerformSTORECombine(SDNode *N,
8212 TargetLowering::DAGCombinerInfo &DCI) {
8213 StoreSDNode *St = cast<StoreSDNode>(N);
8214 if (St->isVolatile())
8217 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
8218 // pack all of the elements in one place. Next, store to memory in fewer
8220 SDValue StVal = St->getValue();
8221 EVT VT = StVal.getValueType();
8222 if (St->isTruncatingStore() && VT.isVector()) {
8223 SelectionDAG &DAG = DCI.DAG;
8224 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8225 EVT StVT = St->getMemoryVT();
8226 unsigned NumElems = VT.getVectorNumElements();
8227 assert(StVT != VT && "Cannot truncate to the same type");
8228 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8229 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8231 // From, To sizes and ElemCount must be pow of two
8232 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8234 // We are going to use the original vector elt for storing.
8235 // Accumulated smaller vector elements must be a multiple of the store size.
8236 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8238 unsigned SizeRatio = FromEltSz / ToEltSz;
8239 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8241 // Create a type on which we perform the shuffle.
8242 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8243 NumElems*SizeRatio);
8244 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8247 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8248 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8249 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8251 // Can't shuffle using an illegal type.
8252 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8254 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8255 DAG.getUNDEF(WideVec.getValueType()),
8257 // At this point all of the data is stored at the bottom of the
8258 // register. We now need to save it to mem.
8260 // Find the largest store unit
8261 MVT StoreType = MVT::i8;
8262 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8263 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8264 MVT Tp = (MVT::SimpleValueType)tp;
8265 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8268 // Didn't find a legal store type.
8269 if (!TLI.isTypeLegal(StoreType))
8272 // Bitcast the original vector into a vector of store-size units
8273 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8274 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8275 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8276 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8277 SmallVector<SDValue, 8> Chains;
8278 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8279 TLI.getPointerTy());
8280 SDValue BasePtr = St->getBasePtr();
8282 // Perform one or more big stores into memory.
8283 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8284 for (unsigned I = 0; I < E; I++) {
8285 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8286 StoreType, ShuffWide,
8287 DAG.getIntPtrConstant(I));
8288 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8289 St->getPointerInfo(), St->isVolatile(),
8290 St->isNonTemporal(), St->getAlignment());
8291 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8293 Chains.push_back(Ch);
8295 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8298 if (!ISD::isNormalStore(St))
8301 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8302 // ARM stores of arguments in the same cache line.
8303 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8304 StVal.getNode()->hasOneUse()) {
8305 SelectionDAG &DAG = DCI.DAG;
8307 SDValue BasePtr = St->getBasePtr();
8308 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8309 StVal.getNode()->getOperand(0), BasePtr,
8310 St->getPointerInfo(), St->isVolatile(),
8311 St->isNonTemporal(), St->getAlignment());
8313 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8314 DAG.getConstant(4, MVT::i32));
8315 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
8316 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8317 St->isNonTemporal(),
8318 std::min(4U, St->getAlignment() / 2));
8321 if (StVal.getValueType() != MVT::i64 ||
8322 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8325 // Bitcast an i64 store extracted from a vector to f64.
8326 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8327 SelectionDAG &DAG = DCI.DAG;
8329 SDValue IntVec = StVal.getOperand(0);
8330 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8331 IntVec.getValueType().getVectorNumElements());
8332 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8333 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8334 Vec, StVal.getOperand(1));
8336 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8337 // Make the DAGCombiner fold the bitcasts.
8338 DCI.AddToWorklist(Vec.getNode());
8339 DCI.AddToWorklist(ExtElt.getNode());
8340 DCI.AddToWorklist(V.getNode());
8341 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8342 St->getPointerInfo(), St->isVolatile(),
8343 St->isNonTemporal(), St->getAlignment(),
8347 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8348 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
8349 /// i64 vector to have f64 elements, since the value can then be loaded
8350 /// directly into a VFP register.
8351 static bool hasNormalLoadOperand(SDNode *N) {
8352 unsigned NumElts = N->getValueType(0).getVectorNumElements();
8353 for (unsigned i = 0; i < NumElts; ++i) {
8354 SDNode *Elt = N->getOperand(i).getNode();
8355 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8361 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8362 /// ISD::BUILD_VECTOR.
8363 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8364 TargetLowering::DAGCombinerInfo &DCI){
8365 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8366 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
8367 // into a pair of GPRs, which is fine when the value is used as a scalar,
8368 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8369 SelectionDAG &DAG = DCI.DAG;
8370 if (N->getNumOperands() == 2) {
8371 SDValue RV = PerformVMOVDRRCombine(N, DAG);
8376 // Load i64 elements as f64 values so that type legalization does not split
8377 // them up into i32 values.
8378 EVT VT = N->getValueType(0);
8379 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8382 SmallVector<SDValue, 8> Ops;
8383 unsigned NumElts = VT.getVectorNumElements();
8384 for (unsigned i = 0; i < NumElts; ++i) {
8385 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8387 // Make the DAGCombiner fold the bitcast.
8388 DCI.AddToWorklist(V.getNode());
8390 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8391 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8392 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8395 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8397 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8398 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8399 // At that time, we may have inserted bitcasts from integer to float.
8400 // If these bitcasts have survived DAGCombine, change the lowering of this
8401 // BUILD_VECTOR in something more vector friendly, i.e., that does not
8402 // force to use floating point types.
8404 // Make sure we can change the type of the vector.
8405 // This is possible iff:
8406 // 1. The vector is only used in a bitcast to a integer type. I.e.,
8407 // 1.1. Vector is used only once.
8408 // 1.2. Use is a bit convert to an integer type.
8409 // 2. The size of its operands are 32-bits (64-bits are not legal).
8410 EVT VT = N->getValueType(0);
8411 EVT EltVT = VT.getVectorElementType();
8413 // Check 1.1. and 2.
8414 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8417 // By construction, the input type must be float.
8418 assert(EltVT == MVT::f32 && "Unexpected type!");
8421 SDNode *Use = *N->use_begin();
8422 if (Use->getOpcode() != ISD::BITCAST ||
8423 Use->getValueType(0).isFloatingPoint())
8426 // Check profitability.
8427 // Model is, if more than half of the relevant operands are bitcast from
8428 // i32, turn the build_vector into a sequence of insert_vector_elt.
8429 // Relevant operands are everything that is not statically
8430 // (i.e., at compile time) bitcasted.
8431 unsigned NumOfBitCastedElts = 0;
8432 unsigned NumElts = VT.getVectorNumElements();
8433 unsigned NumOfRelevantElts = NumElts;
8434 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8435 SDValue Elt = N->getOperand(Idx);
8436 if (Elt->getOpcode() == ISD::BITCAST) {
8437 // Assume only bit cast to i32 will go away.
8438 if (Elt->getOperand(0).getValueType() == MVT::i32)
8439 ++NumOfBitCastedElts;
8440 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8441 // Constants are statically casted, thus do not count them as
8442 // relevant operands.
8443 --NumOfRelevantElts;
8446 // Check if more than half of the elements require a non-free bitcast.
8447 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8450 SelectionDAG &DAG = DCI.DAG;
8451 // Create the new vector type.
8452 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8453 // Check if the type is legal.
8454 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8455 if (!TLI.isTypeLegal(VecVT))
8459 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8460 // => BITCAST INSERT_VECTOR_ELT
8461 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8463 SDValue Vec = DAG.getUNDEF(VecVT);
8465 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8466 SDValue V = N->getOperand(Idx);
8467 if (V.getOpcode() == ISD::UNDEF)
8469 if (V.getOpcode() == ISD::BITCAST &&
8470 V->getOperand(0).getValueType() == MVT::i32)
8471 // Fold obvious case.
8472 V = V.getOperand(0);
8474 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8475 // Make the DAGCombiner fold the bitcasts.
8476 DCI.AddToWorklist(V.getNode());
8478 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8479 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8481 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8482 // Make the DAGCombiner fold the bitcasts.
8483 DCI.AddToWorklist(Vec.getNode());
8487 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8488 /// ISD::INSERT_VECTOR_ELT.
8489 static SDValue PerformInsertEltCombine(SDNode *N,
8490 TargetLowering::DAGCombinerInfo &DCI) {
8491 // Bitcast an i64 load inserted into a vector to f64.
8492 // Otherwise, the i64 value will be legalized to a pair of i32 values.
8493 EVT VT = N->getValueType(0);
8494 SDNode *Elt = N->getOperand(1).getNode();
8495 if (VT.getVectorElementType() != MVT::i64 ||
8496 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8499 SelectionDAG &DAG = DCI.DAG;
8501 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8502 VT.getVectorNumElements());
8503 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8504 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8505 // Make the DAGCombiner fold the bitcasts.
8506 DCI.AddToWorklist(Vec.getNode());
8507 DCI.AddToWorklist(V.getNode());
8508 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8509 Vec, V, N->getOperand(2));
8510 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8513 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8514 /// ISD::VECTOR_SHUFFLE.
8515 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8516 // The LLVM shufflevector instruction does not require the shuffle mask
8517 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8518 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
8519 // operands do not match the mask length, they are extended by concatenating
8520 // them with undef vectors. That is probably the right thing for other
8521 // targets, but for NEON it is better to concatenate two double-register
8522 // size vector operands into a single quad-register size vector. Do that
8523 // transformation here:
8524 // shuffle(concat(v1, undef), concat(v2, undef)) ->
8525 // shuffle(concat(v1, v2), undef)
8526 SDValue Op0 = N->getOperand(0);
8527 SDValue Op1 = N->getOperand(1);
8528 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8529 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8530 Op0.getNumOperands() != 2 ||
8531 Op1.getNumOperands() != 2)
8533 SDValue Concat0Op1 = Op0.getOperand(1);
8534 SDValue Concat1Op1 = Op1.getOperand(1);
8535 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8536 Concat1Op1.getOpcode() != ISD::UNDEF)
8538 // Skip the transformation if any of the types are illegal.
8539 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8540 EVT VT = N->getValueType(0);
8541 if (!TLI.isTypeLegal(VT) ||
8542 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8543 !TLI.isTypeLegal(Concat1Op1.getValueType()))
8546 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8547 Op0.getOperand(0), Op1.getOperand(0));
8548 // Translate the shuffle mask.
8549 SmallVector<int, 16> NewMask;
8550 unsigned NumElts = VT.getVectorNumElements();
8551 unsigned HalfElts = NumElts/2;
8552 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8553 for (unsigned n = 0; n < NumElts; ++n) {
8554 int MaskElt = SVN->getMaskElt(n);
8556 if (MaskElt < (int)HalfElts)
8558 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8559 NewElt = HalfElts + MaskElt - NumElts;
8560 NewMask.push_back(NewElt);
8562 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8563 DAG.getUNDEF(VT), NewMask.data());
8566 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8567 /// NEON load/store intrinsics to merge base address updates.
8568 static SDValue CombineBaseUpdate(SDNode *N,
8569 TargetLowering::DAGCombinerInfo &DCI) {
8570 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8573 SelectionDAG &DAG = DCI.DAG;
8574 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8575 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8576 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8577 SDValue Addr = N->getOperand(AddrOpIdx);
8579 // Search for a use of the address operand that is an increment.
8580 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8581 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8583 if (User->getOpcode() != ISD::ADD ||
8584 UI.getUse().getResNo() != Addr.getResNo())
8587 // Check that the add is independent of the load/store. Otherwise, folding
8588 // it would create a cycle.
8589 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8592 // Find the new opcode for the updating load/store.
8594 bool isLaneOp = false;
8595 unsigned NewOpc = 0;
8596 unsigned NumVecs = 0;
8598 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8600 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8601 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
8603 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
8605 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
8607 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
8609 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8610 NumVecs = 2; isLaneOp = true; break;
8611 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8612 NumVecs = 3; isLaneOp = true; break;
8613 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8614 NumVecs = 4; isLaneOp = true; break;
8615 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
8616 NumVecs = 1; isLoad = false; break;
8617 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
8618 NumVecs = 2; isLoad = false; break;
8619 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
8620 NumVecs = 3; isLoad = false; break;
8621 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
8622 NumVecs = 4; isLoad = false; break;
8623 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8624 NumVecs = 2; isLoad = false; isLaneOp = true; break;
8625 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8626 NumVecs = 3; isLoad = false; isLaneOp = true; break;
8627 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8628 NumVecs = 4; isLoad = false; isLaneOp = true; break;
8632 switch (N->getOpcode()) {
8633 default: llvm_unreachable("unexpected opcode for Neon base update");
8634 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8635 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8636 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8640 // Find the size of memory referenced by the load/store.
8643 VecTy = N->getValueType(0);
8645 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8646 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8648 NumBytes /= VecTy.getVectorNumElements();
8650 // If the increment is a constant, it must match the memory ref size.
8651 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8652 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8653 uint64_t IncVal = CInc->getZExtValue();
8654 if (IncVal != NumBytes)
8656 } else if (NumBytes >= 3 * 16) {
8657 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8658 // separate instructions that make it harder to use a non-constant update.
8662 // Create the new updating load/store node.
8664 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8666 for (n = 0; n < NumResultVecs; ++n)
8668 Tys[n++] = MVT::i32;
8669 Tys[n] = MVT::Other;
8670 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8671 SmallVector<SDValue, 8> Ops;
8672 Ops.push_back(N->getOperand(0)); // incoming chain
8673 Ops.push_back(N->getOperand(AddrOpIdx));
8675 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8676 Ops.push_back(N->getOperand(i));
8678 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8679 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8680 Ops, MemInt->getMemoryVT(),
8681 MemInt->getMemOperand());
8684 std::vector<SDValue> NewResults;
8685 for (unsigned i = 0; i < NumResultVecs; ++i) {
8686 NewResults.push_back(SDValue(UpdN.getNode(), i));
8688 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8689 DCI.CombineTo(N, NewResults);
8690 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8697 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8698 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8699 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
8701 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8702 SelectionDAG &DAG = DCI.DAG;
8703 EVT VT = N->getValueType(0);
8704 // vldN-dup instructions only support 64-bit vectors for N > 1.
8705 if (!VT.is64BitVector())
8708 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8709 SDNode *VLD = N->getOperand(0).getNode();
8710 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8712 unsigned NumVecs = 0;
8713 unsigned NewOpc = 0;
8714 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8715 if (IntNo == Intrinsic::arm_neon_vld2lane) {
8717 NewOpc = ARMISD::VLD2DUP;
8718 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8720 NewOpc = ARMISD::VLD3DUP;
8721 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8723 NewOpc = ARMISD::VLD4DUP;
8728 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8729 // numbers match the load.
8730 unsigned VLDLaneNo =
8731 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8732 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8734 // Ignore uses of the chain result.
8735 if (UI.getUse().getResNo() == NumVecs)
8738 if (User->getOpcode() != ARMISD::VDUPLANE ||
8739 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8743 // Create the vldN-dup node.
8746 for (n = 0; n < NumVecs; ++n)
8748 Tys[n] = MVT::Other;
8749 SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8750 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8751 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8752 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8753 Ops, VLDMemInt->getMemoryVT(),
8754 VLDMemInt->getMemOperand());
8757 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8759 unsigned ResNo = UI.getUse().getResNo();
8760 // Ignore uses of the chain result.
8761 if (ResNo == NumVecs)
8764 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8767 // Now the vldN-lane intrinsic is dead except for its chain result.
8768 // Update uses of the chain.
8769 std::vector<SDValue> VLDDupResults;
8770 for (unsigned n = 0; n < NumVecs; ++n)
8771 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8772 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8773 DCI.CombineTo(VLD, VLDDupResults);
8778 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8779 /// ARMISD::VDUPLANE.
8780 static SDValue PerformVDUPLANECombine(SDNode *N,
8781 TargetLowering::DAGCombinerInfo &DCI) {
8782 SDValue Op = N->getOperand(0);
8784 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8785 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8786 if (CombineVLDDUP(N, DCI))
8787 return SDValue(N, 0);
8789 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8790 // redundant. Ignore bit_converts for now; element sizes are checked below.
8791 while (Op.getOpcode() == ISD::BITCAST)
8792 Op = Op.getOperand(0);
8793 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8796 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8797 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8798 // The canonical VMOV for a zero vector uses a 32-bit element size.
8799 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8801 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8803 EVT VT = N->getValueType(0);
8804 if (EltSize > VT.getVectorElementType().getSizeInBits())
8807 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8810 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8811 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8812 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8816 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8818 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8823 APFloat APF = C->getValueAPF();
8824 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8825 != APFloat::opOK || !isExact)
8828 c0 = (I == 0) ? cN : c0;
8829 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8836 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8837 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8838 /// when the VMUL has a constant operand that is a power of 2.
8840 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8841 /// vmul.f32 d16, d17, d16
8842 /// vcvt.s32.f32 d16, d16
8844 /// vcvt.s32.f32 d16, d16, #3
8845 static SDValue PerformVCVTCombine(SDNode *N,
8846 TargetLowering::DAGCombinerInfo &DCI,
8847 const ARMSubtarget *Subtarget) {
8848 SelectionDAG &DAG = DCI.DAG;
8849 SDValue Op = N->getOperand(0);
8851 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8852 Op.getOpcode() != ISD::FMUL)
8856 SDValue N0 = Op->getOperand(0);
8857 SDValue ConstVec = Op->getOperand(1);
8858 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8860 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8861 !isConstVecPow2(ConstVec, isSigned, C))
8864 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8865 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8866 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8867 // These instructions only exist converting from f32 to i32. We can handle
8868 // smaller integers by generating an extra truncate, but larger ones would
8873 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8874 Intrinsic::arm_neon_vcvtfp2fxu;
8875 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8876 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8877 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8878 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8879 DAG.getConstant(Log2_64(C), MVT::i32));
8881 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8882 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8887 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8888 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8889 /// when the VDIV has a constant operand that is a power of 2.
8891 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8892 /// vcvt.f32.s32 d16, d16
8893 /// vdiv.f32 d16, d17, d16
8895 /// vcvt.f32.s32 d16, d16, #3
8896 static SDValue PerformVDIVCombine(SDNode *N,
8897 TargetLowering::DAGCombinerInfo &DCI,
8898 const ARMSubtarget *Subtarget) {
8899 SelectionDAG &DAG = DCI.DAG;
8900 SDValue Op = N->getOperand(0);
8901 unsigned OpOpcode = Op.getNode()->getOpcode();
8903 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8904 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8908 SDValue ConstVec = N->getOperand(1);
8909 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8911 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8912 !isConstVecPow2(ConstVec, isSigned, C))
8915 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8916 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8917 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8918 // These instructions only exist converting from i32 to f32. We can handle
8919 // smaller integers by generating an extra extend, but larger ones would
8924 SDValue ConvInput = Op.getOperand(0);
8925 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8926 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8927 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8928 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8931 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8932 Intrinsic::arm_neon_vcvtfxu2fp;
8933 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8935 DAG.getConstant(IntrinsicOpcode, MVT::i32),
8936 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8939 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8940 /// operand of a vector shift operation, where all the elements of the
8941 /// build_vector must have the same constant integer value.
8942 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8943 // Ignore bit_converts.
8944 while (Op.getOpcode() == ISD::BITCAST)
8945 Op = Op.getOperand(0);
8946 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8947 APInt SplatBits, SplatUndef;
8948 unsigned SplatBitSize;
8950 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8951 HasAnyUndefs, ElementBits) ||
8952 SplatBitSize > ElementBits)
8954 Cnt = SplatBits.getSExtValue();
8958 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8959 /// operand of a vector shift left operation. That value must be in the range:
8960 /// 0 <= Value < ElementBits for a left shift; or
8961 /// 0 <= Value <= ElementBits for a long left shift.
8962 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8963 assert(VT.isVector() && "vector shift count is not a vector type");
8964 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8965 if (! getVShiftImm(Op, ElementBits, Cnt))
8967 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8970 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8971 /// operand of a vector shift right operation. For a shift opcode, the value
8972 /// is positive, but for an intrinsic the value count must be negative. The
8973 /// absolute value must be in the range:
8974 /// 1 <= |Value| <= ElementBits for a right shift; or
8975 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
8976 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
8978 assert(VT.isVector() && "vector shift count is not a vector type");
8979 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8980 if (! getVShiftImm(Op, ElementBits, Cnt))
8984 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
8987 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
8988 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
8989 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8992 // Don't do anything for most intrinsics.
8995 // Vector shifts: check for immediate versions and lower them.
8996 // Note: This is done during DAG combining instead of DAG legalizing because
8997 // the build_vectors for 64-bit vector element shift counts are generally
8998 // not legal, and it is hard to see their values after they get legalized to
8999 // loads from a constant pool.
9000 case Intrinsic::arm_neon_vshifts:
9001 case Intrinsic::arm_neon_vshiftu:
9002 case Intrinsic::arm_neon_vrshifts:
9003 case Intrinsic::arm_neon_vrshiftu:
9004 case Intrinsic::arm_neon_vrshiftn:
9005 case Intrinsic::arm_neon_vqshifts:
9006 case Intrinsic::arm_neon_vqshiftu:
9007 case Intrinsic::arm_neon_vqshiftsu:
9008 case Intrinsic::arm_neon_vqshiftns:
9009 case Intrinsic::arm_neon_vqshiftnu:
9010 case Intrinsic::arm_neon_vqshiftnsu:
9011 case Intrinsic::arm_neon_vqrshiftns:
9012 case Intrinsic::arm_neon_vqrshiftnu:
9013 case Intrinsic::arm_neon_vqrshiftnsu: {
9014 EVT VT = N->getOperand(1).getValueType();
9016 unsigned VShiftOpc = 0;
9019 case Intrinsic::arm_neon_vshifts:
9020 case Intrinsic::arm_neon_vshiftu:
9021 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9022 VShiftOpc = ARMISD::VSHL;
9025 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9026 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9027 ARMISD::VSHRs : ARMISD::VSHRu);
9032 case Intrinsic::arm_neon_vrshifts:
9033 case Intrinsic::arm_neon_vrshiftu:
9034 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9038 case Intrinsic::arm_neon_vqshifts:
9039 case Intrinsic::arm_neon_vqshiftu:
9040 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9044 case Intrinsic::arm_neon_vqshiftsu:
9045 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9047 llvm_unreachable("invalid shift count for vqshlu intrinsic");
9049 case Intrinsic::arm_neon_vrshiftn:
9050 case Intrinsic::arm_neon_vqshiftns:
9051 case Intrinsic::arm_neon_vqshiftnu:
9052 case Intrinsic::arm_neon_vqshiftnsu:
9053 case Intrinsic::arm_neon_vqrshiftns:
9054 case Intrinsic::arm_neon_vqrshiftnu:
9055 case Intrinsic::arm_neon_vqrshiftnsu:
9056 // Narrowing shifts require an immediate right shift.
9057 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9059 llvm_unreachable("invalid shift count for narrowing vector shift "
9063 llvm_unreachable("unhandled vector shift");
9067 case Intrinsic::arm_neon_vshifts:
9068 case Intrinsic::arm_neon_vshiftu:
9069 // Opcode already set above.
9071 case Intrinsic::arm_neon_vrshifts:
9072 VShiftOpc = ARMISD::VRSHRs; break;
9073 case Intrinsic::arm_neon_vrshiftu:
9074 VShiftOpc = ARMISD::VRSHRu; break;
9075 case Intrinsic::arm_neon_vrshiftn:
9076 VShiftOpc = ARMISD::VRSHRN; break;
9077 case Intrinsic::arm_neon_vqshifts:
9078 VShiftOpc = ARMISD::VQSHLs; break;
9079 case Intrinsic::arm_neon_vqshiftu:
9080 VShiftOpc = ARMISD::VQSHLu; break;
9081 case Intrinsic::arm_neon_vqshiftsu:
9082 VShiftOpc = ARMISD::VQSHLsu; break;
9083 case Intrinsic::arm_neon_vqshiftns:
9084 VShiftOpc = ARMISD::VQSHRNs; break;
9085 case Intrinsic::arm_neon_vqshiftnu:
9086 VShiftOpc = ARMISD::VQSHRNu; break;
9087 case Intrinsic::arm_neon_vqshiftnsu:
9088 VShiftOpc = ARMISD::VQSHRNsu; break;
9089 case Intrinsic::arm_neon_vqrshiftns:
9090 VShiftOpc = ARMISD::VQRSHRNs; break;
9091 case Intrinsic::arm_neon_vqrshiftnu:
9092 VShiftOpc = ARMISD::VQRSHRNu; break;
9093 case Intrinsic::arm_neon_vqrshiftnsu:
9094 VShiftOpc = ARMISD::VQRSHRNsu; break;
9097 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9098 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9101 case Intrinsic::arm_neon_vshiftins: {
9102 EVT VT = N->getOperand(1).getValueType();
9104 unsigned VShiftOpc = 0;
9106 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9107 VShiftOpc = ARMISD::VSLI;
9108 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9109 VShiftOpc = ARMISD::VSRI;
9111 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9114 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9115 N->getOperand(1), N->getOperand(2),
9116 DAG.getConstant(Cnt, MVT::i32));
9119 case Intrinsic::arm_neon_vqrshifts:
9120 case Intrinsic::arm_neon_vqrshiftu:
9121 // No immediate versions of these to check for.
9128 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9129 /// lowers them. As with the vector shift intrinsics, this is done during DAG
9130 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9131 /// vector element shift counts are generally not legal, and it is hard to see
9132 /// their values after they get legalized to loads from a constant pool.
9133 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9134 const ARMSubtarget *ST) {
9135 EVT VT = N->getValueType(0);
9136 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9137 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9138 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9139 SDValue N1 = N->getOperand(1);
9140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9141 SDValue N0 = N->getOperand(0);
9142 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9143 DAG.MaskedValueIsZero(N0.getOperand(0),
9144 APInt::getHighBitsSet(32, 16)))
9145 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9149 // Nothing to be done for scalar shifts.
9150 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9151 if (!VT.isVector() || !TLI.isTypeLegal(VT))
9154 assert(ST->hasNEON() && "unexpected vector shift");
9157 switch (N->getOpcode()) {
9158 default: llvm_unreachable("unexpected shift opcode");
9161 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9162 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9163 DAG.getConstant(Cnt, MVT::i32));
9168 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9169 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9170 ARMISD::VSHRs : ARMISD::VSHRu);
9171 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9172 DAG.getConstant(Cnt, MVT::i32));
9178 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9179 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9180 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9181 const ARMSubtarget *ST) {
9182 SDValue N0 = N->getOperand(0);
9184 // Check for sign- and zero-extensions of vector extract operations of 8-
9185 // and 16-bit vector elements. NEON supports these directly. They are
9186 // handled during DAG combining because type legalization will promote them
9187 // to 32-bit types and it is messy to recognize the operations after that.
9188 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9189 SDValue Vec = N0.getOperand(0);
9190 SDValue Lane = N0.getOperand(1);
9191 EVT VT = N->getValueType(0);
9192 EVT EltVT = N0.getValueType();
9193 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9195 if (VT == MVT::i32 &&
9196 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9197 TLI.isTypeLegal(Vec.getValueType()) &&
9198 isa<ConstantSDNode>(Lane)) {
9201 switch (N->getOpcode()) {
9202 default: llvm_unreachable("unexpected opcode");
9203 case ISD::SIGN_EXTEND:
9204 Opc = ARMISD::VGETLANEs;
9206 case ISD::ZERO_EXTEND:
9207 case ISD::ANY_EXTEND:
9208 Opc = ARMISD::VGETLANEu;
9211 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9218 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9219 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9220 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9221 const ARMSubtarget *ST) {
9222 // If the target supports NEON, try to use vmax/vmin instructions for f32
9223 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
9224 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
9225 // a NaN; only do the transformation when it matches that behavior.
9227 // For now only do this when using NEON for FP operations; if using VFP, it
9228 // is not obvious that the benefit outweighs the cost of switching to the
9230 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9231 N->getValueType(0) != MVT::f32)
9234 SDValue CondLHS = N->getOperand(0);
9235 SDValue CondRHS = N->getOperand(1);
9236 SDValue LHS = N->getOperand(2);
9237 SDValue RHS = N->getOperand(3);
9238 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9240 unsigned Opcode = 0;
9242 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9243 IsReversed = false; // x CC y ? x : y
9244 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9245 IsReversed = true ; // x CC y ? y : x
9259 // If LHS is NaN, an ordered comparison will be false and the result will
9260 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
9261 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9262 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9263 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9265 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9266 // will return -0, so vmin can only be used for unsafe math or if one of
9267 // the operands is known to be nonzero.
9268 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9269 !DAG.getTarget().Options.UnsafeFPMath &&
9270 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9272 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9281 // If LHS is NaN, an ordered comparison will be false and the result will
9282 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
9283 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9284 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9285 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9287 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9288 // will return +0, so vmax can only be used for unsafe math or if one of
9289 // the operands is known to be nonzero.
9290 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9291 !DAG.getTarget().Options.UnsafeFPMath &&
9292 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9294 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9300 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9303 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9305 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9306 SDValue Cmp = N->getOperand(4);
9307 if (Cmp.getOpcode() != ARMISD::CMPZ)
9308 // Only looking at EQ and NE cases.
9311 EVT VT = N->getValueType(0);
9313 SDValue LHS = Cmp.getOperand(0);
9314 SDValue RHS = Cmp.getOperand(1);
9315 SDValue FalseVal = N->getOperand(0);
9316 SDValue TrueVal = N->getOperand(1);
9317 SDValue ARMcc = N->getOperand(2);
9318 ARMCC::CondCodes CC =
9319 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9337 /// FIXME: Turn this into a target neutral optimization?
9339 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9340 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9341 N->getOperand(3), Cmp);
9342 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9344 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9345 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9346 N->getOperand(3), NewCmp);
9349 if (Res.getNode()) {
9350 APInt KnownZero, KnownOne;
9351 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9352 // Capture demanded bits information that would be otherwise lost.
9353 if (KnownZero == 0xfffffffe)
9354 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9355 DAG.getValueType(MVT::i1));
9356 else if (KnownZero == 0xffffff00)
9357 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9358 DAG.getValueType(MVT::i8));
9359 else if (KnownZero == 0xffff0000)
9360 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9361 DAG.getValueType(MVT::i16));
9367 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9368 DAGCombinerInfo &DCI) const {
9369 switch (N->getOpcode()) {
9371 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
9372 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
9373 case ISD::SUB: return PerformSUBCombine(N, DCI);
9374 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
9375 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
9376 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
9377 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
9378 case ARMISD::BFI: return PerformBFICombine(N, DCI);
9379 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9380 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9381 case ISD::STORE: return PerformSTORECombine(N, DCI);
9382 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9383 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9384 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9385 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9386 case ISD::FP_TO_SINT:
9387 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9388 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
9389 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9392 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
9393 case ISD::SIGN_EXTEND:
9394 case ISD::ZERO_EXTEND:
9395 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9396 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9397 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9398 case ARMISD::VLD2DUP:
9399 case ARMISD::VLD3DUP:
9400 case ARMISD::VLD4DUP:
9401 return CombineBaseUpdate(N, DCI);
9402 case ARMISD::BUILD_VECTOR:
9403 return PerformARMBUILD_VECTORCombine(N, DCI);
9404 case ISD::INTRINSIC_VOID:
9405 case ISD::INTRINSIC_W_CHAIN:
9406 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9407 case Intrinsic::arm_neon_vld1:
9408 case Intrinsic::arm_neon_vld2:
9409 case Intrinsic::arm_neon_vld3:
9410 case Intrinsic::arm_neon_vld4:
9411 case Intrinsic::arm_neon_vld2lane:
9412 case Intrinsic::arm_neon_vld3lane:
9413 case Intrinsic::arm_neon_vld4lane:
9414 case Intrinsic::arm_neon_vst1:
9415 case Intrinsic::arm_neon_vst2:
9416 case Intrinsic::arm_neon_vst3:
9417 case Intrinsic::arm_neon_vst4:
9418 case Intrinsic::arm_neon_vst2lane:
9419 case Intrinsic::arm_neon_vst3lane:
9420 case Intrinsic::arm_neon_vst4lane:
9421 return CombineBaseUpdate(N, DCI);
9429 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9431 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9434 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9436 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9437 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9439 switch (VT.getSimpleVT().SimpleTy) {
9445 // Unaligned access can use (for example) LRDB, LRDH, LDR
9446 if (AllowsUnaligned) {
9448 *Fast = Subtarget->hasV7Ops();
9455 // For any little-endian targets with neon, we can support unaligned ld/st
9456 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9457 // A big-endian target may also explicitly support unaligned accesses
9458 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9468 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9469 unsigned AlignCheck) {
9470 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9471 (DstAlign == 0 || DstAlign % AlignCheck == 0));
9474 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9475 unsigned DstAlign, unsigned SrcAlign,
9476 bool IsMemset, bool ZeroMemset,
9478 MachineFunction &MF) const {
9479 const Function *F = MF.getFunction();
9481 // See if we can use NEON instructions for this...
9482 if ((!IsMemset || ZeroMemset) &&
9483 Subtarget->hasNEON() &&
9484 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9485 Attribute::NoImplicitFloat)) {
9488 (memOpAlign(SrcAlign, DstAlign, 16) ||
9489 (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9491 } else if (Size >= 8 &&
9492 (memOpAlign(SrcAlign, DstAlign, 8) ||
9493 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9498 // Lowering to i32/i16 if the size permits.
9504 // Let the target-independent logic figure it out.
9508 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9509 if (Val.getOpcode() != ISD::LOAD)
9512 EVT VT1 = Val.getValueType();
9513 if (!VT1.isSimple() || !VT1.isInteger() ||
9514 !VT2.isSimple() || !VT2.isInteger())
9517 switch (VT1.getSimpleVT().SimpleTy) {
9522 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9529 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9530 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9533 if (!isTypeLegal(EVT::getEVT(Ty1)))
9536 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9538 // Assuming the caller doesn't have a zeroext or signext return parameter,
9539 // truncation all the way down to i1 is valid.
9544 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9549 switch (VT.getSimpleVT().SimpleTy) {
9550 default: return false;
9565 if ((V & (Scale - 1)) != 0)
9568 return V == (V & ((1LL << 5) - 1));
9571 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9572 const ARMSubtarget *Subtarget) {
9579 switch (VT.getSimpleVT().SimpleTy) {
9580 default: return false;
9585 // + imm12 or - imm8
9587 return V == (V & ((1LL << 8) - 1));
9588 return V == (V & ((1LL << 12) - 1));
9591 // Same as ARM mode. FIXME: NEON?
9592 if (!Subtarget->hasVFP2())
9597 return V == (V & ((1LL << 8) - 1));
9601 /// isLegalAddressImmediate - Return true if the integer value can be used
9602 /// as the offset of the target addressing mode for load / store of the
9604 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9605 const ARMSubtarget *Subtarget) {
9612 if (Subtarget->isThumb1Only())
9613 return isLegalT1AddressImmediate(V, VT);
9614 else if (Subtarget->isThumb2())
9615 return isLegalT2AddressImmediate(V, VT, Subtarget);
9620 switch (VT.getSimpleVT().SimpleTy) {
9621 default: return false;
9626 return V == (V & ((1LL << 12) - 1));
9629 return V == (V & ((1LL << 8) - 1));
9632 if (!Subtarget->hasVFP2()) // FIXME: NEON?
9637 return V == (V & ((1LL << 8) - 1));
9641 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9643 int Scale = AM.Scale;
9647 switch (VT.getSimpleVT().SimpleTy) {
9648 default: return false;
9657 return Scale == 2 || Scale == 4 || Scale == 8;
9660 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9664 // Note, we allow "void" uses (basically, uses that aren't loads or
9665 // stores), because arm allows folding a scale into many arithmetic
9666 // operations. This should be made more precise and revisited later.
9668 // Allow r << imm, but the imm has to be a multiple of two.
9669 if (Scale & 1) return false;
9670 return isPowerOf2_32(Scale);
9674 /// isLegalAddressingMode - Return true if the addressing mode represented
9675 /// by AM is legal for this target, for a load/store of the specified type.
9676 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9678 EVT VT = getValueType(Ty, true);
9679 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9682 // Can never fold addr of global into load/store.
9687 case 0: // no scale reg, must be "r+i" or "r", or "i".
9690 if (Subtarget->isThumb1Only())
9694 // ARM doesn't support any R+R*scale+imm addr modes.
9701 if (Subtarget->isThumb2())
9702 return isLegalT2ScaledAddressingMode(AM, VT);
9704 int Scale = AM.Scale;
9705 switch (VT.getSimpleVT().SimpleTy) {
9706 default: return false;
9710 if (Scale < 0) Scale = -Scale;
9714 return isPowerOf2_32(Scale & ~1);
9718 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9723 // Note, we allow "void" uses (basically, uses that aren't loads or
9724 // stores), because arm allows folding a scale into many arithmetic
9725 // operations. This should be made more precise and revisited later.
9727 // Allow r << imm, but the imm has to be a multiple of two.
9728 if (Scale & 1) return false;
9729 return isPowerOf2_32(Scale);
9735 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9736 /// icmp immediate, that is the target has icmp instructions which can compare
9737 /// a register against the immediate without having to materialize the
9738 /// immediate into a register.
9739 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9740 // Thumb2 and ARM modes can use cmn for negative immediates.
9741 if (!Subtarget->isThumb())
9742 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9743 if (Subtarget->isThumb2())
9744 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9745 // Thumb1 doesn't have cmn, and only 8-bit immediates.
9746 return Imm >= 0 && Imm <= 255;
9749 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9750 /// *or sub* immediate, that is the target has add or sub instructions which can
9751 /// add a register with the immediate without having to materialize the
9752 /// immediate into a register.
9753 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9754 // Same encoding for add/sub, just flip the sign.
9755 int64_t AbsImm = llvm::abs64(Imm);
9756 if (!Subtarget->isThumb())
9757 return ARM_AM::getSOImmVal(AbsImm) != -1;
9758 if (Subtarget->isThumb2())
9759 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9760 // Thumb1 only has 8-bit unsigned immediate.
9761 return AbsImm >= 0 && AbsImm <= 255;
9764 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9765 bool isSEXTLoad, SDValue &Base,
9766 SDValue &Offset, bool &isInc,
9767 SelectionDAG &DAG) {
9768 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9771 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9773 Base = Ptr->getOperand(0);
9774 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9775 int RHSC = (int)RHS->getZExtValue();
9776 if (RHSC < 0 && RHSC > -256) {
9777 assert(Ptr->getOpcode() == ISD::ADD);
9779 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9783 isInc = (Ptr->getOpcode() == ISD::ADD);
9784 Offset = Ptr->getOperand(1);
9786 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9788 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9789 int RHSC = (int)RHS->getZExtValue();
9790 if (RHSC < 0 && RHSC > -0x1000) {
9791 assert(Ptr->getOpcode() == ISD::ADD);
9793 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9794 Base = Ptr->getOperand(0);
9799 if (Ptr->getOpcode() == ISD::ADD) {
9801 ARM_AM::ShiftOpc ShOpcVal=
9802 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9803 if (ShOpcVal != ARM_AM::no_shift) {
9804 Base = Ptr->getOperand(1);
9805 Offset = Ptr->getOperand(0);
9807 Base = Ptr->getOperand(0);
9808 Offset = Ptr->getOperand(1);
9813 isInc = (Ptr->getOpcode() == ISD::ADD);
9814 Base = Ptr->getOperand(0);
9815 Offset = Ptr->getOperand(1);
9819 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9823 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9824 bool isSEXTLoad, SDValue &Base,
9825 SDValue &Offset, bool &isInc,
9826 SelectionDAG &DAG) {
9827 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9830 Base = Ptr->getOperand(0);
9831 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9832 int RHSC = (int)RHS->getZExtValue();
9833 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9834 assert(Ptr->getOpcode() == ISD::ADD);
9836 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9838 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9839 isInc = Ptr->getOpcode() == ISD::ADD;
9840 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9848 /// getPreIndexedAddressParts - returns true by value, base pointer and
9849 /// offset pointer and addressing mode by reference if the node's address
9850 /// can be legally represented as pre-indexed load / store address.
9852 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9854 ISD::MemIndexedMode &AM,
9855 SelectionDAG &DAG) const {
9856 if (Subtarget->isThumb1Only())
9861 bool isSEXTLoad = false;
9862 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9863 Ptr = LD->getBasePtr();
9864 VT = LD->getMemoryVT();
9865 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9866 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9867 Ptr = ST->getBasePtr();
9868 VT = ST->getMemoryVT();
9873 bool isLegal = false;
9874 if (Subtarget->isThumb2())
9875 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9876 Offset, isInc, DAG);
9878 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9879 Offset, isInc, DAG);
9883 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9887 /// getPostIndexedAddressParts - returns true by value, base pointer and
9888 /// offset pointer and addressing mode by reference if this node can be
9889 /// combined with a load / store to form a post-indexed load / store.
9890 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9893 ISD::MemIndexedMode &AM,
9894 SelectionDAG &DAG) const {
9895 if (Subtarget->isThumb1Only())
9900 bool isSEXTLoad = false;
9901 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9902 VT = LD->getMemoryVT();
9903 Ptr = LD->getBasePtr();
9904 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9905 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9906 VT = ST->getMemoryVT();
9907 Ptr = ST->getBasePtr();
9912 bool isLegal = false;
9913 if (Subtarget->isThumb2())
9914 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9917 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9923 // Swap base ptr and offset to catch more post-index load / store when
9924 // it's legal. In Thumb2 mode, offset must be an immediate.
9925 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9926 !Subtarget->isThumb2())
9927 std::swap(Base, Offset);
9929 // Post-indexed load / store update the base pointer.
9934 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9938 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9941 const SelectionDAG &DAG,
9942 unsigned Depth) const {
9943 unsigned BitWidth = KnownOne.getBitWidth();
9944 KnownZero = KnownOne = APInt(BitWidth, 0);
9945 switch (Op.getOpcode()) {
9951 // These nodes' second result is a boolean
9952 if (Op.getResNo() == 0)
9954 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
9956 case ARMISD::CMOV: {
9957 // Bits are known zero/one if known on the LHS and RHS.
9958 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9959 if (KnownZero == 0 && KnownOne == 0) return;
9961 APInt KnownZeroRHS, KnownOneRHS;
9962 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9963 KnownZero &= KnownZeroRHS;
9964 KnownOne &= KnownOneRHS;
9967 case ISD::INTRINSIC_W_CHAIN: {
9968 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
9969 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
9972 case Intrinsic::arm_ldaex:
9973 case Intrinsic::arm_ldrex: {
9974 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
9975 unsigned MemBits = VT.getScalarType().getSizeInBits();
9976 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
9984 //===----------------------------------------------------------------------===//
9985 // ARM Inline Assembly Support
9986 //===----------------------------------------------------------------------===//
9988 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
9989 // Looking for "rev" which is V6+.
9990 if (!Subtarget->hasV6Ops())
9993 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9994 std::string AsmStr = IA->getAsmString();
9995 SmallVector<StringRef, 4> AsmPieces;
9996 SplitString(AsmStr, AsmPieces, ";\n");
9998 switch (AsmPieces.size()) {
9999 default: return false;
10001 AsmStr = AsmPieces[0];
10003 SplitString(AsmStr, AsmPieces, " \t,");
10006 if (AsmPieces.size() == 3 &&
10007 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10008 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10009 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10010 if (Ty && Ty->getBitWidth() == 32)
10011 return IntrinsicLowering::LowerToByteSwap(CI);
10019 /// getConstraintType - Given a constraint letter, return the type of
10020 /// constraint it is for this target.
10021 ARMTargetLowering::ConstraintType
10022 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10023 if (Constraint.size() == 1) {
10024 switch (Constraint[0]) {
10026 case 'l': return C_RegisterClass;
10027 case 'w': return C_RegisterClass;
10028 case 'h': return C_RegisterClass;
10029 case 'x': return C_RegisterClass;
10030 case 't': return C_RegisterClass;
10031 case 'j': return C_Other; // Constant for movw.
10032 // An address with a single base register. Due to the way we
10033 // currently handle addresses it is the same as an 'r' memory constraint.
10034 case 'Q': return C_Memory;
10036 } else if (Constraint.size() == 2) {
10037 switch (Constraint[0]) {
10039 // All 'U+' constraints are addresses.
10040 case 'U': return C_Memory;
10043 return TargetLowering::getConstraintType(Constraint);
10046 /// Examine constraint type and operand type and determine a weight value.
10047 /// This object must already have been set up with the operand type
10048 /// and the current alternative constraint selected.
10049 TargetLowering::ConstraintWeight
10050 ARMTargetLowering::getSingleConstraintMatchWeight(
10051 AsmOperandInfo &info, const char *constraint) const {
10052 ConstraintWeight weight = CW_Invalid;
10053 Value *CallOperandVal = info.CallOperandVal;
10054 // If we don't have a value, we can't do a match,
10055 // but allow it at the lowest weight.
10056 if (!CallOperandVal)
10058 Type *type = CallOperandVal->getType();
10059 // Look at the constraint type.
10060 switch (*constraint) {
10062 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10065 if (type->isIntegerTy()) {
10066 if (Subtarget->isThumb())
10067 weight = CW_SpecificReg;
10069 weight = CW_Register;
10073 if (type->isFloatingPointTy())
10074 weight = CW_Register;
10080 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10082 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10084 if (Constraint.size() == 1) {
10085 // GCC ARM Constraint Letters
10086 switch (Constraint[0]) {
10087 case 'l': // Low regs or general regs.
10088 if (Subtarget->isThumb())
10089 return RCPair(0U, &ARM::tGPRRegClass);
10090 return RCPair(0U, &ARM::GPRRegClass);
10091 case 'h': // High regs or no regs.
10092 if (Subtarget->isThumb())
10093 return RCPair(0U, &ARM::hGPRRegClass);
10096 return RCPair(0U, &ARM::GPRRegClass);
10098 if (VT == MVT::Other)
10100 if (VT == MVT::f32)
10101 return RCPair(0U, &ARM::SPRRegClass);
10102 if (VT.getSizeInBits() == 64)
10103 return RCPair(0U, &ARM::DPRRegClass);
10104 if (VT.getSizeInBits() == 128)
10105 return RCPair(0U, &ARM::QPRRegClass);
10108 if (VT == MVT::Other)
10110 if (VT == MVT::f32)
10111 return RCPair(0U, &ARM::SPR_8RegClass);
10112 if (VT.getSizeInBits() == 64)
10113 return RCPair(0U, &ARM::DPR_8RegClass);
10114 if (VT.getSizeInBits() == 128)
10115 return RCPair(0U, &ARM::QPR_8RegClass);
10118 if (VT == MVT::f32)
10119 return RCPair(0U, &ARM::SPRRegClass);
10123 if (StringRef("{cc}").equals_lower(Constraint))
10124 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10126 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10129 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10130 /// vector. If it is invalid, don't add anything to Ops.
10131 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10132 std::string &Constraint,
10133 std::vector<SDValue>&Ops,
10134 SelectionDAG &DAG) const {
10137 // Currently only support length 1 constraints.
10138 if (Constraint.length() != 1) return;
10140 char ConstraintLetter = Constraint[0];
10141 switch (ConstraintLetter) {
10144 case 'I': case 'J': case 'K': case 'L':
10145 case 'M': case 'N': case 'O':
10146 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10150 int64_t CVal64 = C->getSExtValue();
10151 int CVal = (int) CVal64;
10152 // None of these constraints allow values larger than 32 bits. Check
10153 // that the value fits in an int.
10154 if (CVal != CVal64)
10157 switch (ConstraintLetter) {
10159 // Constant suitable for movw, must be between 0 and
10161 if (Subtarget->hasV6T2Ops())
10162 if (CVal >= 0 && CVal <= 65535)
10166 if (Subtarget->isThumb1Only()) {
10167 // This must be a constant between 0 and 255, for ADD
10169 if (CVal >= 0 && CVal <= 255)
10171 } else if (Subtarget->isThumb2()) {
10172 // A constant that can be used as an immediate value in a
10173 // data-processing instruction.
10174 if (ARM_AM::getT2SOImmVal(CVal) != -1)
10177 // A constant that can be used as an immediate value in a
10178 // data-processing instruction.
10179 if (ARM_AM::getSOImmVal(CVal) != -1)
10185 if (Subtarget->isThumb()) { // FIXME thumb2
10186 // This must be a constant between -255 and -1, for negated ADD
10187 // immediates. This can be used in GCC with an "n" modifier that
10188 // prints the negated value, for use with SUB instructions. It is
10189 // not useful otherwise but is implemented for compatibility.
10190 if (CVal >= -255 && CVal <= -1)
10193 // This must be a constant between -4095 and 4095. It is not clear
10194 // what this constraint is intended for. Implemented for
10195 // compatibility with GCC.
10196 if (CVal >= -4095 && CVal <= 4095)
10202 if (Subtarget->isThumb1Only()) {
10203 // A 32-bit value where only one byte has a nonzero value. Exclude
10204 // zero to match GCC. This constraint is used by GCC internally for
10205 // constants that can be loaded with a move/shift combination.
10206 // It is not useful otherwise but is implemented for compatibility.
10207 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10209 } else if (Subtarget->isThumb2()) {
10210 // A constant whose bitwise inverse can be used as an immediate
10211 // value in a data-processing instruction. This can be used in GCC
10212 // with a "B" modifier that prints the inverted value, for use with
10213 // BIC and MVN instructions. It is not useful otherwise but is
10214 // implemented for compatibility.
10215 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10218 // A constant whose bitwise inverse can be used as an immediate
10219 // value in a data-processing instruction. This can be used in GCC
10220 // with a "B" modifier that prints the inverted value, for use with
10221 // BIC and MVN instructions. It is not useful otherwise but is
10222 // implemented for compatibility.
10223 if (ARM_AM::getSOImmVal(~CVal) != -1)
10229 if (Subtarget->isThumb1Only()) {
10230 // This must be a constant between -7 and 7,
10231 // for 3-operand ADD/SUB immediate instructions.
10232 if (CVal >= -7 && CVal < 7)
10234 } else if (Subtarget->isThumb2()) {
10235 // A constant whose negation can be used as an immediate value in a
10236 // data-processing instruction. This can be used in GCC with an "n"
10237 // modifier that prints the negated value, for use with SUB
10238 // instructions. It is not useful otherwise but is implemented for
10240 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10243 // A constant whose negation can be used as an immediate value in a
10244 // data-processing instruction. This can be used in GCC with an "n"
10245 // modifier that prints the negated value, for use with SUB
10246 // instructions. It is not useful otherwise but is implemented for
10248 if (ARM_AM::getSOImmVal(-CVal) != -1)
10254 if (Subtarget->isThumb()) { // FIXME thumb2
10255 // This must be a multiple of 4 between 0 and 1020, for
10256 // ADD sp + immediate.
10257 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10260 // A power of two or a constant between 0 and 32. This is used in
10261 // GCC for the shift amount on shifted register operands, but it is
10262 // useful in general for any shift amounts.
10263 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10269 if (Subtarget->isThumb()) { // FIXME thumb2
10270 // This must be a constant between 0 and 31, for shift amounts.
10271 if (CVal >= 0 && CVal <= 31)
10277 if (Subtarget->isThumb()) { // FIXME thumb2
10278 // This must be a multiple of 4 between -508 and 508, for
10279 // ADD/SUB sp = sp + immediate.
10280 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10285 Result = DAG.getTargetConstant(CVal, Op.getValueType());
10289 if (Result.getNode()) {
10290 Ops.push_back(Result);
10293 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10296 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10297 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10298 unsigned Opcode = Op->getOpcode();
10299 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10300 "Invalid opcode for Div/Rem lowering");
10301 bool isSigned = (Opcode == ISD::SDIVREM);
10302 EVT VT = Op->getValueType(0);
10303 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10306 switch (VT.getSimpleVT().SimpleTy) {
10307 default: llvm_unreachable("Unexpected request for libcall!");
10308 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
10309 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10310 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10311 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10314 SDValue InChain = DAG.getEntryNode();
10316 TargetLowering::ArgListTy Args;
10317 TargetLowering::ArgListEntry Entry;
10318 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10319 EVT ArgVT = Op->getOperand(i).getValueType();
10320 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10321 Entry.Node = Op->getOperand(i);
10323 Entry.isSExt = isSigned;
10324 Entry.isZExt = !isSigned;
10325 Args.push_back(Entry);
10328 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10331 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10335 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10336 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10337 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10338 Callee, Args, DAG, dl);
10339 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10341 return CallInfo.first;
10345 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10346 // The ARM target isn't yet aware of offsets.
10350 bool ARM::isBitFieldInvertedMask(unsigned v) {
10351 if (v == 0xffffffff)
10354 // there can be 1's on either or both "outsides", all the "inside"
10355 // bits must be 0's
10356 unsigned TO = CountTrailingOnes_32(v);
10357 unsigned LO = CountLeadingOnes_32(v);
10358 v = (v >> TO) << TO;
10359 v = (v << LO) >> LO;
10363 /// isFPImmLegal - Returns true if the target can instruction select the
10364 /// specified FP immediate natively. If false, the legalizer will
10365 /// materialize the FP immediate as a load from a constant pool.
10366 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10367 if (!Subtarget->hasVFP3())
10369 if (VT == MVT::f32)
10370 return ARM_AM::getFP32Imm(Imm) != -1;
10371 if (VT == MVT::f64)
10372 return ARM_AM::getFP64Imm(Imm) != -1;
10376 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10377 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
10378 /// specified in the intrinsic calls.
10379 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10381 unsigned Intrinsic) const {
10382 switch (Intrinsic) {
10383 case Intrinsic::arm_neon_vld1:
10384 case Intrinsic::arm_neon_vld2:
10385 case Intrinsic::arm_neon_vld3:
10386 case Intrinsic::arm_neon_vld4:
10387 case Intrinsic::arm_neon_vld2lane:
10388 case Intrinsic::arm_neon_vld3lane:
10389 case Intrinsic::arm_neon_vld4lane: {
10390 Info.opc = ISD::INTRINSIC_W_CHAIN;
10391 // Conservatively set memVT to the entire set of vectors loaded.
10392 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10393 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10394 Info.ptrVal = I.getArgOperand(0);
10396 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10397 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10398 Info.vol = false; // volatile loads with NEON intrinsics not supported
10399 Info.readMem = true;
10400 Info.writeMem = false;
10403 case Intrinsic::arm_neon_vst1:
10404 case Intrinsic::arm_neon_vst2:
10405 case Intrinsic::arm_neon_vst3:
10406 case Intrinsic::arm_neon_vst4:
10407 case Intrinsic::arm_neon_vst2lane:
10408 case Intrinsic::arm_neon_vst3lane:
10409 case Intrinsic::arm_neon_vst4lane: {
10410 Info.opc = ISD::INTRINSIC_VOID;
10411 // Conservatively set memVT to the entire set of vectors stored.
10412 unsigned NumElts = 0;
10413 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10414 Type *ArgTy = I.getArgOperand(ArgI)->getType();
10415 if (!ArgTy->isVectorTy())
10417 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10419 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10420 Info.ptrVal = I.getArgOperand(0);
10422 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10423 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10424 Info.vol = false; // volatile stores with NEON intrinsics not supported
10425 Info.readMem = false;
10426 Info.writeMem = true;
10429 case Intrinsic::arm_ldaex:
10430 case Intrinsic::arm_ldrex: {
10431 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10432 Info.opc = ISD::INTRINSIC_W_CHAIN;
10433 Info.memVT = MVT::getVT(PtrTy->getElementType());
10434 Info.ptrVal = I.getArgOperand(0);
10436 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10438 Info.readMem = true;
10439 Info.writeMem = false;
10442 case Intrinsic::arm_stlex:
10443 case Intrinsic::arm_strex: {
10444 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10445 Info.opc = ISD::INTRINSIC_W_CHAIN;
10446 Info.memVT = MVT::getVT(PtrTy->getElementType());
10447 Info.ptrVal = I.getArgOperand(1);
10449 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10451 Info.readMem = false;
10452 Info.writeMem = true;
10455 case Intrinsic::arm_stlexd:
10456 case Intrinsic::arm_strexd: {
10457 Info.opc = ISD::INTRINSIC_W_CHAIN;
10458 Info.memVT = MVT::i64;
10459 Info.ptrVal = I.getArgOperand(2);
10463 Info.readMem = false;
10464 Info.writeMem = true;
10467 case Intrinsic::arm_ldaexd:
10468 case Intrinsic::arm_ldrexd: {
10469 Info.opc = ISD::INTRINSIC_W_CHAIN;
10470 Info.memVT = MVT::i64;
10471 Info.ptrVal = I.getArgOperand(0);
10475 Info.readMem = true;
10476 Info.writeMem = false;
10486 /// \brief Returns true if it is beneficial to convert a load of a constant
10487 /// to just the constant itself.
10488 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10490 assert(Ty->isIntegerTy());
10492 unsigned Bits = Ty->getPrimitiveSizeInBits();
10493 if (Bits == 0 || Bits > 32)
10498 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10499 // Loads and stores less than 64-bits are already atomic; ones above that
10500 // are doomed anyway, so defer to the default libcall and blame the OS when
10501 // things go wrong:
10502 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10503 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10504 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10505 return LI->getType()->getPrimitiveSizeInBits() == 64;
10507 // For the real atomic operations, we have ldrex/strex up to 64 bits.
10508 return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10511 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10512 AtomicOrdering Ord) const {
10513 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10514 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10516 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10518 // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10519 // intrinsic must return {i32, i32} and we have to recombine them into a
10520 // single i64 here.
10521 if (ValTy->getPrimitiveSizeInBits() == 64) {
10522 Intrinsic::ID Int =
10523 IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10524 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10526 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10527 Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10529 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10530 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10531 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10532 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10533 return Builder.CreateOr(
10534 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10537 Type *Tys[] = { Addr->getType() };
10538 Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10539 Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10541 return Builder.CreateTruncOrBitCast(
10542 Builder.CreateCall(Ldrex, Addr),
10543 cast<PointerType>(Addr->getType())->getElementType());
10546 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10548 AtomicOrdering Ord) const {
10549 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10551 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10553 // Since the intrinsics must have legal type, the i64 intrinsics take two
10554 // parameters: "i32, i32". We must marshal Val into the appropriate form
10555 // before the call.
10556 if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10557 Intrinsic::ID Int =
10558 IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10559 Function *Strex = Intrinsic::getDeclaration(M, Int);
10560 Type *Int32Ty = Type::getInt32Ty(M->getContext());
10562 Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10563 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10564 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10565 return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10568 Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10569 Type *Tys[] = { Addr->getType() };
10570 Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10572 return Builder.CreateCall2(
10573 Strex, Builder.CreateZExtOrBitCast(
10574 Val, Strex->getFunctionType()->getParamType(0)),