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 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMSubtarget.h"
23 #include "ARMTargetMachine.h"
24 #include "ARMTargetObjectFile.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/IntrinsicLowering.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalValue.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetOptions.h"
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");
58 // This option should go away when tail calls fully work.
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61 cl::desc("Generate tail calls (TEMPORARY OPTION)."),
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66 cl::desc("Generate calls via indirect call instructions"),
70 ARMInterworking("arm-interworking", cl::Hidden,
71 cl::desc("Enable / disable ARM interworking (for debugging only)"),
75 class ARMCCState : public CCState {
77 ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78 const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
79 LLVMContext &C, ParmContext PC)
80 : CCState(CC, isVarArg, MF, TM, locs, C) {
81 assert(((PC == Call) || (PC == Prologue)) &&
82 "ARMCCState users must specify whether their context is call"
83 "or prologue generation.");
89 // The APCS parameter registers.
90 static const uint16_t GPRArgRegs[] = {
91 ARM::R0, ARM::R1, ARM::R2, ARM::R3
94 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
95 MVT PromotedBitwiseVT) {
96 if (VT != PromotedLdStVT) {
97 setOperationAction(ISD::LOAD, VT, Promote);
98 AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
100 setOperationAction(ISD::STORE, VT, Promote);
101 AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
104 MVT ElemTy = VT.getVectorElementType();
105 if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
106 setOperationAction(ISD::SETCC, VT, Custom);
107 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
108 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
109 if (ElemTy == MVT::i32) {
110 setOperationAction(ISD::SINT_TO_FP, VT, Custom);
111 setOperationAction(ISD::UINT_TO_FP, VT, Custom);
112 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
113 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
115 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
116 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
117 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
118 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
120 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
121 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
122 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
123 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
124 setOperationAction(ISD::SELECT, VT, Expand);
125 setOperationAction(ISD::SELECT_CC, VT, Expand);
126 setOperationAction(ISD::VSELECT, VT, Expand);
127 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
128 if (VT.isInteger()) {
129 setOperationAction(ISD::SHL, VT, Custom);
130 setOperationAction(ISD::SRA, VT, Custom);
131 setOperationAction(ISD::SRL, VT, Custom);
134 // Promote all bit-wise operations.
135 if (VT.isInteger() && VT != PromotedBitwiseVT) {
136 setOperationAction(ISD::AND, VT, Promote);
137 AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
138 setOperationAction(ISD::OR, VT, Promote);
139 AddPromotedToType (ISD::OR, VT, PromotedBitwiseVT);
140 setOperationAction(ISD::XOR, VT, Promote);
141 AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
144 // Neon does not support vector divide/remainder operations.
145 setOperationAction(ISD::SDIV, VT, Expand);
146 setOperationAction(ISD::UDIV, VT, Expand);
147 setOperationAction(ISD::FDIV, VT, Expand);
148 setOperationAction(ISD::SREM, VT, Expand);
149 setOperationAction(ISD::UREM, VT, Expand);
150 setOperationAction(ISD::FREM, VT, Expand);
153 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
154 addRegisterClass(VT, &ARM::DPRRegClass);
155 addTypeForNEON(VT, MVT::f64, MVT::v2i32);
158 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
159 addRegisterClass(VT, &ARM::QPRRegClass);
160 addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
163 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
164 if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
165 return new TargetLoweringObjectFileMachO();
167 return new ARMElfTargetObjectFile();
170 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
171 : TargetLowering(TM, createTLOF(TM)) {
172 Subtarget = &TM.getSubtarget<ARMSubtarget>();
173 RegInfo = TM.getRegisterInfo();
174 Itins = TM.getInstrItineraryData();
176 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
178 if (Subtarget->isTargetIOS()) {
179 // Uses VFP for Thumb libfuncs if available.
180 if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
181 // Single-precision floating-point arithmetic.
182 setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
183 setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
184 setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
185 setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
187 // Double-precision floating-point arithmetic.
188 setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
189 setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
190 setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
191 setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
193 // Single-precision comparisons.
194 setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
195 setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
196 setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
197 setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
198 setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
199 setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
200 setLibcallName(RTLIB::UO_F32, "__unordsf2vfp");
201 setLibcallName(RTLIB::O_F32, "__unordsf2vfp");
203 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
204 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
205 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
206 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
207 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
208 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
209 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
210 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
212 // Double-precision comparisons.
213 setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
214 setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
215 setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
216 setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
217 setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
218 setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
219 setLibcallName(RTLIB::UO_F64, "__unorddf2vfp");
220 setLibcallName(RTLIB::O_F64, "__unorddf2vfp");
222 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
223 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
224 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
225 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
226 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
227 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
228 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
229 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
231 // Floating-point to integer conversions.
232 // i64 conversions are done via library routines even when generating VFP
233 // instructions, so use the same ones.
234 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
235 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
236 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
237 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
239 // Conversions between floating types.
240 setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
241 setLibcallName(RTLIB::FPEXT_F32_F64, "__extendsfdf2vfp");
243 // Integer to floating-point conversions.
244 // i64 conversions are done via library routines even when generating VFP
245 // instructions, so use the same ones.
246 // FIXME: There appears to be some naming inconsistency in ARM libgcc:
247 // e.g., __floatunsidf vs. __floatunssidfvfp.
248 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
249 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
250 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
251 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
255 // These libcalls are not available in 32-bit.
256 setLibcallName(RTLIB::SHL_I128, 0);
257 setLibcallName(RTLIB::SRL_I128, 0);
258 setLibcallName(RTLIB::SRA_I128, 0);
260 if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
261 // Double-precision floating-point arithmetic helper functions
262 // RTABI chapter 4.1.2, Table 2
263 setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
264 setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
265 setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
266 setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
267 setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
268 setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
269 setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
270 setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
272 // Double-precision floating-point comparison helper functions
273 // RTABI chapter 4.1.2, Table 3
274 setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
275 setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
276 setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
277 setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
278 setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
279 setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
280 setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
281 setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
282 setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
283 setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
284 setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
285 setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
286 setLibcallName(RTLIB::UO_F64, "__aeabi_dcmpun");
287 setCmpLibcallCC(RTLIB::UO_F64, ISD::SETNE);
288 setLibcallName(RTLIB::O_F64, "__aeabi_dcmpun");
289 setCmpLibcallCC(RTLIB::O_F64, ISD::SETEQ);
290 setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
291 setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
292 setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
293 setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
294 setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
295 setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
296 setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
297 setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
299 // Single-precision floating-point arithmetic helper functions
300 // RTABI chapter 4.1.2, Table 4
301 setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
302 setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
303 setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
304 setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
305 setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
306 setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
307 setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
308 setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
310 // Single-precision floating-point comparison helper functions
311 // RTABI chapter 4.1.2, Table 5
312 setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
313 setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
314 setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
315 setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
316 setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
317 setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
318 setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
319 setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
320 setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
321 setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
322 setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
323 setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
324 setLibcallName(RTLIB::UO_F32, "__aeabi_fcmpun");
325 setCmpLibcallCC(RTLIB::UO_F32, ISD::SETNE);
326 setLibcallName(RTLIB::O_F32, "__aeabi_fcmpun");
327 setCmpLibcallCC(RTLIB::O_F32, ISD::SETEQ);
328 setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
329 setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
330 setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
331 setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
332 setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
333 setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
334 setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
335 setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
337 // Floating-point to integer conversions.
338 // RTABI chapter 4.1.2, Table 6
339 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
340 setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
341 setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
342 setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
343 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
344 setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
345 setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
346 setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
347 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
348 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
349 setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
350 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
351 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
352 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
353 setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
354 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
356 // Conversions between floating types.
357 // RTABI chapter 4.1.2, Table 7
358 setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
359 setLibcallName(RTLIB::FPEXT_F32_F64, "__aeabi_f2d");
360 setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
361 setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
363 // Integer to floating-point conversions.
364 // RTABI chapter 4.1.2, Table 8
365 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
366 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
367 setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
368 setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
369 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
370 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
371 setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
372 setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
373 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
374 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
375 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
376 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
377 setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
378 setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
379 setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
380 setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
382 // Long long helper functions
383 // RTABI chapter 4.2, Table 9
384 setLibcallName(RTLIB::MUL_I64, "__aeabi_lmul");
385 setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
386 setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
387 setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
388 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
389 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
390 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
391 setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
392 setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
393 setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
395 // Integer division functions
396 // RTABI chapter 4.3.1
397 setLibcallName(RTLIB::SDIV_I8, "__aeabi_idiv");
398 setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
399 setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
400 setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
401 setLibcallName(RTLIB::UDIV_I8, "__aeabi_uidiv");
402 setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
403 setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
404 setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
405 setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
406 setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
407 setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
408 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
409 setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
410 setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
411 setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
412 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
415 // RTABI chapter 4.3.4
416 setLibcallName(RTLIB::MEMCPY, "__aeabi_memcpy");
417 setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
418 setLibcallName(RTLIB::MEMSET, "__aeabi_memset");
419 setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
420 setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
421 setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
424 // Use divmod compiler-rt calls for iOS 5.0 and later.
425 if (Subtarget->getTargetTriple().isiOS() &&
426 !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
427 setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
428 setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
431 if (Subtarget->isThumb1Only())
432 addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
434 addRegisterClass(MVT::i32, &ARM::GPRRegClass);
435 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
436 !Subtarget->isThumb1Only()) {
437 addRegisterClass(MVT::f32, &ARM::SPRRegClass);
438 if (!Subtarget->isFPOnlySP())
439 addRegisterClass(MVT::f64, &ARM::DPRRegClass);
441 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
444 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
445 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
446 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
447 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
448 setTruncStoreAction((MVT::SimpleValueType)VT,
449 (MVT::SimpleValueType)InnerVT, Expand);
450 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
451 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
452 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
455 setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
456 setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458 if (Subtarget->hasNEON()) {
459 addDRTypeForNEON(MVT::v2f32);
460 addDRTypeForNEON(MVT::v8i8);
461 addDRTypeForNEON(MVT::v4i16);
462 addDRTypeForNEON(MVT::v2i32);
463 addDRTypeForNEON(MVT::v1i64);
465 addQRTypeForNEON(MVT::v4f32);
466 addQRTypeForNEON(MVT::v2f64);
467 addQRTypeForNEON(MVT::v16i8);
468 addQRTypeForNEON(MVT::v8i16);
469 addQRTypeForNEON(MVT::v4i32);
470 addQRTypeForNEON(MVT::v2i64);
472 // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
473 // neither Neon nor VFP support any arithmetic operations on it.
474 // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
475 // supported for v4f32.
476 setOperationAction(ISD::FADD, MVT::v2f64, Expand);
477 setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
478 setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
479 // FIXME: Code duplication: FDIV and FREM are expanded always, see
480 // ARMTargetLowering::addTypeForNEON method for details.
481 setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
482 setOperationAction(ISD::FREM, MVT::v2f64, Expand);
483 // FIXME: Create unittest.
484 // In another words, find a way when "copysign" appears in DAG with vector
486 setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
487 // FIXME: Code duplication: SETCC has custom operation action, see
488 // ARMTargetLowering::addTypeForNEON method for details.
489 setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
490 // FIXME: Create unittest for FNEG and for FABS.
491 setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
492 setOperationAction(ISD::FABS, MVT::v2f64, Expand);
493 setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
494 setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
495 setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
496 setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
497 setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
498 setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
499 setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
500 setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
501 setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
502 setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
503 // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
504 setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
505 setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
506 setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
507 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
508 setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
509 setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511 setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512 setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513 setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514 setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515 setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516 setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517 setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518 setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519 setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520 setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
521 setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
522 setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
523 setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
524 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
525 setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527 // Mark v2f32 intrinsics.
528 setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
529 setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
530 setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
531 setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
532 setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
533 setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
534 setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
535 setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
536 setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
537 setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
538 setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
539 setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
540 setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
541 setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
542 setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544 // Neon does not support some operations on v1i64 and v2i64 types.
545 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
546 // Custom handling for some quad-vector types to detect VMULL.
547 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
548 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
549 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
550 // Custom handling for some vector types to avoid expensive expansions
551 setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
552 setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
553 setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
554 setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
555 setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
556 setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
557 // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
558 // a destination type that is wider than the source, and nor does
559 // it have a FP_TO_[SU]INT instruction with a narrower destination than
561 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
562 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
563 setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
564 setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
567 setOperationAction(ISD::FP_EXTEND, MVT::v2f64, Expand);
569 // Custom expand long extensions to vectors.
570 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
571 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
572 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
573 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
574 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
575 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
576 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
577 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
579 // NEON does not have single instruction CTPOP for vectors with element
580 // types wider than 8-bits. However, custom lowering can leverage the
581 // v8i8/v16i8 vcnt instruction.
582 setOperationAction(ISD::CTPOP, MVT::v2i32, Custom);
583 setOperationAction(ISD::CTPOP, MVT::v4i32, Custom);
584 setOperationAction(ISD::CTPOP, MVT::v4i16, Custom);
585 setOperationAction(ISD::CTPOP, MVT::v8i16, Custom);
587 // NEON only has FMA instructions as of VFP4.
588 if (!Subtarget->hasVFP4()) {
589 setOperationAction(ISD::FMA, MVT::v2f32, Expand);
590 setOperationAction(ISD::FMA, MVT::v4f32, Expand);
593 setTargetDAGCombine(ISD::INTRINSIC_VOID);
594 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
595 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
596 setTargetDAGCombine(ISD::SHL);
597 setTargetDAGCombine(ISD::SRL);
598 setTargetDAGCombine(ISD::SRA);
599 setTargetDAGCombine(ISD::SIGN_EXTEND);
600 setTargetDAGCombine(ISD::ZERO_EXTEND);
601 setTargetDAGCombine(ISD::ANY_EXTEND);
602 setTargetDAGCombine(ISD::SELECT_CC);
603 setTargetDAGCombine(ISD::BUILD_VECTOR);
604 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
605 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
606 setTargetDAGCombine(ISD::STORE);
607 setTargetDAGCombine(ISD::FP_TO_SINT);
608 setTargetDAGCombine(ISD::FP_TO_UINT);
609 setTargetDAGCombine(ISD::FDIV);
611 // It is legal to extload from v4i8 to v4i16 or v4i32.
612 MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
613 MVT::v4i16, MVT::v2i16,
615 for (unsigned i = 0; i < 6; ++i) {
616 setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
617 setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
618 setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
622 // ARM and Thumb2 support UMLAL/SMLAL.
623 if (!Subtarget->isThumb1Only())
624 setTargetDAGCombine(ISD::ADDC);
627 computeRegisterProperties();
629 // ARM does not have f32 extending load.
630 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632 // ARM does not have i1 sign extending load.
633 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
635 // ARM supports all 4 flavors of integer indexed load / store.
636 if (!Subtarget->isThumb1Only()) {
637 for (unsigned im = (unsigned)ISD::PRE_INC;
638 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
639 setIndexedLoadAction(im, MVT::i1, Legal);
640 setIndexedLoadAction(im, MVT::i8, Legal);
641 setIndexedLoadAction(im, MVT::i16, Legal);
642 setIndexedLoadAction(im, MVT::i32, Legal);
643 setIndexedStoreAction(im, MVT::i1, Legal);
644 setIndexedStoreAction(im, MVT::i8, Legal);
645 setIndexedStoreAction(im, MVT::i16, Legal);
646 setIndexedStoreAction(im, MVT::i32, Legal);
650 // i64 operation support.
651 setOperationAction(ISD::MUL, MVT::i64, Expand);
652 setOperationAction(ISD::MULHU, MVT::i32, Expand);
653 if (Subtarget->isThumb1Only()) {
654 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
655 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
657 if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
658 || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
659 setOperationAction(ISD::MULHS, MVT::i32, Expand);
661 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
662 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
663 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
664 setOperationAction(ISD::SRL, MVT::i64, Custom);
665 setOperationAction(ISD::SRA, MVT::i64, Custom);
667 if (!Subtarget->isThumb1Only()) {
668 // FIXME: We should do this for Thumb1 as well.
669 setOperationAction(ISD::ADDC, MVT::i32, Custom);
670 setOperationAction(ISD::ADDE, MVT::i32, Custom);
671 setOperationAction(ISD::SUBC, MVT::i32, Custom);
672 setOperationAction(ISD::SUBE, MVT::i32, Custom);
675 // ARM does not have ROTL.
676 setOperationAction(ISD::ROTL, MVT::i32, Expand);
677 setOperationAction(ISD::CTTZ, MVT::i32, Custom);
678 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
679 if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
680 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
682 // These just redirect to CTTZ and CTLZ on ARM.
683 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i32 , Expand);
684 setOperationAction(ISD::CTLZ_ZERO_UNDEF , MVT::i32 , Expand);
686 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
688 // Only ARMv6 has BSWAP.
689 if (!Subtarget->hasV6Ops())
690 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
692 if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
693 !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
694 // These are expanded into libcalls if the cpu doesn't have HW divider.
695 setOperationAction(ISD::SDIV, MVT::i32, Expand);
696 setOperationAction(ISD::UDIV, MVT::i32, Expand);
699 // FIXME: Also set divmod for SREM on EABI
700 setOperationAction(ISD::SREM, MVT::i32, Expand);
701 setOperationAction(ISD::UREM, MVT::i32, Expand);
702 // Register based DivRem for AEABI (RTABI 4.2)
703 if (Subtarget->isTargetAEABI()) {
704 setLibcallName(RTLIB::SDIVREM_I8, "__aeabi_idivmod");
705 setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
706 setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
707 setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
708 setLibcallName(RTLIB::UDIVREM_I8, "__aeabi_uidivmod");
709 setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
710 setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
711 setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
713 setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
714 setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
715 setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
716 setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
717 setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
718 setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
719 setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
720 setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
722 setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
723 setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
725 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
726 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
729 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
730 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
731 setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
732 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
733 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
735 setOperationAction(ISD::TRAP, MVT::Other, Legal);
737 // Use the default implementation.
738 setOperationAction(ISD::VASTART, MVT::Other, Custom);
739 setOperationAction(ISD::VAARG, MVT::Other, Expand);
740 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
741 setOperationAction(ISD::VAEND, MVT::Other, Expand);
742 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
743 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
745 if (!Subtarget->isTargetDarwin()) {
746 // Non-Darwin platforms may return values in these registers via the
747 // personality function.
748 setExceptionPointerRegister(ARM::R0);
749 setExceptionSelectorRegister(ARM::R1);
752 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
753 // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
754 // the default expansion.
755 // FIXME: This should be checking for v6k, not just v6.
756 if (Subtarget->hasDataBarrier() ||
757 (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
758 // membarrier needs custom lowering; the rest are legal and handled
760 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
761 // Custom lowering for 64-bit ops
762 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
763 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
764 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
765 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
766 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
767 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
768 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
769 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
770 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
771 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
772 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
773 // On v8, we have particularly efficient implementations of atomic fences
774 // if they can be combined with nearby atomic loads and stores.
775 if (!Subtarget->hasV8Ops()) {
776 // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
777 setInsertFencesForAtomic(true);
779 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
780 //setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Custom);
782 // Set them all for expansion, which will force libcalls.
783 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
784 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
785 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
786 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
787 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
788 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
789 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
790 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
791 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
792 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
793 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
794 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
795 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
796 // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
797 // Unordered/Monotonic case.
798 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
799 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
802 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
804 // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
805 if (!Subtarget->hasV6Ops()) {
806 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
807 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
809 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
811 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
812 !Subtarget->isThumb1Only()) {
813 // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
814 // iff target supports vfp2.
815 setOperationAction(ISD::BITCAST, MVT::i64, Custom);
816 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
819 // We want to custom lower some of our intrinsics.
820 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
821 if (Subtarget->isTargetDarwin()) {
822 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
823 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
824 setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
827 setOperationAction(ISD::SETCC, MVT::i32, Expand);
828 setOperationAction(ISD::SETCC, MVT::f32, Expand);
829 setOperationAction(ISD::SETCC, MVT::f64, Expand);
830 setOperationAction(ISD::SELECT, MVT::i32, Custom);
831 setOperationAction(ISD::SELECT, MVT::f32, Custom);
832 setOperationAction(ISD::SELECT, MVT::f64, Custom);
833 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
834 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
835 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
837 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
838 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
839 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
840 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
841 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
843 // We don't support sin/cos/fmod/copysign/pow
844 setOperationAction(ISD::FSIN, MVT::f64, Expand);
845 setOperationAction(ISD::FSIN, MVT::f32, Expand);
846 setOperationAction(ISD::FCOS, MVT::f32, Expand);
847 setOperationAction(ISD::FCOS, MVT::f64, Expand);
848 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
849 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
850 setOperationAction(ISD::FREM, MVT::f64, Expand);
851 setOperationAction(ISD::FREM, MVT::f32, Expand);
852 if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
853 !Subtarget->isThumb1Only()) {
854 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
855 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
857 setOperationAction(ISD::FPOW, MVT::f64, Expand);
858 setOperationAction(ISD::FPOW, MVT::f32, Expand);
860 if (!Subtarget->hasVFP4()) {
861 setOperationAction(ISD::FMA, MVT::f64, Expand);
862 setOperationAction(ISD::FMA, MVT::f32, Expand);
865 // Various VFP goodness
866 if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
867 // int <-> fp are custom expanded into bit_convert + ARMISD ops.
868 if (Subtarget->hasVFP2()) {
869 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
870 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
871 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
872 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
874 // Special handling for half-precision FP.
875 if (!Subtarget->hasFP16()) {
876 setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
877 setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
881 // We have target-specific dag combine patterns for the following nodes:
882 // ARMISD::VMOVRRD - No need to call setTargetDAGCombine
883 setTargetDAGCombine(ISD::ADD);
884 setTargetDAGCombine(ISD::SUB);
885 setTargetDAGCombine(ISD::MUL);
886 setTargetDAGCombine(ISD::AND);
887 setTargetDAGCombine(ISD::OR);
888 setTargetDAGCombine(ISD::XOR);
890 if (Subtarget->hasV6Ops())
891 setTargetDAGCombine(ISD::SRL);
893 setStackPointerRegisterToSaveRestore(ARM::SP);
895 if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
896 !Subtarget->hasVFP2())
897 setSchedulingPreference(Sched::RegPressure);
899 setSchedulingPreference(Sched::Hybrid);
901 //// temporary - rewrite interface to use type
902 MaxStoresPerMemset = 8;
903 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
904 MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
905 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
906 MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
907 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
909 // On ARM arguments smaller than 4 bytes are extended, so all arguments
910 // are at least 4 bytes aligned.
911 setMinStackArgumentAlignment(4);
913 // Prefer likely predicted branches to selects on out-of-order cores.
914 PredictableSelectIsExpensive = Subtarget->isLikeA9();
916 setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
919 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
920 bool isThumb2, unsigned &LdrOpc,
922 static const unsigned LoadBares[4][2] = {{ARM::LDREXB, ARM::t2LDREXB},
923 {ARM::LDREXH, ARM::t2LDREXH},
924 {ARM::LDREX, ARM::t2LDREX},
925 {ARM::LDREXD, ARM::t2LDREXD}};
926 static const unsigned LoadAcqs[4][2] = {{ARM::LDAEXB, ARM::t2LDAEXB},
927 {ARM::LDAEXH, ARM::t2LDAEXH},
928 {ARM::LDAEX, ARM::t2LDAEX},
929 {ARM::LDAEXD, ARM::t2LDAEXD}};
930 static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
931 {ARM::STREXH, ARM::t2STREXH},
932 {ARM::STREX, ARM::t2STREX},
933 {ARM::STREXD, ARM::t2STREXD}};
934 static const unsigned StoreRels[4][2] = {{ARM::STLEXB, ARM::t2STLEXB},
935 {ARM::STLEXH, ARM::t2STLEXH},
936 {ARM::STLEX, ARM::t2STLEX},
937 {ARM::STLEXD, ARM::t2STLEXD}};
939 const unsigned (*LoadOps)[2], (*StoreOps)[2];
940 if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
945 if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
946 StoreOps = StoreRels;
948 StoreOps = StoreBares;
950 assert(isPowerOf2_32(Size) && Size <= 8 &&
951 "unsupported size for atomic binary op!");
953 LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
954 StrOpc = StoreOps[Log2_32(Size)][isThumb2];
957 // FIXME: It might make sense to define the representative register class as the
958 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
959 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
960 // SPR's representative would be DPR_VFP2. This should work well if register
961 // pressure tracking were modified such that a register use would increment the
962 // pressure of the register class's representative and all of it's super
963 // classes' representatives transitively. We have not implemented this because
964 // of the difficulty prior to coalescing of modeling operand register classes
965 // due to the common occurrence of cross class copies and subregister insertions
967 std::pair<const TargetRegisterClass*, uint8_t>
968 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
969 const TargetRegisterClass *RRC = 0;
971 switch (VT.SimpleTy) {
973 return TargetLowering::findRepresentativeClass(VT);
974 // Use DPR as representative register class for all floating point
975 // and vector types. Since there are 32 SPR registers and 32 DPR registers so
976 // the cost is 1 for both f32 and f64.
977 case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
978 case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
979 RRC = &ARM::DPRRegClass;
980 // When NEON is used for SP, only half of the register file is available
981 // because operations that define both SP and DP results will be constrained
982 // to the VFP2 class (D0-D15). We currently model this constraint prior to
983 // coalescing by double-counting the SP regs. See the FIXME above.
984 if (Subtarget->useNEONForSinglePrecisionFP())
987 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
988 case MVT::v4f32: case MVT::v2f64:
989 RRC = &ARM::DPRRegClass;
993 RRC = &ARM::DPRRegClass;
997 RRC = &ARM::DPRRegClass;
1001 return std::make_pair(RRC, Cost);
1004 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007 case ARMISD::Wrapper: return "ARMISD::Wrapper";
1008 case ARMISD::WrapperDYN: return "ARMISD::WrapperDYN";
1009 case ARMISD::WrapperPIC: return "ARMISD::WrapperPIC";
1010 case ARMISD::WrapperJT: return "ARMISD::WrapperJT";
1011 case ARMISD::CALL: return "ARMISD::CALL";
1012 case ARMISD::CALL_PRED: return "ARMISD::CALL_PRED";
1013 case ARMISD::CALL_NOLINK: return "ARMISD::CALL_NOLINK";
1014 case ARMISD::tCALL: return "ARMISD::tCALL";
1015 case ARMISD::BRCOND: return "ARMISD::BRCOND";
1016 case ARMISD::BR_JT: return "ARMISD::BR_JT";
1017 case ARMISD::BR2_JT: return "ARMISD::BR2_JT";
1018 case ARMISD::RET_FLAG: return "ARMISD::RET_FLAG";
1019 case ARMISD::INTRET_FLAG: return "ARMISD::INTRET_FLAG";
1020 case ARMISD::PIC_ADD: return "ARMISD::PIC_ADD";
1021 case ARMISD::CMP: return "ARMISD::CMP";
1022 case ARMISD::CMN: return "ARMISD::CMN";
1023 case ARMISD::CMPZ: return "ARMISD::CMPZ";
1024 case ARMISD::CMPFP: return "ARMISD::CMPFP";
1025 case ARMISD::CMPFPw0: return "ARMISD::CMPFPw0";
1026 case ARMISD::BCC_i64: return "ARMISD::BCC_i64";
1027 case ARMISD::FMSTAT: return "ARMISD::FMSTAT";
1029 case ARMISD::CMOV: return "ARMISD::CMOV";
1031 case ARMISD::RBIT: return "ARMISD::RBIT";
1033 case ARMISD::FTOSI: return "ARMISD::FTOSI";
1034 case ARMISD::FTOUI: return "ARMISD::FTOUI";
1035 case ARMISD::SITOF: return "ARMISD::SITOF";
1036 case ARMISD::UITOF: return "ARMISD::UITOF";
1038 case ARMISD::SRL_FLAG: return "ARMISD::SRL_FLAG";
1039 case ARMISD::SRA_FLAG: return "ARMISD::SRA_FLAG";
1040 case ARMISD::RRX: return "ARMISD::RRX";
1042 case ARMISD::ADDC: return "ARMISD::ADDC";
1043 case ARMISD::ADDE: return "ARMISD::ADDE";
1044 case ARMISD::SUBC: return "ARMISD::SUBC";
1045 case ARMISD::SUBE: return "ARMISD::SUBE";
1047 case ARMISD::VMOVRRD: return "ARMISD::VMOVRRD";
1048 case ARMISD::VMOVDRR: return "ARMISD::VMOVDRR";
1050 case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1051 case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053 case ARMISD::TC_RETURN: return "ARMISD::TC_RETURN";
1055 case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057 case ARMISD::DYN_ALLOC: return "ARMISD::DYN_ALLOC";
1059 case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061 case ARMISD::PRELOAD: return "ARMISD::PRELOAD";
1063 case ARMISD::VCEQ: return "ARMISD::VCEQ";
1064 case ARMISD::VCEQZ: return "ARMISD::VCEQZ";
1065 case ARMISD::VCGE: return "ARMISD::VCGE";
1066 case ARMISD::VCGEZ: return "ARMISD::VCGEZ";
1067 case ARMISD::VCLEZ: return "ARMISD::VCLEZ";
1068 case ARMISD::VCGEU: return "ARMISD::VCGEU";
1069 case ARMISD::VCGT: return "ARMISD::VCGT";
1070 case ARMISD::VCGTZ: return "ARMISD::VCGTZ";
1071 case ARMISD::VCLTZ: return "ARMISD::VCLTZ";
1072 case ARMISD::VCGTU: return "ARMISD::VCGTU";
1073 case ARMISD::VTST: return "ARMISD::VTST";
1075 case ARMISD::VSHL: return "ARMISD::VSHL";
1076 case ARMISD::VSHRs: return "ARMISD::VSHRs";
1077 case ARMISD::VSHRu: return "ARMISD::VSHRu";
1078 case ARMISD::VSHLLs: return "ARMISD::VSHLLs";
1079 case ARMISD::VSHLLu: return "ARMISD::VSHLLu";
1080 case ARMISD::VSHLLi: return "ARMISD::VSHLLi";
1081 case ARMISD::VSHRN: return "ARMISD::VSHRN";
1082 case ARMISD::VRSHRs: return "ARMISD::VRSHRs";
1083 case ARMISD::VRSHRu: return "ARMISD::VRSHRu";
1084 case ARMISD::VRSHRN: return "ARMISD::VRSHRN";
1085 case ARMISD::VQSHLs: return "ARMISD::VQSHLs";
1086 case ARMISD::VQSHLu: return "ARMISD::VQSHLu";
1087 case ARMISD::VQSHLsu: return "ARMISD::VQSHLsu";
1088 case ARMISD::VQSHRNs: return "ARMISD::VQSHRNs";
1089 case ARMISD::VQSHRNu: return "ARMISD::VQSHRNu";
1090 case ARMISD::VQSHRNsu: return "ARMISD::VQSHRNsu";
1091 case ARMISD::VQRSHRNs: return "ARMISD::VQRSHRNs";
1092 case ARMISD::VQRSHRNu: return "ARMISD::VQRSHRNu";
1093 case ARMISD::VQRSHRNsu: return "ARMISD::VQRSHRNsu";
1094 case ARMISD::VGETLANEu: return "ARMISD::VGETLANEu";
1095 case ARMISD::VGETLANEs: return "ARMISD::VGETLANEs";
1096 case ARMISD::VMOVIMM: return "ARMISD::VMOVIMM";
1097 case ARMISD::VMVNIMM: return "ARMISD::VMVNIMM";
1098 case ARMISD::VMOVFPIMM: return "ARMISD::VMOVFPIMM";
1099 case ARMISD::VDUP: return "ARMISD::VDUP";
1100 case ARMISD::VDUPLANE: return "ARMISD::VDUPLANE";
1101 case ARMISD::VEXT: return "ARMISD::VEXT";
1102 case ARMISD::VREV64: return "ARMISD::VREV64";
1103 case ARMISD::VREV32: return "ARMISD::VREV32";
1104 case ARMISD::VREV16: return "ARMISD::VREV16";
1105 case ARMISD::VZIP: return "ARMISD::VZIP";
1106 case ARMISD::VUZP: return "ARMISD::VUZP";
1107 case ARMISD::VTRN: return "ARMISD::VTRN";
1108 case ARMISD::VTBL1: return "ARMISD::VTBL1";
1109 case ARMISD::VTBL2: return "ARMISD::VTBL2";
1110 case ARMISD::VMULLs: return "ARMISD::VMULLs";
1111 case ARMISD::VMULLu: return "ARMISD::VMULLu";
1112 case ARMISD::UMLAL: return "ARMISD::UMLAL";
1113 case ARMISD::SMLAL: return "ARMISD::SMLAL";
1114 case ARMISD::BUILD_VECTOR: return "ARMISD::BUILD_VECTOR";
1115 case ARMISD::FMAX: return "ARMISD::FMAX";
1116 case ARMISD::FMIN: return "ARMISD::FMIN";
1117 case ARMISD::VMAXNM: return "ARMISD::VMAX";
1118 case ARMISD::VMINNM: return "ARMISD::VMIN";
1119 case ARMISD::BFI: return "ARMISD::BFI";
1120 case ARMISD::VORRIMM: return "ARMISD::VORRIMM";
1121 case ARMISD::VBICIMM: return "ARMISD::VBICIMM";
1122 case ARMISD::VBSL: return "ARMISD::VBSL";
1123 case ARMISD::VLD2DUP: return "ARMISD::VLD2DUP";
1124 case ARMISD::VLD3DUP: return "ARMISD::VLD3DUP";
1125 case ARMISD::VLD4DUP: return "ARMISD::VLD4DUP";
1126 case ARMISD::VLD1_UPD: return "ARMISD::VLD1_UPD";
1127 case ARMISD::VLD2_UPD: return "ARMISD::VLD2_UPD";
1128 case ARMISD::VLD3_UPD: return "ARMISD::VLD3_UPD";
1129 case ARMISD::VLD4_UPD: return "ARMISD::VLD4_UPD";
1130 case ARMISD::VLD2LN_UPD: return "ARMISD::VLD2LN_UPD";
1131 case ARMISD::VLD3LN_UPD: return "ARMISD::VLD3LN_UPD";
1132 case ARMISD::VLD4LN_UPD: return "ARMISD::VLD4LN_UPD";
1133 case ARMISD::VLD2DUP_UPD: return "ARMISD::VLD2DUP_UPD";
1134 case ARMISD::VLD3DUP_UPD: return "ARMISD::VLD3DUP_UPD";
1135 case ARMISD::VLD4DUP_UPD: return "ARMISD::VLD4DUP_UPD";
1136 case ARMISD::VST1_UPD: return "ARMISD::VST1_UPD";
1137 case ARMISD::VST2_UPD: return "ARMISD::VST2_UPD";
1138 case ARMISD::VST3_UPD: return "ARMISD::VST3_UPD";
1139 case ARMISD::VST4_UPD: return "ARMISD::VST4_UPD";
1140 case ARMISD::VST2LN_UPD: return "ARMISD::VST2LN_UPD";
1141 case ARMISD::VST3LN_UPD: return "ARMISD::VST3LN_UPD";
1142 case ARMISD::VST4LN_UPD: return "ARMISD::VST4LN_UPD";
1146 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1147 if (!VT.isVector()) return getPointerTy();
1148 return VT.changeVectorElementTypeToInteger();
1151 /// getRegClassFor - Return the register class that should be used for the
1152 /// specified value type.
1153 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1154 // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1155 // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1156 // load / store 4 to 8 consecutive D registers.
1157 if (Subtarget->hasNEON()) {
1158 if (VT == MVT::v4i64)
1159 return &ARM::QQPRRegClass;
1160 if (VT == MVT::v8i64)
1161 return &ARM::QQQQPRRegClass;
1163 return TargetLowering::getRegClassFor(VT);
1166 // Create a fast isel object.
1168 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1169 const TargetLibraryInfo *libInfo) const {
1170 return ARM::createFastISel(funcInfo, libInfo);
1173 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1174 /// be used for loads / stores from the global.
1175 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1176 return (Subtarget->isThumb1Only() ? 127 : 4095);
1179 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1180 unsigned NumVals = N->getNumValues();
1182 return Sched::RegPressure;
1184 for (unsigned i = 0; i != NumVals; ++i) {
1185 EVT VT = N->getValueType(i);
1186 if (VT == MVT::Glue || VT == MVT::Other)
1188 if (VT.isFloatingPoint() || VT.isVector())
1192 if (!N->isMachineOpcode())
1193 return Sched::RegPressure;
1195 // Load are scheduled for latency even if there instruction itinerary
1196 // is not available.
1197 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1198 const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1200 if (MCID.getNumDefs() == 0)
1201 return Sched::RegPressure;
1202 if (!Itins->isEmpty() &&
1203 Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1206 return Sched::RegPressure;
1209 //===----------------------------------------------------------------------===//
1211 //===----------------------------------------------------------------------===//
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1216 default: llvm_unreachable("Unknown condition code!");
1217 case ISD::SETNE: return ARMCC::NE;
1218 case ISD::SETEQ: return ARMCC::EQ;
1219 case ISD::SETGT: return ARMCC::GT;
1220 case ISD::SETGE: return ARMCC::GE;
1221 case ISD::SETLT: return ARMCC::LT;
1222 case ISD::SETLE: return ARMCC::LE;
1223 case ISD::SETUGT: return ARMCC::HI;
1224 case ISD::SETUGE: return ARMCC::HS;
1225 case ISD::SETULT: return ARMCC::LO;
1226 case ISD::SETULE: return ARMCC::LS;
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232 ARMCC::CondCodes &CondCode2) {
1233 CondCode2 = ARMCC::AL;
1235 default: llvm_unreachable("Unknown FP condition!");
1237 case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1239 case ISD::SETOGT: CondCode = ARMCC::GT; break;
1241 case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242 case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243 case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244 case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245 case ISD::SETO: CondCode = ARMCC::VC; break;
1246 case ISD::SETUO: CondCode = ARMCC::VS; break;
1247 case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248 case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249 case ISD::SETUGE: CondCode = ARMCC::PL; break;
1251 case ISD::SETULT: CondCode = ARMCC::LT; break;
1253 case ISD::SETULE: CondCode = ARMCC::LE; break;
1255 case ISD::SETUNE: CondCode = ARMCC::NE; break;
1259 //===----------------------------------------------------------------------===//
1260 // Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1263 #include "ARMGenCallingConv.inc"
1265 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1266 /// given CallingConvention value.
1267 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1269 bool isVarArg) const {
1272 llvm_unreachable("Unsupported calling convention");
1273 case CallingConv::Fast:
1274 if (Subtarget->hasVFP2() && !isVarArg) {
1275 if (!Subtarget->isAAPCS_ABI())
1276 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1277 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1278 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1281 case CallingConv::C: {
1282 // Use target triple & subtarget features to do actual dispatch.
1283 if (!Subtarget->isAAPCS_ABI())
1284 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1285 else if (Subtarget->hasVFP2() &&
1286 getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1288 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1289 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1291 case CallingConv::ARM_AAPCS_VFP:
1293 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1295 case CallingConv::ARM_AAPCS:
1296 return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1297 case CallingConv::ARM_APCS:
1298 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1299 case CallingConv::GHC:
1300 return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1304 /// LowerCallResult - Lower the result values of a call into the
1305 /// appropriate copies out of appropriate physical registers.
1307 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1308 CallingConv::ID CallConv, bool isVarArg,
1309 const SmallVectorImpl<ISD::InputArg> &Ins,
1310 SDLoc dl, SelectionDAG &DAG,
1311 SmallVectorImpl<SDValue> &InVals,
1312 bool isThisReturn, SDValue ThisVal) const {
1314 // Assign locations to each value returned by this call.
1315 SmallVector<CCValAssign, 16> RVLocs;
1316 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1317 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1318 CCInfo.AnalyzeCallResult(Ins,
1319 CCAssignFnForNode(CallConv, /* Return*/ true,
1322 // Copy all of the result registers out of their specified physreg.
1323 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1324 CCValAssign VA = RVLocs[i];
1326 // Pass 'this' value directly from the argument to return value, to avoid
1327 // reg unit interference
1328 if (i == 0 && isThisReturn) {
1329 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1330 "unexpected return calling convention register assignment");
1331 InVals.push_back(ThisVal);
1336 if (VA.needsCustom()) {
1337 // Handle f64 or half of a v2f64.
1338 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1340 Chain = Lo.getValue(1);
1341 InFlag = Lo.getValue(2);
1342 VA = RVLocs[++i]; // skip ahead to next loc
1343 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1345 Chain = Hi.getValue(1);
1346 InFlag = Hi.getValue(2);
1347 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1349 if (VA.getLocVT() == MVT::v2f64) {
1350 SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1351 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1352 DAG.getConstant(0, MVT::i32));
1354 VA = RVLocs[++i]; // skip ahead to next loc
1355 Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1356 Chain = Lo.getValue(1);
1357 InFlag = Lo.getValue(2);
1358 VA = RVLocs[++i]; // skip ahead to next loc
1359 Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1360 Chain = Hi.getValue(1);
1361 InFlag = Hi.getValue(2);
1362 Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1363 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1364 DAG.getConstant(1, MVT::i32));
1367 Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1369 Chain = Val.getValue(1);
1370 InFlag = Val.getValue(2);
1373 switch (VA.getLocInfo()) {
1374 default: llvm_unreachable("Unknown loc info!");
1375 case CCValAssign::Full: break;
1376 case CCValAssign::BCvt:
1377 Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1381 InVals.push_back(Val);
1387 /// LowerMemOpCallTo - Store the argument to the stack.
1389 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1390 SDValue StackPtr, SDValue Arg,
1391 SDLoc dl, SelectionDAG &DAG,
1392 const CCValAssign &VA,
1393 ISD::ArgFlagsTy Flags) const {
1394 unsigned LocMemOffset = VA.getLocMemOffset();
1395 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1396 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1397 return DAG.getStore(Chain, dl, Arg, PtrOff,
1398 MachinePointerInfo::getStack(LocMemOffset),
1402 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1403 SDValue Chain, SDValue &Arg,
1404 RegsToPassVector &RegsToPass,
1405 CCValAssign &VA, CCValAssign &NextVA,
1407 SmallVectorImpl<SDValue> &MemOpChains,
1408 ISD::ArgFlagsTy Flags) const {
1410 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1411 DAG.getVTList(MVT::i32, MVT::i32), Arg);
1412 RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1414 if (NextVA.isRegLoc())
1415 RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1417 assert(NextVA.isMemLoc());
1418 if (StackPtr.getNode() == 0)
1419 StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1421 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1427 /// LowerCall - Lowering a call into a callseq_start <-
1428 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1431 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1432 SmallVectorImpl<SDValue> &InVals) const {
1433 SelectionDAG &DAG = CLI.DAG;
1435 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1436 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
1437 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
1438 SDValue Chain = CLI.Chain;
1439 SDValue Callee = CLI.Callee;
1440 bool &isTailCall = CLI.IsTailCall;
1441 CallingConv::ID CallConv = CLI.CallConv;
1442 bool doesNotRet = CLI.DoesNotReturn;
1443 bool isVarArg = CLI.IsVarArg;
1445 MachineFunction &MF = DAG.getMachineFunction();
1446 bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1447 bool isThisReturn = false;
1448 bool isSibCall = false;
1449 // Disable tail calls if they're not supported.
1450 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1453 // Check if it's really possible to do a tail call.
1454 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1455 isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1456 Outs, OutVals, Ins, DAG);
1457 // We don't support GuaranteedTailCallOpt for ARM, only automatically
1458 // detected sibcalls.
1465 // Analyze operands of the call, assigning locations to each operand.
1466 SmallVector<CCValAssign, 16> ArgLocs;
1467 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1468 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1469 CCInfo.AnalyzeCallOperands(Outs,
1470 CCAssignFnForNode(CallConv, /* Return*/ false,
1473 // Get a count of how many bytes are to be pushed on the stack.
1474 unsigned NumBytes = CCInfo.getNextStackOffset();
1476 // For tail calls, memory operands are available in our caller's stack.
1480 // Adjust the stack pointer for the new arguments...
1481 // These operations are automatically eliminated by the prolog/epilog pass
1483 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1486 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1488 RegsToPassVector RegsToPass;
1489 SmallVector<SDValue, 8> MemOpChains;
1491 // Walk the register/memloc assignments, inserting copies/loads. In the case
1492 // of tail call optimization, arguments are handled later.
1493 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1495 ++i, ++realArgIdx) {
1496 CCValAssign &VA = ArgLocs[i];
1497 SDValue Arg = OutVals[realArgIdx];
1498 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1499 bool isByVal = Flags.isByVal();
1501 // Promote the value if needed.
1502 switch (VA.getLocInfo()) {
1503 default: llvm_unreachable("Unknown loc info!");
1504 case CCValAssign::Full: break;
1505 case CCValAssign::SExt:
1506 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1508 case CCValAssign::ZExt:
1509 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1511 case CCValAssign::AExt:
1512 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1514 case CCValAssign::BCvt:
1515 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1519 // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1520 if (VA.needsCustom()) {
1521 if (VA.getLocVT() == MVT::v2f64) {
1522 SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1523 DAG.getConstant(0, MVT::i32));
1524 SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1525 DAG.getConstant(1, MVT::i32));
1527 PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1528 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1530 VA = ArgLocs[++i]; // skip ahead to next loc
1531 if (VA.isRegLoc()) {
1532 PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1533 VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1535 assert(VA.isMemLoc());
1537 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1538 dl, DAG, VA, Flags));
1541 PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1542 StackPtr, MemOpChains, Flags);
1544 } else if (VA.isRegLoc()) {
1545 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1546 assert(VA.getLocVT() == MVT::i32 &&
1547 "unexpected calling convention register assignment");
1548 assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1549 "unexpected use of 'returned'");
1550 isThisReturn = true;
1552 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1553 } else if (isByVal) {
1554 assert(VA.isMemLoc());
1555 unsigned offset = 0;
1557 // True if this byval aggregate will be split between registers
1559 unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1560 unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1562 if (CurByValIdx < ByValArgsCount) {
1564 unsigned RegBegin, RegEnd;
1565 CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1567 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1569 for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1570 SDValue Const = DAG.getConstant(4*i, MVT::i32);
1571 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1572 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1573 MachinePointerInfo(),
1574 false, false, false,
1575 DAG.InferPtrAlignment(AddArg));
1576 MemOpChains.push_back(Load.getValue(1));
1577 RegsToPass.push_back(std::make_pair(j, Load));
1580 // If parameter size outsides register area, "offset" value
1581 // helps us to calculate stack slot for remained part properly.
1582 offset = RegEnd - RegBegin;
1584 CCInfo.nextInRegsParam();
1587 if (Flags.getByValSize() > 4*offset) {
1588 unsigned LocMemOffset = VA.getLocMemOffset();
1589 SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1590 SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1592 SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1593 SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1594 SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1596 SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1598 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1599 SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1600 MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1601 Ops, array_lengthof(Ops)));
1603 } else if (!isSibCall) {
1604 assert(VA.isMemLoc());
1606 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1607 dl, DAG, VA, Flags));
1611 if (!MemOpChains.empty())
1612 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1613 &MemOpChains[0], MemOpChains.size());
1615 // Build a sequence of copy-to-reg nodes chained together with token chain
1616 // and flag operands which copy the outgoing args into the appropriate regs.
1618 // Tail call byval lowering might overwrite argument registers so in case of
1619 // tail call optimization the copies to registers are lowered later.
1621 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1622 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1623 RegsToPass[i].second, InFlag);
1624 InFlag = Chain.getValue(1);
1627 // For tail calls lower the arguments to the 'real' stack slot.
1629 // Force all the incoming stack arguments to be loaded from the stack
1630 // before any new outgoing arguments are stored to the stack, because the
1631 // outgoing stack slots may alias the incoming argument stack slots, and
1632 // the alias isn't otherwise explicit. This is slightly more conservative
1633 // than necessary, because it means that each store effectively depends
1634 // on every argument instead of just those arguments it would clobber.
1636 // Do not flag preceding copytoreg stuff together with the following stuff.
1638 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1639 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1640 RegsToPass[i].second, InFlag);
1641 InFlag = Chain.getValue(1);
1646 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1647 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1648 // node so that legalize doesn't hack it.
1649 bool isDirect = false;
1650 bool isARMFunc = false;
1651 bool isLocalARMFunc = false;
1652 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1654 if (EnableARMLongCalls) {
1655 assert (getTargetMachine().getRelocationModel() == Reloc::Static
1656 && "long-calls with non-static relocation model!");
1657 // Handle a global address or an external symbol. If it's not one of
1658 // those, the target's already in a register, so we don't need to do
1660 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1661 const GlobalValue *GV = G->getGlobal();
1662 // Create a constant pool entry for the callee address
1663 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1664 ARMConstantPoolValue *CPV =
1665 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1667 // Get the address of the callee into a register
1668 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1669 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1670 Callee = DAG.getLoad(getPointerTy(), dl,
1671 DAG.getEntryNode(), CPAddr,
1672 MachinePointerInfo::getConstantPool(),
1673 false, false, false, 0);
1674 } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1675 const char *Sym = S->getSymbol();
1677 // Create a constant pool entry for the callee address
1678 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1679 ARMConstantPoolValue *CPV =
1680 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1681 ARMPCLabelIndex, 0);
1682 // Get the address of the callee into a register
1683 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1684 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1685 Callee = DAG.getLoad(getPointerTy(), dl,
1686 DAG.getEntryNode(), CPAddr,
1687 MachinePointerInfo::getConstantPool(),
1688 false, false, false, 0);
1690 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1691 const GlobalValue *GV = G->getGlobal();
1693 bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1694 bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1695 getTargetMachine().getRelocationModel() != Reloc::Static;
1696 isARMFunc = !Subtarget->isThumb() || isStub;
1697 // ARM call to a local ARM function is predicable.
1698 isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1699 // tBX takes a register source operand.
1700 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1701 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1702 ARMConstantPoolValue *CPV =
1703 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1704 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1705 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1706 Callee = DAG.getLoad(getPointerTy(), dl,
1707 DAG.getEntryNode(), CPAddr,
1708 MachinePointerInfo::getConstantPool(),
1709 false, false, false, 0);
1710 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1711 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1712 getPointerTy(), Callee, PICLabel);
1714 // On ELF targets for PIC code, direct calls should go through the PLT
1715 unsigned OpFlags = 0;
1716 if (Subtarget->isTargetELF() &&
1717 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1718 OpFlags = ARMII::MO_PLT;
1719 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1721 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1723 bool isStub = Subtarget->isTargetDarwin() &&
1724 getTargetMachine().getRelocationModel() != Reloc::Static;
1725 isARMFunc = !Subtarget->isThumb() || isStub;
1726 // tBX takes a register source operand.
1727 const char *Sym = S->getSymbol();
1728 if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1730 ARMConstantPoolValue *CPV =
1731 ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1732 ARMPCLabelIndex, 4);
1733 SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1734 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1735 Callee = DAG.getLoad(getPointerTy(), dl,
1736 DAG.getEntryNode(), CPAddr,
1737 MachinePointerInfo::getConstantPool(),
1738 false, false, false, 0);
1739 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1740 Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1741 getPointerTy(), Callee, PICLabel);
1743 unsigned OpFlags = 0;
1744 // On ELF targets for PIC code, direct calls should go through the PLT
1745 if (Subtarget->isTargetELF() &&
1746 getTargetMachine().getRelocationModel() == Reloc::PIC_)
1747 OpFlags = ARMII::MO_PLT;
1748 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1752 // FIXME: handle tail calls differently.
1754 bool HasMinSizeAttr = MF.getFunction()->getAttributes().
1755 hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
1756 if (Subtarget->isThumb()) {
1757 if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1758 CallOpc = ARMISD::CALL_NOLINK;
1760 CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1762 if (!isDirect && !Subtarget->hasV5TOps())
1763 CallOpc = ARMISD::CALL_NOLINK;
1764 else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1765 // Emit regular call when code size is the priority
1767 // "mov lr, pc; b _foo" to avoid confusing the RSP
1768 CallOpc = ARMISD::CALL_NOLINK;
1770 CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1773 std::vector<SDValue> Ops;
1774 Ops.push_back(Chain);
1775 Ops.push_back(Callee);
1777 // Add argument registers to the end of the list so that they are known live
1779 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1780 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1781 RegsToPass[i].second.getValueType()));
1783 // Add a register mask operand representing the call-preserved registers.
1785 const uint32_t *Mask;
1786 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1787 const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1789 // For 'this' returns, use the R0-preserving mask if applicable
1790 Mask = ARI->getThisReturnPreservedMask(CallConv);
1792 // Set isThisReturn to false if the calling convention is not one that
1793 // allows 'returned' to be modeled in this way, so LowerCallResult does
1794 // not try to pass 'this' straight through
1795 isThisReturn = false;
1796 Mask = ARI->getCallPreservedMask(CallConv);
1799 Mask = ARI->getCallPreservedMask(CallConv);
1801 assert(Mask && "Missing call preserved mask for calling convention");
1802 Ops.push_back(DAG.getRegisterMask(Mask));
1805 if (InFlag.getNode())
1806 Ops.push_back(InFlag);
1808 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1810 return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1812 // Returns a chain and a flag for retval copy to use.
1813 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1814 InFlag = Chain.getValue(1);
1816 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1817 DAG.getIntPtrConstant(0, true), InFlag, dl);
1819 InFlag = Chain.getValue(1);
1821 // Handle result values, copying them out of physregs into vregs that we
1823 return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1824 InVals, isThisReturn,
1825 isThisReturn ? OutVals[0] : SDValue());
1828 /// HandleByVal - Every parameter *after* a byval parameter is passed
1829 /// on the stack. Remember the next parameter register to allocate,
1830 /// and then confiscate the rest of the parameter registers to insure
1833 ARMTargetLowering::HandleByVal(
1834 CCState *State, unsigned &size, unsigned Align) const {
1835 unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1836 assert((State->getCallOrPrologue() == Prologue ||
1837 State->getCallOrPrologue() == Call) &&
1838 "unhandled ParmContext");
1840 // For in-prologue parameters handling, we also introduce stack offset
1841 // for byval registers: see CallingConvLower.cpp, CCState::HandleByVal.
1842 // This behaviour outsides AAPCS rules (5.5 Parameters Passing) of how
1843 // NSAA should be evaluted (NSAA means "next stacked argument address").
1844 // So: NextStackOffset = NSAAOffset + SizeOfByValParamsStoredInRegs.
1845 // Then: NSAAOffset = NextStackOffset - SizeOfByValParamsStoredInRegs.
1846 unsigned NSAAOffset = State->getNextStackOffset();
1847 if (State->getCallOrPrologue() != Call) {
1848 for (unsigned i = 0, e = State->getInRegsParamsCount(); i != e; ++i) {
1850 State->getInRegsParamInfo(i, RB, RE);
1851 assert(NSAAOffset >= (RE-RB)*4 &&
1852 "Stack offset for byval regs doesn't introduced anymore?");
1853 NSAAOffset -= (RE-RB)*4;
1856 if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1857 if (Subtarget->isAAPCS_ABI() && Align > 4) {
1858 unsigned AlignInRegs = Align / 4;
1859 unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1860 for (unsigned i = 0; i < Waste; ++i)
1861 reg = State->AllocateReg(GPRArgRegs, 4);
1864 unsigned excess = 4 * (ARM::R4 - reg);
1866 // Special case when NSAA != SP and parameter size greater than size of
1867 // all remained GPR regs. In that case we can't split parameter, we must
1868 // send it to stack. We also must set NCRN to R4, so waste all
1869 // remained registers.
1870 if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1871 while (State->AllocateReg(GPRArgRegs, 4))
1876 // First register for byval parameter is the first register that wasn't
1877 // allocated before this method call, so it would be "reg".
1878 // If parameter is small enough to be saved in range [reg, r4), then
1879 // the end (first after last) register would be reg + param-size-in-regs,
1880 // else parameter would be splitted between registers and stack,
1881 // end register would be r4 in this case.
1882 unsigned ByValRegBegin = reg;
1883 unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1884 State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1885 // Note, first register is allocated in the beginning of function already,
1886 // allocate remained amount of registers we need.
1887 for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1888 State->AllocateReg(GPRArgRegs, 4);
1889 // At a call site, a byval parameter that is split between
1890 // registers and memory needs its size truncated here. In a
1891 // function prologue, such byval parameters are reassembled in
1892 // memory, and are not truncated.
1893 if (State->getCallOrPrologue() == Call) {
1894 // Make remained size equal to 0 in case, when
1895 // the whole structure may be stored into registers.
1905 /// MatchingStackOffset - Return true if the given stack call argument is
1906 /// already available in the same position (relatively) of the caller's
1907 /// incoming argument stack.
1909 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1910 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1911 const TargetInstrInfo *TII) {
1912 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1914 if (Arg.getOpcode() == ISD::CopyFromReg) {
1915 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1916 if (!TargetRegisterInfo::isVirtualRegister(VR))
1918 MachineInstr *Def = MRI->getVRegDef(VR);
1921 if (!Flags.isByVal()) {
1922 if (!TII->isLoadFromStackSlot(Def, FI))
1927 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1928 if (Flags.isByVal())
1929 // ByVal argument is passed in as a pointer but it's now being
1930 // dereferenced. e.g.
1931 // define @foo(%struct.X* %A) {
1932 // tail call @bar(%struct.X* byval %A)
1935 SDValue Ptr = Ld->getBasePtr();
1936 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1939 FI = FINode->getIndex();
1943 assert(FI != INT_MAX);
1944 if (!MFI->isFixedObjectIndex(FI))
1946 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1949 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1950 /// for tail call optimization. Targets which want to do tail call
1951 /// optimization should implement this function.
1953 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1954 CallingConv::ID CalleeCC,
1956 bool isCalleeStructRet,
1957 bool isCallerStructRet,
1958 const SmallVectorImpl<ISD::OutputArg> &Outs,
1959 const SmallVectorImpl<SDValue> &OutVals,
1960 const SmallVectorImpl<ISD::InputArg> &Ins,
1961 SelectionDAG& DAG) const {
1962 const Function *CallerF = DAG.getMachineFunction().getFunction();
1963 CallingConv::ID CallerCC = CallerF->getCallingConv();
1964 bool CCMatch = CallerCC == CalleeCC;
1966 // Look for obvious safe cases to perform tail call optimization that do not
1967 // require ABI changes. This is what gcc calls sibcall.
1969 // Do not sibcall optimize vararg calls unless the call site is not passing
1971 if (isVarArg && !Outs.empty())
1974 // Exception-handling functions need a special set of instructions to indicate
1975 // a return to the hardware. Tail-calling another function would probably
1977 if (CallerF->hasFnAttribute("interrupt"))
1980 // Also avoid sibcall optimization if either caller or callee uses struct
1981 // return semantics.
1982 if (isCalleeStructRet || isCallerStructRet)
1985 // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1986 // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1987 // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1988 // support in the assembler and linker to be used. This would need to be
1989 // fixed to fully support tail calls in Thumb1.
1991 // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1992 // LR. This means if we need to reload LR, it takes an extra instructions,
1993 // which outweighs the value of the tail call; but here we don't know yet
1994 // whether LR is going to be used. Probably the right approach is to
1995 // generate the tail call here and turn it back into CALL/RET in
1996 // emitEpilogue if LR is used.
1998 // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1999 // but we need to make sure there are enough registers; the only valid
2000 // registers are the 4 used for parameters. We don't currently do this
2002 if (Subtarget->isThumb1Only())
2005 // If the calling conventions do not match, then we'd better make sure the
2006 // results are returned in the same way as what the caller expects.
2008 SmallVector<CCValAssign, 16> RVLocs1;
2009 ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2010 getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
2011 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2013 SmallVector<CCValAssign, 16> RVLocs2;
2014 ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2015 getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
2016 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2018 if (RVLocs1.size() != RVLocs2.size())
2020 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2021 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2023 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2025 if (RVLocs1[i].isRegLoc()) {
2026 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2029 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2035 // If Caller's vararg or byval argument has been split between registers and
2036 // stack, do not perform tail call, since part of the argument is in caller's
2038 const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2039 getInfo<ARMFunctionInfo>();
2040 if (AFI_Caller->getArgRegsSaveSize())
2043 // If the callee takes no arguments then go on to check the results of the
2045 if (!Outs.empty()) {
2046 // Check if stack adjustment is needed. For now, do not do this if any
2047 // argument is passed on the stack.
2048 SmallVector<CCValAssign, 16> ArgLocs;
2049 ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2050 getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2051 CCInfo.AnalyzeCallOperands(Outs,
2052 CCAssignFnForNode(CalleeCC, false, isVarArg));
2053 if (CCInfo.getNextStackOffset()) {
2054 MachineFunction &MF = DAG.getMachineFunction();
2056 // Check if the arguments are already laid out in the right way as
2057 // the caller's fixed stack objects.
2058 MachineFrameInfo *MFI = MF.getFrameInfo();
2059 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2060 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2061 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2063 ++i, ++realArgIdx) {
2064 CCValAssign &VA = ArgLocs[i];
2065 EVT RegVT = VA.getLocVT();
2066 SDValue Arg = OutVals[realArgIdx];
2067 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2068 if (VA.getLocInfo() == CCValAssign::Indirect)
2070 if (VA.needsCustom()) {
2071 // f64 and vector types are split into multiple registers or
2072 // register/stack-slot combinations. The types will not match
2073 // the registers; give up on memory f64 refs until we figure
2074 // out what to do about this.
2077 if (!ArgLocs[++i].isRegLoc())
2079 if (RegVT == MVT::v2f64) {
2080 if (!ArgLocs[++i].isRegLoc())
2082 if (!ArgLocs[++i].isRegLoc())
2085 } else if (!VA.isRegLoc()) {
2086 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2098 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2099 MachineFunction &MF, bool isVarArg,
2100 const SmallVectorImpl<ISD::OutputArg> &Outs,
2101 LLVMContext &Context) const {
2102 SmallVector<CCValAssign, 16> RVLocs;
2103 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2104 return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2108 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2109 SDLoc DL, SelectionDAG &DAG) {
2110 const MachineFunction &MF = DAG.getMachineFunction();
2111 const Function *F = MF.getFunction();
2113 StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2115 // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2116 // version of the "preferred return address". These offsets affect the return
2117 // instruction if this is a return from PL1 without hypervisor extensions.
2118 // IRQ/FIQ: +4 "subs pc, lr, #4"
2119 // SWI: 0 "subs pc, lr, #0"
2120 // ABORT: +4 "subs pc, lr, #4"
2121 // UNDEF: +4/+2 "subs pc, lr, #0"
2122 // UNDEF varies depending on where the exception came from ARM or Thumb
2123 // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2126 if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2129 else if (IntKind == "SWI" || IntKind == "UNDEF")
2132 report_fatal_error("Unsupported interrupt attribute. If present, value "
2133 "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2135 RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2137 return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2138 RetOps.data(), RetOps.size());
2142 ARMTargetLowering::LowerReturn(SDValue Chain,
2143 CallingConv::ID CallConv, bool isVarArg,
2144 const SmallVectorImpl<ISD::OutputArg> &Outs,
2145 const SmallVectorImpl<SDValue> &OutVals,
2146 SDLoc dl, SelectionDAG &DAG) const {
2148 // CCValAssign - represent the assignment of the return value to a location.
2149 SmallVector<CCValAssign, 16> RVLocs;
2151 // CCState - Info about the registers and stack slots.
2152 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2153 getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2155 // Analyze outgoing return values.
2156 CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2160 SmallVector<SDValue, 4> RetOps;
2161 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2163 // Copy the result values into the output registers.
2164 for (unsigned i = 0, realRVLocIdx = 0;
2166 ++i, ++realRVLocIdx) {
2167 CCValAssign &VA = RVLocs[i];
2168 assert(VA.isRegLoc() && "Can only return in registers!");
2170 SDValue Arg = OutVals[realRVLocIdx];
2172 switch (VA.getLocInfo()) {
2173 default: llvm_unreachable("Unknown loc info!");
2174 case CCValAssign::Full: break;
2175 case CCValAssign::BCvt:
2176 Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2180 if (VA.needsCustom()) {
2181 if (VA.getLocVT() == MVT::v2f64) {
2182 // Extract the first half and return it in two registers.
2183 SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2184 DAG.getConstant(0, MVT::i32));
2185 SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2186 DAG.getVTList(MVT::i32, MVT::i32), Half);
2188 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2189 Flag = Chain.getValue(1);
2190 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2191 VA = RVLocs[++i]; // skip ahead to next loc
2192 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2193 HalfGPRs.getValue(1), Flag);
2194 Flag = Chain.getValue(1);
2195 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2196 VA = RVLocs[++i]; // skip ahead to next loc
2198 // Extract the 2nd half and fall through to handle it as an f64 value.
2199 Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2200 DAG.getConstant(1, MVT::i32));
2202 // Legalize ret f64 -> ret 2 x i32. We always have fmrrd if f64 is
2204 SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2205 DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2206 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2207 Flag = Chain.getValue(1);
2208 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2209 VA = RVLocs[++i]; // skip ahead to next loc
2210 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2213 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2215 // Guarantee that all emitted copies are
2216 // stuck together, avoiding something bad.
2217 Flag = Chain.getValue(1);
2218 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2221 // Update chain and glue.
2224 RetOps.push_back(Flag);
2226 // CPUs which aren't M-class use a special sequence to return from
2227 // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2228 // though we use "subs pc, lr, #N").
2230 // M-class CPUs actually use a normal return sequence with a special
2231 // (hardware-provided) value in LR, so the normal code path works.
2232 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2233 !Subtarget->isMClass()) {
2234 if (Subtarget->isThumb1Only())
2235 report_fatal_error("interrupt attribute is not supported in Thumb1");
2236 return LowerInterruptReturn(RetOps, dl, DAG);
2239 return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2240 RetOps.data(), RetOps.size());
2243 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2244 if (N->getNumValues() != 1)
2246 if (!N->hasNUsesOfValue(1, 0))
2249 SDValue TCChain = Chain;
2250 SDNode *Copy = *N->use_begin();
2251 if (Copy->getOpcode() == ISD::CopyToReg) {
2252 // If the copy has a glue operand, we conservatively assume it isn't safe to
2253 // perform a tail call.
2254 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2256 TCChain = Copy->getOperand(0);
2257 } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2258 SDNode *VMov = Copy;
2259 // f64 returned in a pair of GPRs.
2260 SmallPtrSet<SDNode*, 2> Copies;
2261 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2263 if (UI->getOpcode() != ISD::CopyToReg)
2267 if (Copies.size() > 2)
2270 for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2272 SDValue UseChain = UI->getOperand(0);
2273 if (Copies.count(UseChain.getNode()))
2280 } else if (Copy->getOpcode() == ISD::BITCAST) {
2281 // f32 returned in a single GPR.
2282 if (!Copy->hasOneUse())
2284 Copy = *Copy->use_begin();
2285 if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2287 TCChain = Copy->getOperand(0);
2292 bool HasRet = false;
2293 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2295 if (UI->getOpcode() != ARMISD::RET_FLAG &&
2296 UI->getOpcode() != ARMISD::INTRET_FLAG)
2308 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2309 if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
2312 if (!CI->isTailCall())
2315 return !Subtarget->isThumb1Only();
2318 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2319 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2320 // one of the above mentioned nodes. It has to be wrapped because otherwise
2321 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2322 // be used to form addressing mode. These wrapped nodes will be selected
2324 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2325 EVT PtrVT = Op.getValueType();
2326 // FIXME there is no actual debug info here
2328 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2330 if (CP->isMachineConstantPoolEntry())
2331 Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2332 CP->getAlignment());
2334 Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2335 CP->getAlignment());
2336 return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2339 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2340 return MachineJumpTableInfo::EK_Inline;
2343 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2344 SelectionDAG &DAG) const {
2345 MachineFunction &MF = DAG.getMachineFunction();
2346 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2347 unsigned ARMPCLabelIndex = 0;
2349 EVT PtrVT = getPointerTy();
2350 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2351 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2353 if (RelocM == Reloc::Static) {
2354 CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2356 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2357 ARMPCLabelIndex = AFI->createPICLabelUId();
2358 ARMConstantPoolValue *CPV =
2359 ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2360 ARMCP::CPBlockAddress, PCAdj);
2361 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2363 CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2364 SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2365 MachinePointerInfo::getConstantPool(),
2366 false, false, false, 0);
2367 if (RelocM == Reloc::Static)
2369 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2370 return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2373 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2375 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2376 SelectionDAG &DAG) const {
2378 EVT PtrVT = getPointerTy();
2379 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2380 MachineFunction &MF = DAG.getMachineFunction();
2381 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2382 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2383 ARMConstantPoolValue *CPV =
2384 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2385 ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2386 SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2387 Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2388 Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2389 MachinePointerInfo::getConstantPool(),
2390 false, false, false, 0);
2391 SDValue Chain = Argument.getValue(1);
2393 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2394 Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2396 // call __tls_get_addr.
2399 Entry.Node = Argument;
2400 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2401 Args.push_back(Entry);
2402 // FIXME: is there useful debug info available here?
2403 TargetLowering::CallLoweringInfo CLI(Chain,
2404 (Type *) Type::getInt32Ty(*DAG.getContext()),
2405 false, false, false, false,
2406 0, CallingConv::C, /*isTailCall=*/false,
2407 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2408 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2409 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2410 return CallResult.first;
2413 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2414 // "local exec" model.
2416 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2418 TLSModel::Model model) const {
2419 const GlobalValue *GV = GA->getGlobal();
2422 SDValue Chain = DAG.getEntryNode();
2423 EVT PtrVT = getPointerTy();
2424 // Get the Thread Pointer
2425 SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2427 if (model == TLSModel::InitialExec) {
2428 MachineFunction &MF = DAG.getMachineFunction();
2429 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2430 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2431 // Initial exec model.
2432 unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2433 ARMConstantPoolValue *CPV =
2434 ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2435 ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2437 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2438 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2439 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2440 MachinePointerInfo::getConstantPool(),
2441 false, false, false, 0);
2442 Chain = Offset.getValue(1);
2444 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2445 Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2447 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2448 MachinePointerInfo::getConstantPool(),
2449 false, false, false, 0);
2452 assert(model == TLSModel::LocalExec);
2453 ARMConstantPoolValue *CPV =
2454 ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2455 Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2456 Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2457 Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2458 MachinePointerInfo::getConstantPool(),
2459 false, false, false, 0);
2462 // The address of the thread local variable is the add of the thread
2463 // pointer with the offset of the variable.
2464 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2468 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2469 // TODO: implement the "local dynamic" model
2470 assert(Subtarget->isTargetELF() &&
2471 "TLS not implemented for non-ELF targets");
2472 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2474 TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2477 case TLSModel::GeneralDynamic:
2478 case TLSModel::LocalDynamic:
2479 return LowerToTLSGeneralDynamicModel(GA, DAG);
2480 case TLSModel::InitialExec:
2481 case TLSModel::LocalExec:
2482 return LowerToTLSExecModels(GA, DAG, model);
2484 llvm_unreachable("bogus TLS model");
2487 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2488 SelectionDAG &DAG) const {
2489 EVT PtrVT = getPointerTy();
2491 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2492 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2493 bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2494 ARMConstantPoolValue *CPV =
2495 ARMConstantPoolConstant::Create(GV,
2496 UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2497 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2498 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2499 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2501 MachinePointerInfo::getConstantPool(),
2502 false, false, false, 0);
2503 SDValue Chain = Result.getValue(1);
2504 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2505 Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2507 Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2508 MachinePointerInfo::getGOT(),
2509 false, false, false, 0);
2513 // If we have T2 ops, we can materialize the address directly via movt/movw
2514 // pair. This is always cheaper.
2515 if (Subtarget->useMovt()) {
2517 // FIXME: Once remat is capable of dealing with instructions with register
2518 // operands, expand this into two nodes.
2519 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2520 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2522 SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2523 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2524 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2525 MachinePointerInfo::getConstantPool(),
2526 false, false, false, 0);
2530 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2531 SelectionDAG &DAG) const {
2532 EVT PtrVT = getPointerTy();
2534 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2535 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2537 // FIXME: Enable this for static codegen when tool issues are fixed. Also
2538 // update ARMFastISel::ARMMaterializeGV.
2539 if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2541 // FIXME: Once remat is capable of dealing with instructions with register
2542 // operands, expand this into two nodes.
2543 if (RelocM == Reloc::Static)
2544 return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2545 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2547 unsigned Wrapper = (RelocM == Reloc::PIC_)
2548 ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2549 SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2550 DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2551 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2552 Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2553 MachinePointerInfo::getGOT(),
2554 false, false, false, 0);
2558 unsigned ARMPCLabelIndex = 0;
2560 if (RelocM == Reloc::Static) {
2561 CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2563 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2564 ARMPCLabelIndex = AFI->createPICLabelUId();
2565 unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2566 ARMConstantPoolValue *CPV =
2567 ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2569 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2571 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2573 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2574 MachinePointerInfo::getConstantPool(),
2575 false, false, false, 0);
2576 SDValue Chain = Result.getValue(1);
2578 if (RelocM == Reloc::PIC_) {
2579 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2580 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2583 if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2584 Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2585 false, false, false, 0);
2590 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2591 SelectionDAG &DAG) const {
2592 assert(Subtarget->isTargetELF() &&
2593 "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2596 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2597 EVT PtrVT = getPointerTy();
2599 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2600 ARMConstantPoolValue *CPV =
2601 ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2602 ARMPCLabelIndex, PCAdj);
2603 SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2604 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2605 SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2606 MachinePointerInfo::getConstantPool(),
2607 false, false, false, 0);
2608 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2609 return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2613 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2615 SDValue Val = DAG.getConstant(0, MVT::i32);
2616 return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2617 DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2618 Op.getOperand(1), Val);
2622 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2624 return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2625 Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2629 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2630 const ARMSubtarget *Subtarget) const {
2631 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2634 default: return SDValue(); // Don't custom lower most intrinsics.
2635 case Intrinsic::arm_thread_pointer: {
2636 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2637 return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2639 case Intrinsic::eh_sjlj_lsda: {
2640 MachineFunction &MF = DAG.getMachineFunction();
2641 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2642 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2643 EVT PtrVT = getPointerTy();
2644 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2646 unsigned PCAdj = (RelocM != Reloc::PIC_)
2647 ? 0 : (Subtarget->isThumb() ? 4 : 8);
2648 ARMConstantPoolValue *CPV =
2649 ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2650 ARMCP::CPLSDA, PCAdj);
2651 CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2652 CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2654 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2655 MachinePointerInfo::getConstantPool(),
2656 false, false, false, 0);
2658 if (RelocM == Reloc::PIC_) {
2659 SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2660 Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2664 case Intrinsic::arm_neon_vmulls:
2665 case Intrinsic::arm_neon_vmullu: {
2666 unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2667 ? ARMISD::VMULLs : ARMISD::VMULLu;
2668 return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2669 Op.getOperand(1), Op.getOperand(2));
2674 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2675 const ARMSubtarget *Subtarget) {
2676 // FIXME: handle "fence singlethread" more efficiently.
2678 if (!Subtarget->hasDataBarrier()) {
2679 // Some ARMv6 cpus can support data barriers with an mcr instruction.
2680 // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2682 assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2683 "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2684 return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2685 DAG.getConstant(0, MVT::i32));
2688 ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2689 AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2690 unsigned Domain = ARM_MB::ISH;
2691 if (Subtarget->isMClass()) {
2692 // Only a full system barrier exists in the M-class architectures.
2693 Domain = ARM_MB::SY;
2694 } else if (Subtarget->isSwift() && Ord == Release) {
2695 // Swift happens to implement ISHST barriers in a way that's compatible with
2696 // Release semantics but weaker than ISH so we'd be fools not to use
2697 // it. Beware: other processors probably don't!
2698 Domain = ARM_MB::ISHST;
2701 return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2702 DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2703 DAG.getConstant(Domain, MVT::i32));
2706 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2707 const ARMSubtarget *Subtarget) {
2708 // ARM pre v5TE and Thumb1 does not have preload instructions.
2709 if (!(Subtarget->isThumb2() ||
2710 (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2711 // Just preserve the chain.
2712 return Op.getOperand(0);
2715 unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2717 (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2718 // ARMv7 with MP extension has PLDW.
2719 return Op.getOperand(0);
2721 unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2722 if (Subtarget->isThumb()) {
2724 isRead = ~isRead & 1;
2725 isData = ~isData & 1;
2728 return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2729 Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2730 DAG.getConstant(isData, MVT::i32));
2733 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2734 MachineFunction &MF = DAG.getMachineFunction();
2735 ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2737 // vastart just stores the address of the VarArgsFrameIndex slot into the
2738 // memory location argument.
2740 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2741 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2742 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2743 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2744 MachinePointerInfo(SV), false, false, 0);
2748 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2749 SDValue &Root, SelectionDAG &DAG,
2751 MachineFunction &MF = DAG.getMachineFunction();
2752 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2754 const TargetRegisterClass *RC;
2755 if (AFI->isThumb1OnlyFunction())
2756 RC = &ARM::tGPRRegClass;
2758 RC = &ARM::GPRRegClass;
2760 // Transform the arguments stored in physical registers into virtual ones.
2761 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2762 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2765 if (NextVA.isMemLoc()) {
2766 MachineFrameInfo *MFI = MF.getFrameInfo();
2767 int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2769 // Create load node to retrieve arguments from the stack.
2770 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2771 ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2772 MachinePointerInfo::getFixedStack(FI),
2773 false, false, false, 0);
2775 Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2776 ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2779 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2783 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2784 unsigned InRegsParamRecordIdx,
2786 unsigned &ArgRegsSize,
2787 unsigned &ArgRegsSaveSize)
2790 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2791 unsigned RBegin, REnd;
2792 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2793 NumGPRs = REnd - RBegin;
2795 unsigned int firstUnalloced;
2796 firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2797 sizeof(GPRArgRegs) /
2798 sizeof(GPRArgRegs[0]));
2799 NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2802 unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2803 ArgRegsSize = NumGPRs * 4;
2805 // If parameter is split between stack and GPRs...
2806 if (NumGPRs && Align == 8 &&
2807 (ArgRegsSize < ArgSize ||
2808 InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2809 // Add padding for part of param recovered from GPRs, so
2810 // its last byte must be at address K*8 - 1.
2811 // We need to do it, since remained (stack) part of parameter has
2812 // stack alignment, and we need to "attach" "GPRs head" without gaps
2815 // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2816 // [ [padding] [GPRs head] ] [ Tail passed via stack ....
2818 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2820 ((ArgRegsSize + AFI->getArgRegsSaveSize() + Align - 1) & ~(Align-1)) -
2821 (ArgRegsSize + AFI->getArgRegsSaveSize());
2822 ArgRegsSaveSize = ArgRegsSize + Padding;
2824 // We don't need to extend regs save size for byval parameters if they
2825 // are passed via GPRs only.
2826 ArgRegsSaveSize = ArgRegsSize;
2829 // The remaining GPRs hold either the beginning of variable-argument
2830 // data, or the beginning of an aggregate passed by value (usually
2831 // byval). Either way, we allocate stack slots adjacent to the data
2832 // provided by our caller, and store the unallocated registers there.
2833 // If this is a variadic function, the va_list pointer will begin with
2834 // these values; otherwise, this reassembles a (byval) structure that
2835 // was split between registers and memory.
2836 // Return: The frame index registers were stored into.
2838 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2839 SDLoc dl, SDValue &Chain,
2840 const Value *OrigArg,
2841 unsigned InRegsParamRecordIdx,
2842 unsigned OffsetFromOrigArg,
2845 bool ForceMutable) const {
2847 // Currently, two use-cases possible:
2848 // Case #1. Non var-args function, and we meet first byval parameter.
2849 // Setup first unallocated register as first byval register;
2850 // eat all remained registers
2851 // (these two actions are performed by HandleByVal method).
2852 // Then, here, we initialize stack frame with
2853 // "store-reg" instructions.
2854 // Case #2. Var-args function, that doesn't contain byval parameters.
2855 // The same: eat all remained unallocated registers,
2856 // initialize stack frame.
2858 MachineFunction &MF = DAG.getMachineFunction();
2859 MachineFrameInfo *MFI = MF.getFrameInfo();
2860 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2861 unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2862 unsigned RBegin, REnd;
2863 if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2864 CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2865 firstRegToSaveIndex = RBegin - ARM::R0;
2866 lastRegToSaveIndex = REnd - ARM::R0;
2868 firstRegToSaveIndex = CCInfo.getFirstUnallocated
2869 (GPRArgRegs, array_lengthof(GPRArgRegs));
2870 lastRegToSaveIndex = 4;
2873 unsigned ArgRegsSize, ArgRegsSaveSize;
2874 computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2875 ArgRegsSize, ArgRegsSaveSize);
2877 // Store any by-val regs to their spots on the stack so that they may be
2878 // loaded by deferencing the result of formal parameter pointer or va_next.
2879 // Note: once stack area for byval/varargs registers
2880 // was initialized, it can't be initialized again.
2881 if (ArgRegsSaveSize) {
2883 unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2886 assert(AFI->getStoredByValParamsPadding() == 0 &&
2887 "The only parameter may be padded.");
2888 AFI->setStoredByValParamsPadding(Padding);
2891 int FrameIndex = MFI->CreateFixedObject(
2893 Padding + ArgOffset,
2895 SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2897 SmallVector<SDValue, 4> MemOps;
2898 for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2899 ++firstRegToSaveIndex, ++i) {
2900 const TargetRegisterClass *RC;
2901 if (AFI->isThumb1OnlyFunction())
2902 RC = &ARM::tGPRRegClass;
2904 RC = &ARM::GPRRegClass;
2906 unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2907 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2909 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2910 MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2912 MemOps.push_back(Store);
2913 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2914 DAG.getConstant(4, getPointerTy()));
2917 AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2919 if (!MemOps.empty())
2920 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2921 &MemOps[0], MemOps.size());
2924 // This will point to the next argument passed via stack.
2925 return MFI->CreateFixedObject(
2926 4, AFI->getStoredByValParamsPadding() + ArgOffset, !ForceMutable);
2929 // Setup stack frame, the va_list pointer will start from.
2931 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2932 SDLoc dl, SDValue &Chain,
2934 bool ForceMutable) const {
2935 MachineFunction &MF = DAG.getMachineFunction();
2936 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2938 // Try to store any remaining integer argument regs
2939 // to their spots on the stack so that they may be loaded by deferencing
2940 // the result of va_next.
2941 // If there is no regs to be stored, just point address after last
2942 // argument passed via stack.
2944 StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2945 0, ArgOffset, 0, ForceMutable);
2947 AFI->setVarArgsFrameIndex(FrameIndex);
2951 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2952 CallingConv::ID CallConv, bool isVarArg,
2953 const SmallVectorImpl<ISD::InputArg>
2955 SDLoc dl, SelectionDAG &DAG,
2956 SmallVectorImpl<SDValue> &InVals)
2958 MachineFunction &MF = DAG.getMachineFunction();
2959 MachineFrameInfo *MFI = MF.getFrameInfo();
2961 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2963 // Assign locations to all of the incoming arguments.
2964 SmallVector<CCValAssign, 16> ArgLocs;
2965 ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2966 getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2967 CCInfo.AnalyzeFormalArguments(Ins,
2968 CCAssignFnForNode(CallConv, /* Return*/ false,
2971 SmallVector<SDValue, 16> ArgValues;
2972 int lastInsIndex = -1;
2974 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2975 unsigned CurArgIdx = 0;
2977 // Initially ArgRegsSaveSize is zero.
2978 // Then we increase this value each time we meet byval parameter.
2979 // We also increase this value in case of varargs function.
2980 AFI->setArgRegsSaveSize(0);
2982 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2983 CCValAssign &VA = ArgLocs[i];
2984 std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2985 CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2986 // Arguments stored in registers.
2987 if (VA.isRegLoc()) {
2988 EVT RegVT = VA.getLocVT();
2990 if (VA.needsCustom()) {
2991 // f64 and vector types are split up into multiple registers or
2992 // combinations of registers and stack slots.
2993 if (VA.getLocVT() == MVT::v2f64) {
2994 SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2996 VA = ArgLocs[++i]; // skip ahead to next loc
2998 if (VA.isMemLoc()) {
2999 int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3000 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3001 ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3002 MachinePointerInfo::getFixedStack(FI),
3003 false, false, false, 0);
3005 ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3008 ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3009 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3010 ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3011 ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3012 ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3014 ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3017 const TargetRegisterClass *RC;
3019 if (RegVT == MVT::f32)
3020 RC = &ARM::SPRRegClass;
3021 else if (RegVT == MVT::f64)
3022 RC = &ARM::DPRRegClass;
3023 else if (RegVT == MVT::v2f64)
3024 RC = &ARM::QPRRegClass;
3025 else if (RegVT == MVT::i32)
3026 RC = AFI->isThumb1OnlyFunction() ?
3027 (const TargetRegisterClass*)&ARM::tGPRRegClass :
3028 (const TargetRegisterClass*)&ARM::GPRRegClass;
3030 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3032 // Transform the arguments in physical registers into virtual ones.
3033 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3034 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3037 // If this is an 8 or 16-bit value, it is really passed promoted
3038 // to 32 bits. Insert an assert[sz]ext to capture this, then
3039 // truncate to the right size.
3040 switch (VA.getLocInfo()) {
3041 default: llvm_unreachable("Unknown loc info!");
3042 case CCValAssign::Full: break;
3043 case CCValAssign::BCvt:
3044 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3046 case CCValAssign::SExt:
3047 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3048 DAG.getValueType(VA.getValVT()));
3049 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3051 case CCValAssign::ZExt:
3052 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3053 DAG.getValueType(VA.getValVT()));
3054 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3058 InVals.push_back(ArgValue);
3060 } else { // VA.isRegLoc()
3063 assert(VA.isMemLoc());
3064 assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3066 int index = ArgLocs[i].getValNo();
3068 // Some Ins[] entries become multiple ArgLoc[] entries.
3069 // Process them only once.
3070 if (index != lastInsIndex)
3072 ISD::ArgFlagsTy Flags = Ins[index].Flags;
3073 // FIXME: For now, all byval parameter objects are marked mutable.
3074 // This can be changed with more analysis.
3075 // In case of tail call optimization mark all arguments mutable.
3076 // Since they could be overwritten by lowering of arguments in case of
3078 if (Flags.isByVal()) {
3079 unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3080 int FrameIndex = StoreByValRegs(
3081 CCInfo, DAG, dl, Chain, CurOrigArg,
3083 Ins[VA.getValNo()].PartOffset,
3084 VA.getLocMemOffset(),
3085 Flags.getByValSize(),
3086 true /*force mutable frames*/);
3087 InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3088 CCInfo.nextInRegsParam();
3090 unsigned FIOffset = VA.getLocMemOffset() +
3091 AFI->getStoredByValParamsPadding();
3092 int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3095 // Create load nodes to retrieve arguments from the stack.
3096 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3097 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3098 MachinePointerInfo::getFixedStack(FI),
3099 false, false, false, 0));
3101 lastInsIndex = index;
3108 VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3109 CCInfo.getNextStackOffset());
3114 /// isFloatingPointZero - Return true if this is +0.0.
3115 static bool isFloatingPointZero(SDValue Op) {
3116 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3117 return CFP->getValueAPF().isPosZero();
3118 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3119 // Maybe this has already been legalized into the constant pool?
3120 if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3121 SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3122 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3123 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3124 return CFP->getValueAPF().isPosZero();
3130 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3131 /// the given operands.
3133 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3134 SDValue &ARMcc, SelectionDAG &DAG,
3136 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3137 unsigned C = RHSC->getZExtValue();
3138 if (!isLegalICmpImmediate(C)) {
3139 // Constant does not fit, try adjusting it by one?
3144 if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3145 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3146 RHS = DAG.getConstant(C-1, MVT::i32);
3151 if (C != 0 && isLegalICmpImmediate(C-1)) {
3152 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3153 RHS = DAG.getConstant(C-1, MVT::i32);
3158 if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3159 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3160 RHS = DAG.getConstant(C+1, MVT::i32);
3165 if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3166 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3167 RHS = DAG.getConstant(C+1, MVT::i32);
3174 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3175 ARMISD::NodeType CompareType;
3178 CompareType = ARMISD::CMP;
3183 CompareType = ARMISD::CMPZ;
3186 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3187 return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3190 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3192 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3195 if (!isFloatingPointZero(RHS))
3196 Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3198 Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3199 return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3202 /// duplicateCmp - Glue values can have only one use, so this function
3203 /// duplicates a comparison node.
3205 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3206 unsigned Opc = Cmp.getOpcode();
3208 if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3209 return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3211 assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3212 Cmp = Cmp.getOperand(0);
3213 Opc = Cmp.getOpcode();
3214 if (Opc == ARMISD::CMPFP)
3215 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3217 assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3218 Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3220 return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3223 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3224 SDValue Cond = Op.getOperand(0);
3225 SDValue SelectTrue = Op.getOperand(1);
3226 SDValue SelectFalse = Op.getOperand(2);
3231 // (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3232 // (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3234 if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3235 const ConstantSDNode *CMOVTrue =
3236 dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3237 const ConstantSDNode *CMOVFalse =
3238 dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3240 if (CMOVTrue && CMOVFalse) {
3241 unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3242 unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3246 if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3248 False = SelectFalse;
3249 } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3254 if (True.getNode() && False.getNode()) {
3255 EVT VT = Op.getValueType();
3256 SDValue ARMcc = Cond.getOperand(2);
3257 SDValue CCR = Cond.getOperand(3);
3258 SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3259 assert(True.getValueType() == VT);
3260 return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3265 // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3266 // undefined bits before doing a full-word comparison with zero.
3267 Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3268 DAG.getConstant(1, Cond.getValueType()));
3270 return DAG.getSelectCC(dl, Cond,
3271 DAG.getConstant(0, Cond.getValueType()),
3272 SelectTrue, SelectFalse, ISD::SETNE);
3275 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3276 if (CC == ISD::SETNE)
3278 return ISD::getSetCCSwappedOperands(CC);
3281 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3282 bool &swpCmpOps, bool &swpVselOps) {
3283 // Start by selecting the GE condition code for opcodes that return true for
3285 if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3287 CondCode = ARMCC::GE;
3289 // and GT for opcodes that return false for 'equality'.
3290 else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3292 CondCode = ARMCC::GT;
3294 // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3295 // to swap the compare operands.
3296 if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3300 // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3301 // If we have an unordered opcode, we need to swap the operands to the VSEL
3302 // instruction (effectively negating the condition).
3304 // This also has the effect of swapping which one of 'less' or 'greater'
3305 // returns true, so we also swap the compare operands. It also switches
3306 // whether we return true for 'equality', so we compensate by picking the
3307 // opposite condition code to our original choice.
3308 if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3309 CC == ISD::SETUGT) {
3310 swpCmpOps = !swpCmpOps;
3311 swpVselOps = !swpVselOps;
3312 CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3315 // 'ordered' is 'anything but unordered', so use the VS condition code and
3316 // swap the VSEL operands.
3317 if (CC == ISD::SETO) {
3318 CondCode = ARMCC::VS;
3322 // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3323 // code and swap the VSEL operands.
3324 if (CC == ISD::SETUNE) {
3325 CondCode = ARMCC::EQ;
3330 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3331 EVT VT = Op.getValueType();
3332 SDValue LHS = Op.getOperand(0);
3333 SDValue RHS = Op.getOperand(1);
3334 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3335 SDValue TrueVal = Op.getOperand(2);
3336 SDValue FalseVal = Op.getOperand(3);
3339 if (LHS.getValueType() == MVT::i32) {
3340 // Try to generate VSEL on ARMv8.
3341 // The VSEL instruction can't use all the usual ARM condition
3342 // codes: it only has two bits to select the condition code, so it's
3343 // constrained to use only GE, GT, VS and EQ.
3345 // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3346 // swap the operands of the previous compare instruction (effectively
3347 // inverting the compare condition, swapping 'less' and 'greater') and
3348 // sometimes need to swap the operands to the VSEL (which inverts the
3349 // condition in the sense of firing whenever the previous condition didn't)
3350 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3351 TrueVal.getValueType() == MVT::f64)) {
3352 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3353 if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3354 CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3355 CC = getInverseCCForVSEL(CC);
3356 std::swap(TrueVal, FalseVal);
3361 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3362 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3363 return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3367 ARMCC::CondCodes CondCode, CondCode2;
3368 FPCCToARMCC(CC, CondCode, CondCode2);
3370 // Try to generate VSEL on ARMv8.
3371 if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3372 TrueVal.getValueType() == MVT::f64)) {
3373 // We can select VMAXNM/VMINNM from a compare followed by a select with the
3374 // same operands, as follows:
3375 // c = fcmp [ogt, olt, ugt, ult] a, b
3377 // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3378 // handled differently than the original code sequence.
3379 if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3381 if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3382 return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3383 if (CC == ISD::SETOLT || CC == ISD::SETULT)
3384 return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3387 bool swpCmpOps = false;
3388 bool swpVselOps = false;
3389 checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3391 if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3392 CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3394 std::swap(LHS, RHS);
3396 std::swap(TrueVal, FalseVal);
3400 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3401 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3402 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3403 SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3405 if (CondCode2 != ARMCC::AL) {
3406 SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3407 // FIXME: Needs another CMP because flag can have but one use.
3408 SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3409 Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3410 Result, TrueVal, ARMcc2, CCR, Cmp2);
3415 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3416 /// to morph to an integer compare sequence.
3417 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3418 const ARMSubtarget *Subtarget) {
3419 SDNode *N = Op.getNode();
3420 if (!N->hasOneUse())
3421 // Otherwise it requires moving the value from fp to integer registers.
3423 if (!N->getNumValues())
3425 EVT VT = Op.getValueType();
3426 if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3427 // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3428 // vmrs are very slow, e.g. cortex-a8.
3431 if (isFloatingPointZero(Op)) {
3435 return ISD::isNormalLoad(N);
3438 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3439 if (isFloatingPointZero(Op))
3440 return DAG.getConstant(0, MVT::i32);
3442 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3443 return DAG.getLoad(MVT::i32, SDLoc(Op),
3444 Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3445 Ld->isVolatile(), Ld->isNonTemporal(),
3446 Ld->isInvariant(), Ld->getAlignment());
3448 llvm_unreachable("Unknown VFP cmp argument!");
3451 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3452 SDValue &RetVal1, SDValue &RetVal2) {
3453 if (isFloatingPointZero(Op)) {
3454 RetVal1 = DAG.getConstant(0, MVT::i32);
3455 RetVal2 = DAG.getConstant(0, MVT::i32);
3459 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3460 SDValue Ptr = Ld->getBasePtr();
3461 RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3462 Ld->getChain(), Ptr,
3463 Ld->getPointerInfo(),
3464 Ld->isVolatile(), Ld->isNonTemporal(),
3465 Ld->isInvariant(), Ld->getAlignment());
3467 EVT PtrType = Ptr.getValueType();
3468 unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3469 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3470 PtrType, Ptr, DAG.getConstant(4, PtrType));
3471 RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3472 Ld->getChain(), NewPtr,
3473 Ld->getPointerInfo().getWithOffset(4),
3474 Ld->isVolatile(), Ld->isNonTemporal(),
3475 Ld->isInvariant(), NewAlign);
3479 llvm_unreachable("Unknown VFP cmp argument!");
3482 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3483 /// f32 and even f64 comparisons to integer ones.
3485 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3486 SDValue Chain = Op.getOperand(0);
3487 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3488 SDValue LHS = Op.getOperand(2);
3489 SDValue RHS = Op.getOperand(3);
3490 SDValue Dest = Op.getOperand(4);
3493 bool LHSSeenZero = false;
3494 bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3495 bool RHSSeenZero = false;
3496 bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3497 if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3498 // If unsafe fp math optimization is enabled and there are no other uses of
3499 // the CMP operands, and the condition code is EQ or NE, we can optimize it
3500 // to an integer comparison.
3501 if (CC == ISD::SETOEQ)
3503 else if (CC == ISD::SETUNE)
3506 SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3508 if (LHS.getValueType() == MVT::f32) {
3509 LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3510 bitcastf32Toi32(LHS, DAG), Mask);
3511 RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3512 bitcastf32Toi32(RHS, DAG), Mask);
3513 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3514 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3515 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3516 Chain, Dest, ARMcc, CCR, Cmp);
3521 expandf64Toi32(LHS, DAG, LHS1, LHS2);
3522 expandf64Toi32(RHS, DAG, RHS1, RHS2);
3523 LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3524 RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3525 ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3526 ARMcc = DAG.getConstant(CondCode, MVT::i32);
3527 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3528 SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3529 return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3535 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3536 SDValue Chain = Op.getOperand(0);
3537 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3538 SDValue LHS = Op.getOperand(2);
3539 SDValue RHS = Op.getOperand(3);
3540 SDValue Dest = Op.getOperand(4);
3543 if (LHS.getValueType() == MVT::i32) {
3545 SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3546 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3547 return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3548 Chain, Dest, ARMcc, CCR, Cmp);
3551 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3553 if (getTargetMachine().Options.UnsafeFPMath &&
3554 (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3555 CC == ISD::SETNE || CC == ISD::SETUNE)) {
3556 SDValue Result = OptimizeVFPBrcond(Op, DAG);
3557 if (Result.getNode())
3561 ARMCC::CondCodes CondCode, CondCode2;
3562 FPCCToARMCC(CC, CondCode, CondCode2);
3564 SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3565 SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3566 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3567 SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3568 SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3569 SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3570 if (CondCode2 != ARMCC::AL) {
3571 ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3572 SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3573 Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3578 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3579 SDValue Chain = Op.getOperand(0);
3580 SDValue Table = Op.getOperand(1);
3581 SDValue Index = Op.getOperand(2);
3584 EVT PTy = getPointerTy();
3585 JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3586 ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3587 SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3588 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3589 Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3590 Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3591 SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3592 if (Subtarget->isThumb2()) {
3593 // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3594 // which does another jump to the destination. This also makes it easier
3595 // to translate it to TBB / TBH later.
3596 // FIXME: This might not work if the function is extremely large.
3597 return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3598 Addr, Op.getOperand(2), JTI, UId);
3600 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3601 Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3602 MachinePointerInfo::getJumpTable(),
3603 false, false, false, 0);
3604 Chain = Addr.getValue(1);
3605 Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3606 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3608 Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3609 MachinePointerInfo::getJumpTable(),
3610 false, false, false, 0);
3611 Chain = Addr.getValue(1);
3612 return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3616 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3617 EVT VT = Op.getValueType();
3620 if (Op.getValueType().getVectorElementType() == MVT::i32) {
3621 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3623 return DAG.UnrollVectorOp(Op.getNode());
3626 assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3627 "Invalid type for custom lowering!");
3628 if (VT != MVT::v4i16)
3629 return DAG.UnrollVectorOp(Op.getNode());
3631 Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3632 return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3635 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3636 EVT VT = Op.getValueType();
3638 return LowerVectorFP_TO_INT(Op, DAG);
3643 switch (Op.getOpcode()) {
3644 default: llvm_unreachable("Invalid opcode!");
3645 case ISD::FP_TO_SINT:
3646 Opc = ARMISD::FTOSI;
3648 case ISD::FP_TO_UINT:
3649 Opc = ARMISD::FTOUI;
3652 Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3653 return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3656 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3657 EVT VT = Op.getValueType();
3660 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3661 if (VT.getVectorElementType() == MVT::f32)
3663 return DAG.UnrollVectorOp(Op.getNode());
3666 assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3667 "Invalid type for custom lowering!");
3668 if (VT != MVT::v4f32)
3669 return DAG.UnrollVectorOp(Op.getNode());
3673 switch (Op.getOpcode()) {
3674 default: llvm_unreachable("Invalid opcode!");
3675 case ISD::SINT_TO_FP:
3676 CastOpc = ISD::SIGN_EXTEND;
3677 Opc = ISD::SINT_TO_FP;
3679 case ISD::UINT_TO_FP:
3680 CastOpc = ISD::ZERO_EXTEND;
3681 Opc = ISD::UINT_TO_FP;
3685 Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3686 return DAG.getNode(Opc, dl, VT, Op);
3689 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3690 EVT VT = Op.getValueType();
3692 return LowerVectorINT_TO_FP(Op, DAG);
3697 switch (Op.getOpcode()) {
3698 default: llvm_unreachable("Invalid opcode!");
3699 case ISD::SINT_TO_FP:
3700 Opc = ARMISD::SITOF;
3702 case ISD::UINT_TO_FP:
3703 Opc = ARMISD::UITOF;
3707 Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3708 return DAG.getNode(Opc, dl, VT, Op);
3711 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3712 // Implement fcopysign with a fabs and a conditional fneg.
3713 SDValue Tmp0 = Op.getOperand(0);
3714 SDValue Tmp1 = Op.getOperand(1);
3716 EVT VT = Op.getValueType();
3717 EVT SrcVT = Tmp1.getValueType();
3718 bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3719 Tmp0.getOpcode() == ARMISD::VMOVDRR;
3720 bool UseNEON = !InGPR && Subtarget->hasNEON();
3723 // Use VBSL to copy the sign bit.
3724 unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3725 SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3726 DAG.getTargetConstant(EncodedVal, MVT::i32));
3727 EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3729 Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3730 DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3731 DAG.getConstant(32, MVT::i32));
3732 else /*if (VT == MVT::f32)*/
3733 Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3734 if (SrcVT == MVT::f32) {
3735 Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3737 Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3738 DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3739 DAG.getConstant(32, MVT::i32));
3740 } else if (VT == MVT::f32)
3741 Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3742 DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3743 DAG.getConstant(32, MVT::i32));
3744 Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3745 Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3747 SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3749 AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3750 SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3751 DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3753 SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3754 DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3755 DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3756 if (VT == MVT::f32) {
3757 Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3758 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3759 DAG.getConstant(0, MVT::i32));
3761 Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3767 // Bitcast operand 1 to i32.
3768 if (SrcVT == MVT::f64)
3769 Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3770 &Tmp1, 1).getValue(1);
3771 Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3773 // Or in the signbit with integer operations.
3774 SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3775 SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3776 Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3777 if (VT == MVT::f32) {
3778 Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3779 DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3780 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3781 DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3784 // f64: Or the high part with signbit and then combine two parts.
3785 Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3787 SDValue Lo = Tmp0.getValue(0);
3788 SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3789 Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3790 return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3793 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3794 MachineFunction &MF = DAG.getMachineFunction();
3795 MachineFrameInfo *MFI = MF.getFrameInfo();
3796 MFI->setReturnAddressIsTaken(true);
3798 EVT VT = Op.getValueType();
3800 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3802 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3803 SDValue Offset = DAG.getConstant(4, MVT::i32);
3804 return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3805 DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3806 MachinePointerInfo(), false, false, false, 0);
3809 // Return LR, which contains the return address. Mark it an implicit live-in.
3810 unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3811 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3814 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3815 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3816 MFI->setFrameAddressIsTaken(true);
3818 EVT VT = Op.getValueType();
3819 SDLoc dl(Op); // FIXME probably not meaningful
3820 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3821 unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3822 ? ARM::R7 : ARM::R11;
3823 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3825 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3826 MachinePointerInfo(),
3827 false, false, false, 0);
3831 /// Custom Expand long vector extensions, where size(DestVec) > 2*size(SrcVec),
3832 /// and size(DestVec) > 128-bits.
3833 /// This is achieved by doing the one extension from the SrcVec, splitting the
3834 /// result, extending these parts, and then concatenating these into the
3836 static SDValue ExpandVectorExtension(SDNode *N, SelectionDAG &DAG) {
3837 SDValue Op = N->getOperand(0);
3838 EVT SrcVT = Op.getValueType();
3839 EVT DestVT = N->getValueType(0);
3841 assert(DestVT.getSizeInBits() > 128 &&
3842 "Custom sext/zext expansion needs >128-bit vector.");
3843 // If this is a normal length extension, use the default expansion.
3844 if (SrcVT.getSizeInBits()*4 != DestVT.getSizeInBits() &&
3845 SrcVT.getSizeInBits()*8 != DestVT.getSizeInBits())
3849 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
3850 unsigned DestEltSize = DestVT.getVectorElementType().getSizeInBits();
3851 unsigned NumElts = SrcVT.getVectorNumElements();
3852 LLVMContext &Ctx = *DAG.getContext();
3853 SDValue Mid, SplitLo, SplitHi, ExtLo, ExtHi;
3855 EVT MidVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3857 EVT SplitVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, SrcEltSize*2),
3859 EVT ExtVT = EVT::getVectorVT(Ctx, EVT::getIntegerVT(Ctx, DestEltSize),
3862 Mid = DAG.getNode(N->getOpcode(), dl, MidVT, Op);
3863 SplitLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3864 DAG.getIntPtrConstant(0));
3865 SplitHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SplitVT, Mid,
3866 DAG.getIntPtrConstant(NumElts/2));
3867 ExtLo = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitLo);
3868 ExtHi = DAG.getNode(N->getOpcode(), dl, ExtVT, SplitHi);
3869 return DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, ExtLo, ExtHi);
3872 /// ExpandBITCAST - If the target supports VFP, this function is called to
3873 /// expand a bit convert where either the source or destination type is i64 to
3874 /// use a VMOVDRR or VMOVRRD node. This should not be done when the non-i64
3875 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3876 /// vectors), since the legalizer won't know what to do with that.
3877 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3880 SDValue Op = N->getOperand(0);
3882 // This function is only supposed to be called for i64 types, either as the
3883 // source or destination of the bit convert.
3884 EVT SrcVT = Op.getValueType();
3885 EVT DstVT = N->getValueType(0);
3886 assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3887 "ExpandBITCAST called for non-i64 type");
3889 // Turn i64->f64 into VMOVDRR.
3890 if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3891 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3892 DAG.getConstant(0, MVT::i32));
3893 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3894 DAG.getConstant(1, MVT::i32));
3895 return DAG.getNode(ISD::BITCAST, dl, DstVT,
3896 DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3899 // Turn f64->i64 into VMOVRRD.
3900 if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3901 SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3902 DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3903 // Merge the pieces into a single i64 value.
3904 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3910 /// getZeroVector - Returns a vector of specified type with all zero elements.
3911 /// Zero vectors are used to represent vector negation and in those cases
3912 /// will be implemented with the NEON VNEG instruction. However, VNEG does
3913 /// not support i64 elements, so sometimes the zero vectors will need to be
3914 /// explicitly constructed. Regardless, use a canonical VMOV to create the
3916 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3917 assert(VT.isVector() && "Expected a vector type");
3918 // The canonical modified immediate encoding of a zero vector is....0!
3919 SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3920 EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3921 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3922 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3925 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3926 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3927 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3928 SelectionDAG &DAG) const {
3929 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3930 EVT VT = Op.getValueType();
3931 unsigned VTBits = VT.getSizeInBits();
3933 SDValue ShOpLo = Op.getOperand(0);
3934 SDValue ShOpHi = Op.getOperand(1);
3935 SDValue ShAmt = Op.getOperand(2);
3937 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3939 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3941 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3942 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3943 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3944 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3945 DAG.getConstant(VTBits, MVT::i32));
3946 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3947 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3948 SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3950 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3951 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3953 SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3954 SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3957 SDValue Ops[2] = { Lo, Hi };
3958 return DAG.getMergeValues(Ops, 2, dl);
3961 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3962 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3963 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3964 SelectionDAG &DAG) const {
3965 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3966 EVT VT = Op.getValueType();
3967 unsigned VTBits = VT.getSizeInBits();
3969 SDValue ShOpLo = Op.getOperand(0);
3970 SDValue ShOpHi = Op.getOperand(1);
3971 SDValue ShAmt = Op.getOperand(2);
3974 assert(Op.getOpcode() == ISD::SHL_PARTS);
3975 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3976 DAG.getConstant(VTBits, MVT::i32), ShAmt);
3977 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3978 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3979 DAG.getConstant(VTBits, MVT::i32));
3980 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3981 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3983 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3984 SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3985 SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3987 SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3988 SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3991 SDValue Ops[2] = { Lo, Hi };
3992 return DAG.getMergeValues(Ops, 2, dl);
3995 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3996 SelectionDAG &DAG) const {
3997 // The rounding mode is in bits 23:22 of the FPSCR.
3998 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3999 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4000 // so that the shift + and get folded into a bitfield extract.
4002 SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4003 DAG.getConstant(Intrinsic::arm_get_fpscr,
4005 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4006 DAG.getConstant(1U << 22, MVT::i32));
4007 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4008 DAG.getConstant(22, MVT::i32));
4009 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4010 DAG.getConstant(3, MVT::i32));
4013 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4014 const ARMSubtarget *ST) {
4015 EVT VT = N->getValueType(0);
4018 if (!ST->hasV6T2Ops())
4021 SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4022 return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4025 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4026 /// for each 16-bit element from operand, repeated. The basic idea is to
4027 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4029 /// Trace for v4i16:
4030 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4031 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4032 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4033 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4034 /// [b0 b1 b2 b3 b4 b5 b6 b7]
4035 /// +[b1 b0 b3 b2 b5 b4 b7 b6]
4036 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4037 /// vuzp: = [k0 k1 k2 k3 k0 k1 k2 k3] each ki is 8-bits)
4038 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4039 EVT VT = N->getValueType(0);
4042 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4043 SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4044 SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4045 SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4046 SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4047 return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4050 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4051 /// bit-count for each 16-bit element from the operand. We need slightly
4052 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4053 /// 64/128-bit registers.
4055 /// Trace for v4i16:
4056 /// input = [v0 v1 v2 v3 ] (vi 16-bit element)
4057 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4058 /// v8i16:Extended = [k0 k1 k2 k3 k0 k1 k2 k3 ]
4059 /// v4i16:Extracted = [k0 k1 k2 k3 ]
4060 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4061 EVT VT = N->getValueType(0);
4064 SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4065 if (VT.is64BitVector()) {
4066 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4067 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4068 DAG.getIntPtrConstant(0));
4070 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4071 BitCounts, DAG.getIntPtrConstant(0));
4072 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4076 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4077 /// bit-count for each 32-bit element from the operand. The idea here is
4078 /// to split the vector into 16-bit elements, leverage the 16-bit count
4079 /// routine, and then combine the results.
4081 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4082 /// input = [v0 v1 ] (vi: 32-bit elements)
4083 /// Bitcast = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4084 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4085 /// vrev: N0 = [k1 k0 k3 k2 ]
4087 /// N1 =+[k1 k0 k3 k2 ]
4089 /// N2 =+[k1 k3 k0 k2 ]
4091 /// Extended =+[k1 k3 k0 k2 ]
4093 /// Extracted=+[k1 k3 ]
4095 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4096 EVT VT = N->getValueType(0);
4099 EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4101 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4102 SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4103 SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4104 SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4105 SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4107 if (VT.is64BitVector()) {
4108 SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4109 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4110 DAG.getIntPtrConstant(0));
4112 SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4113 DAG.getIntPtrConstant(0));
4114 return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4118 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4119 const ARMSubtarget *ST) {
4120 EVT VT = N->getValueType(0);
4122 assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4123 assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4124 VT == MVT::v4i16 || VT == MVT::v8i16) &&
4125 "Unexpected type for custom ctpop lowering");
4127 if (VT.getVectorElementType() == MVT::i32)
4128 return lowerCTPOP32BitElements(N, DAG);
4130 return lowerCTPOP16BitElements(N, DAG);
4133 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4134 const ARMSubtarget *ST) {
4135 EVT VT = N->getValueType(0);
4141 // Lower vector shifts on NEON to use VSHL.
4142 assert(ST->hasNEON() && "unexpected vector shift");
4144 // Left shifts translate directly to the vshiftu intrinsic.
4145 if (N->getOpcode() == ISD::SHL)
4146 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4147 DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4148 N->getOperand(0), N->getOperand(1));
4150 assert((N->getOpcode() == ISD::SRA ||
4151 N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4153 // NEON uses the same intrinsics for both left and right shifts. For
4154 // right shifts, the shift amounts are negative, so negate the vector of
4156 EVT ShiftVT = N->getOperand(1).getValueType();
4157 SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4158 getZeroVector(ShiftVT, DAG, dl),
4160 Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4161 Intrinsic::arm_neon_vshifts :
4162 Intrinsic::arm_neon_vshiftu);
4163 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4164 DAG.getConstant(vshiftInt, MVT::i32),
4165 N->getOperand(0), NegatedCount);
4168 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4169 const ARMSubtarget *ST) {
4170 EVT VT = N->getValueType(0);
4173 // We can get here for a node like i32 = ISD::SHL i32, i64
4177 assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4178 "Unknown shift to lower!");
4180 // We only lower SRA, SRL of 1 here, all others use generic lowering.
4181 if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4182 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4185 // If we are in thumb mode, we don't have RRX.
4186 if (ST->isThumb1Only()) return SDValue();
4188 // Okay, we have a 64-bit SRA or SRL of 1. Lower this to an RRX expr.
4189 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4190 DAG.getConstant(0, MVT::i32));
4191 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4192 DAG.getConstant(1, MVT::i32));
4194 // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4195 // captures the result into a carry flag.
4196 unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4197 Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4199 // The low part is an ARMISD::RRX operand, which shifts the carry in.
4200 Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4202 // Merge the pieces into a single i64 value.
4203 return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4206 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4207 SDValue TmpOp0, TmpOp1;
4208 bool Invert = false;
4212 SDValue Op0 = Op.getOperand(0);
4213 SDValue Op1 = Op.getOperand(1);
4214 SDValue CC = Op.getOperand(2);
4215 EVT VT = Op.getValueType();
4216 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4219 if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4220 switch (SetCCOpcode) {
4221 default: llvm_unreachable("Illegal FP comparison");
4223 case ISD::SETNE: Invert = true; // Fallthrough
4225 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4227 case ISD::SETLT: Swap = true; // Fallthrough
4229 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4231 case ISD::SETLE: Swap = true; // Fallthrough
4233 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4234 case ISD::SETUGE: Swap = true; // Fallthrough
4235 case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4236 case ISD::SETUGT: Swap = true; // Fallthrough
4237 case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4238 case ISD::SETUEQ: Invert = true; // Fallthrough
4240 // Expand this to (OLT | OGT).
4244 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4245 Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4247 case ISD::SETUO: Invert = true; // Fallthrough
4249 // Expand this to (OLT | OGE).
4253 Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4254 Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4258 // Integer comparisons.
4259 switch (SetCCOpcode) {
4260 default: llvm_unreachable("Illegal integer comparison");
4261 case ISD::SETNE: Invert = true;
4262 case ISD::SETEQ: Opc = ARMISD::VCEQ; break;
4263 case ISD::SETLT: Swap = true;
4264 case ISD::SETGT: Opc = ARMISD::VCGT; break;
4265 case ISD::SETLE: Swap = true;
4266 case ISD::SETGE: Opc = ARMISD::VCGE; break;
4267 case ISD::SETULT: Swap = true;
4268 case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4269 case ISD::SETULE: Swap = true;
4270 case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4273 // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4274 if (Opc == ARMISD::VCEQ) {
4277 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4279 else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4282 // Ignore bitconvert.
4283 if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4284 AndOp = AndOp.getOperand(0);
4286 if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4288 Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4289 Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4296 std::swap(Op0, Op1);
4298 // If one of the operands is a constant vector zero, attempt to fold the
4299 // comparison to a specialized compare-against-zero form.
4301 if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4303 else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4304 if (Opc == ARMISD::VCGE)
4305 Opc = ARMISD::VCLEZ;
4306 else if (Opc == ARMISD::VCGT)
4307 Opc = ARMISD::VCLTZ;
4312 if (SingleOp.getNode()) {
4315 Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4317 Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4319 Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4321 Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4323 Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4325 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4328 Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4332 Result = DAG.getNOT(dl, Result, VT);
4337 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4338 /// valid vector constant for a NEON instruction with a "modified immediate"
4339 /// operand (e.g., VMOV). If so, return the encoded value.
4340 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4341 unsigned SplatBitSize, SelectionDAG &DAG,
4342 EVT &VT, bool is128Bits, NEONModImmType type) {
4343 unsigned OpCmode, Imm;
4345 // SplatBitSize is set to the smallest size that splats the vector, so a
4346 // zero vector will always have SplatBitSize == 8. However, NEON modified
4347 // immediate instructions others than VMOV do not support the 8-bit encoding
4348 // of a zero vector, and the default encoding of zero is supposed to be the
4353 switch (SplatBitSize) {
4355 if (type != VMOVModImm)
4357 // Any 1-byte value is OK. Op=0, Cmode=1110.
4358 assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4361 VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4365 // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4366 VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4367 if ((SplatBits & ~0xff) == 0) {
4368 // Value = 0x00nn: Op=x, Cmode=100x.
4373 if ((SplatBits & ~0xff00) == 0) {
4374 // Value = 0xnn00: Op=x, Cmode=101x.
4376 Imm = SplatBits >> 8;
4382 // NEON's 32-bit VMOV supports splat values where:
4383 // * only one byte is nonzero, or
4384 // * the least significant byte is 0xff and the second byte is nonzero, or
4385 // * the least significant 2 bytes are 0xff and the third is nonzero.
4386 VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4387 if ((SplatBits & ~0xff) == 0) {
4388 // Value = 0x000000nn: Op=x, Cmode=000x.
4393 if ((SplatBits & ~0xff00) == 0) {
4394 // Value = 0x0000nn00: Op=x, Cmode=001x.
4396 Imm = SplatBits >> 8;
4399 if ((SplatBits & ~0xff0000) == 0) {
4400 // Value = 0x00nn0000: Op=x, Cmode=010x.
4402 Imm = SplatBits >> 16;
4405 if ((SplatBits & ~0xff000000) == 0) {
4406 // Value = 0xnn000000: Op=x, Cmode=011x.
4408 Imm = SplatBits >> 24;
4412 // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4413 if (type == OtherModImm) return SDValue();
4415 if ((SplatBits & ~0xffff) == 0 &&
4416 ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4417 // Value = 0x0000nnff: Op=x, Cmode=1100.
4419 Imm = SplatBits >> 8;
4424 if ((SplatBits & ~0xffffff) == 0 &&
4425 ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4426 // Value = 0x00nnffff: Op=x, Cmode=1101.
4428 Imm = SplatBits >> 16;
4429 SplatBits |= 0xffff;
4433 // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4434 // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4435 // VMOV.I32. A (very) minor optimization would be to replicate the value
4436 // and fall through here to test for a valid 64-bit splat. But, then the
4437 // caller would also need to check and handle the change in size.
4441 if (type != VMOVModImm)
4443 // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4444 uint64_t BitMask = 0xff;
4446 unsigned ImmMask = 1;
4448 for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4449 if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4452 } else if ((SplatBits & BitMask) != 0) {
4458 // Op=1, Cmode=1110.
4461 VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4466 llvm_unreachable("unexpected size for isNEONModifiedImm");
4469 unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4470 return DAG.getTargetConstant(EncodedVal, MVT::i32);
4473 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4474 const ARMSubtarget *ST) const {
4478 bool IsDouble = Op.getValueType() == MVT::f64;
4479 ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4481 // Try splatting with a VMOV.f32...
4482 APFloat FPVal = CFP->getValueAPF();
4483 int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4486 if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4487 // We have code in place to select a valid ConstantFP already, no need to
4492 // It's a float and we are trying to use NEON operations where
4493 // possible. Lower it to a splat followed by an extract.
4495 SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4496 SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4498 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4499 DAG.getConstant(0, MVT::i32));
4502 // The rest of our options are NEON only, make sure that's allowed before
4504 if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4508 uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4510 // It wouldn't really be worth bothering for doubles except for one very
4511 // important value, which does happen to match: 0.0. So make sure we don't do
4513 if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4516 // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4517 SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4519 if (NewVal != SDValue()) {
4521 SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4524 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4526 // It's a float: cast and extract a vector element.
4527 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4529 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4530 DAG.getConstant(0, MVT::i32));
4533 // Finally, try a VMVN.i32
4534 NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4536 if (NewVal != SDValue()) {
4538 SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4541 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4543 // It's a float: cast and extract a vector element.
4544 SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4547 DAG.getConstant(0, MVT::i32));
4553 // check if an VEXT instruction can handle the shuffle mask when the
4554 // vector sources of the shuffle are the same.
4555 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4556 unsigned NumElts = VT.getVectorNumElements();
4558 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4564 // If this is a VEXT shuffle, the immediate value is the index of the first
4565 // element. The other shuffle indices must be the successive elements after
4567 unsigned ExpectedElt = Imm;
4568 for (unsigned i = 1; i < NumElts; ++i) {
4569 // Increment the expected index. If it wraps around, just follow it
4570 // back to index zero and keep going.
4572 if (ExpectedElt == NumElts)
4575 if (M[i] < 0) continue; // ignore UNDEF indices
4576 if (ExpectedElt != static_cast<unsigned>(M[i]))
4584 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4585 bool &ReverseVEXT, unsigned &Imm) {
4586 unsigned NumElts = VT.getVectorNumElements();
4587 ReverseVEXT = false;
4589 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4595 // If this is a VEXT shuffle, the immediate value is the index of the first
4596 // element. The other shuffle indices must be the successive elements after
4598 unsigned ExpectedElt = Imm;
4599 for (unsigned i = 1; i < NumElts; ++i) {
4600 // Increment the expected index. If it wraps around, it may still be
4601 // a VEXT but the source vectors must be swapped.
4603 if (ExpectedElt == NumElts * 2) {
4608 if (M[i] < 0) continue; // ignore UNDEF indices
4609 if (ExpectedElt != static_cast<unsigned>(M[i]))
4613 // Adjust the index value if the source operands will be swapped.
4620 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4621 /// instruction with the specified blocksize. (The order of the elements
4622 /// within each block of the vector is reversed.)
4623 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4624 assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4625 "Only possible block sizes for VREV are: 16, 32, 64");
4627 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4631 unsigned NumElts = VT.getVectorNumElements();
4632 unsigned BlockElts = M[0] + 1;
4633 // If the first shuffle index is UNDEF, be optimistic.
4635 BlockElts = BlockSize / EltSz;
4637 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4640 for (unsigned i = 0; i < NumElts; ++i) {
4641 if (M[i] < 0) continue; // ignore UNDEF indices
4642 if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4649 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4650 // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4651 // range, then 0 is placed into the resulting vector. So pretty much any mask
4652 // of 8 elements can work here.
4653 return VT == MVT::v8i8 && M.size() == 8;
4656 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4657 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4661 unsigned NumElts = VT.getVectorNumElements();
4662 WhichResult = (M[0] == 0 ? 0 : 1);
4663 for (unsigned i = 0; i < NumElts; i += 2) {
4664 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4665 (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4671 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4672 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4673 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4674 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4675 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4679 unsigned NumElts = VT.getVectorNumElements();
4680 WhichResult = (M[0] == 0 ? 0 : 1);
4681 for (unsigned i = 0; i < NumElts; i += 2) {
4682 if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4683 (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4689 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4690 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4694 unsigned NumElts = VT.getVectorNumElements();
4695 WhichResult = (M[0] == 0 ? 0 : 1);
4696 for (unsigned i = 0; i != NumElts; ++i) {
4697 if (M[i] < 0) continue; // ignore UNDEF indices
4698 if ((unsigned) M[i] != 2 * i + WhichResult)
4702 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4703 if (VT.is64BitVector() && EltSz == 32)
4709 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4710 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4711 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4712 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4713 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4717 unsigned Half = VT.getVectorNumElements() / 2;
4718 WhichResult = (M[0] == 0 ? 0 : 1);
4719 for (unsigned j = 0; j != 2; ++j) {
4720 unsigned Idx = WhichResult;
4721 for (unsigned i = 0; i != Half; ++i) {
4722 int MIdx = M[i + j * Half];
4723 if (MIdx >= 0 && (unsigned) MIdx != Idx)
4729 // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4730 if (VT.is64BitVector() && EltSz == 32)
4736 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4737 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4741 unsigned NumElts = VT.getVectorNumElements();
4742 WhichResult = (M[0] == 0 ? 0 : 1);
4743 unsigned Idx = WhichResult * NumElts / 2;
4744 for (unsigned i = 0; i != NumElts; i += 2) {
4745 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4746 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4751 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4752 if (VT.is64BitVector() && EltSz == 32)
4758 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4759 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4760 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4761 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4762 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4766 unsigned NumElts = VT.getVectorNumElements();
4767 WhichResult = (M[0] == 0 ? 0 : 1);
4768 unsigned Idx = WhichResult * NumElts / 2;
4769 for (unsigned i = 0; i != NumElts; i += 2) {
4770 if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4771 (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4776 // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4777 if (VT.is64BitVector() && EltSz == 32)
4783 /// \return true if this is a reverse operation on an vector.
4784 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4785 unsigned NumElts = VT.getVectorNumElements();
4786 // Make sure the mask has the right size.
4787 if (NumElts != M.size())
4790 // Look for <15, ..., 3, -1, 1, 0>.
4791 for (unsigned i = 0; i != NumElts; ++i)
4792 if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4798 // If N is an integer constant that can be moved into a register in one
4799 // instruction, return an SDValue of such a constant (will become a MOV
4800 // instruction). Otherwise return null.
4801 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4802 const ARMSubtarget *ST, SDLoc dl) {
4804 if (!isa<ConstantSDNode>(N))
4806 Val = cast<ConstantSDNode>(N)->getZExtValue();
4808 if (ST->isThumb1Only()) {
4809 if (Val <= 255 || ~Val <= 255)
4810 return DAG.getConstant(Val, MVT::i32);
4812 if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4813 return DAG.getConstant(Val, MVT::i32);
4818 // If this is a case we can't handle, return null and let the default
4819 // expansion code take care of it.
4820 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4821 const ARMSubtarget *ST) const {
4822 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4824 EVT VT = Op.getValueType();
4826 APInt SplatBits, SplatUndef;
4827 unsigned SplatBitSize;
4829 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4830 if (SplatBitSize <= 64) {
4831 // Check if an immediate VMOV works.
4833 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4834 SplatUndef.getZExtValue(), SplatBitSize,
4835 DAG, VmovVT, VT.is128BitVector(),
4837 if (Val.getNode()) {
4838 SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4839 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4842 // Try an immediate VMVN.
4843 uint64_t NegatedImm = (~SplatBits).getZExtValue();
4844 Val = isNEONModifiedImm(NegatedImm,
4845 SplatUndef.getZExtValue(), SplatBitSize,
4846 DAG, VmovVT, VT.is128BitVector(),
4848 if (Val.getNode()) {
4849 SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4850 return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4853 // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4854 if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4855 int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4857 SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4858 return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4864 // Scan through the operands to see if only one value is used.
4866 // As an optimisation, even if more than one value is used it may be more
4867 // profitable to splat with one value then change some lanes.
4869 // Heuristically we decide to do this if the vector has a "dominant" value,
4870 // defined as splatted to more than half of the lanes.
4871 unsigned NumElts = VT.getVectorNumElements();
4872 bool isOnlyLowElement = true;
4873 bool usesOnlyOneValue = true;
4874 bool hasDominantValue = false;
4875 bool isConstant = true;
4877 // Map of the number of times a particular SDValue appears in the
4879 DenseMap<SDValue, unsigned> ValueCounts;
4881 for (unsigned i = 0; i < NumElts; ++i) {
4882 SDValue V = Op.getOperand(i);
4883 if (V.getOpcode() == ISD::UNDEF)
4886 isOnlyLowElement = false;
4887 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4890 ValueCounts.insert(std::make_pair(V, 0));
4891 unsigned &Count = ValueCounts[V];
4893 // Is this value dominant? (takes up more than half of the lanes)
4894 if (++Count > (NumElts / 2)) {
4895 hasDominantValue = true;
4899 if (ValueCounts.size() != 1)
4900 usesOnlyOneValue = false;
4901 if (!Value.getNode() && ValueCounts.size() > 0)
4902 Value = ValueCounts.begin()->first;
4904 if (ValueCounts.size() == 0)
4905 return DAG.getUNDEF(VT);
4907 // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4908 // Keep going if we are hitting this case.
4909 if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4910 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4912 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4914 // Use VDUP for non-constant splats. For f32 constant splats, reduce to
4915 // i32 and try again.
4916 if (hasDominantValue && EltSize <= 32) {
4920 // If we are VDUPing a value that comes directly from a vector, that will
4921 // cause an unnecessary move to and from a GPR, where instead we could
4922 // just use VDUPLANE. We can only do this if the lane being extracted
4923 // is at a constant index, as the VDUP from lane instructions only have
4924 // constant-index forms.
4925 if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4926 isa<ConstantSDNode>(Value->getOperand(1))) {
4927 // We need to create a new undef vector to use for the VDUPLANE if the
4928 // size of the vector from which we get the value is different than the
4929 // size of the vector that we need to create. We will insert the element
4930 // such that the register coalescer will remove unnecessary copies.
4931 if (VT != Value->getOperand(0).getValueType()) {
4932 ConstantSDNode *constIndex;
4933 constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4934 assert(constIndex && "The index is not a constant!");
4935 unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4936 VT.getVectorNumElements();
4937 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4938 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4939 Value, DAG.getConstant(index, MVT::i32)),
4940 DAG.getConstant(index, MVT::i32));
4942 N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4943 Value->getOperand(0), Value->getOperand(1));
4945 N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4947 if (!usesOnlyOneValue) {
4948 // The dominant value was splatted as 'N', but we now have to insert
4949 // all differing elements.
4950 for (unsigned I = 0; I < NumElts; ++I) {
4951 if (Op.getOperand(I) == Value)
4953 SmallVector<SDValue, 3> Ops;
4955 Ops.push_back(Op.getOperand(I));
4956 Ops.push_back(DAG.getConstant(I, MVT::i32));
4957 N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4962 if (VT.getVectorElementType().isFloatingPoint()) {
4963 SmallVector<SDValue, 8> Ops;
4964 for (unsigned i = 0; i < NumElts; ++i)
4965 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4967 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4968 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4969 Val = LowerBUILD_VECTOR(Val, DAG, ST);
4971 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4973 if (usesOnlyOneValue) {
4974 SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4975 if (isConstant && Val.getNode())
4976 return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4980 // If all elements are constants and the case above didn't get hit, fall back
4981 // to the default expansion, which will generate a load from the constant
4986 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4988 SDValue shuffle = ReconstructShuffle(Op, DAG);
4989 if (shuffle != SDValue())
4993 // Vectors with 32- or 64-bit elements can be built by directly assigning
4994 // the subregisters. Lower it to an ARMISD::BUILD_VECTOR so the operands
4995 // will be legalized.
4996 if (EltSize >= 32) {
4997 // Do the expansion with floating-point types, since that is what the VFP
4998 // registers are defined to use, and since i64 is not legal.
4999 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5000 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5001 SmallVector<SDValue, 8> Ops;
5002 for (unsigned i = 0; i < NumElts; ++i)
5003 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5004 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5005 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5008 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5009 // know the default expansion would otherwise fall back on something even
5010 // worse. For a vector with one or two non-undef values, that's
5011 // scalar_to_vector for the elements followed by a shuffle (provided the
5012 // shuffle is valid for the target) and materialization element by element
5013 // on the stack followed by a load for everything else.
5014 if (!isConstant && !usesOnlyOneValue) {
5015 SDValue Vec = DAG.getUNDEF(VT);
5016 for (unsigned i = 0 ; i < NumElts; ++i) {
5017 SDValue V = Op.getOperand(i);
5018 if (V.getOpcode() == ISD::UNDEF)
5020 SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5021 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5029 // Gather data to see if the operation can be modelled as a
5030 // shuffle in combination with VEXTs.
5031 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5032 SelectionDAG &DAG) const {
5034 EVT VT = Op.getValueType();
5035 unsigned NumElts = VT.getVectorNumElements();
5037 SmallVector<SDValue, 2> SourceVecs;
5038 SmallVector<unsigned, 2> MinElts;
5039 SmallVector<unsigned, 2> MaxElts;
5041 for (unsigned i = 0; i < NumElts; ++i) {
5042 SDValue V = Op.getOperand(i);
5043 if (V.getOpcode() == ISD::UNDEF)
5045 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5046 // A shuffle can only come from building a vector from various
5047 // elements of other vectors.
5049 } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5050 VT.getVectorElementType()) {
5051 // This code doesn't know how to handle shuffles where the vector
5052 // element types do not match (this happens because type legalization
5053 // promotes the return type of EXTRACT_VECTOR_ELT).
5054 // FIXME: It might be appropriate to extend this code to handle
5055 // mismatched types.
5059 // Record this extraction against the appropriate vector if possible...
5060 SDValue SourceVec = V.getOperand(0);
5061 // If the element number isn't a constant, we can't effectively
5062 // analyze what's going on.
5063 if (!isa<ConstantSDNode>(V.getOperand(1)))
5065 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5066 bool FoundSource = false;
5067 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5068 if (SourceVecs[j] == SourceVec) {
5069 if (MinElts[j] > EltNo)
5071 if (MaxElts[j] < EltNo)
5078 // Or record a new source if not...
5080 SourceVecs.push_back(SourceVec);
5081 MinElts.push_back(EltNo);
5082 MaxElts.push_back(EltNo);
5086 // Currently only do something sane when at most two source vectors
5088 if (SourceVecs.size() > 2)
5091 SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5092 int VEXTOffsets[2] = {0, 0};
5094 // This loop extracts the usage patterns of the source vectors
5095 // and prepares appropriate SDValues for a shuffle if possible.
5096 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5097 if (SourceVecs[i].getValueType() == VT) {
5098 // No VEXT necessary
5099 ShuffleSrcs[i] = SourceVecs[i];
5102 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5103 // It probably isn't worth padding out a smaller vector just to
5104 // break it down again in a shuffle.
5108 // Since only 64-bit and 128-bit vectors are legal on ARM and
5109 // we've eliminated the other cases...
5110 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5111 "unexpected vector sizes in ReconstructShuffle");
5113 if (MaxElts[i] - MinElts[i] >= NumElts) {
5114 // Span too large for a VEXT to cope
5118 if (MinElts[i] >= NumElts) {
5119 // The extraction can just take the second half
5120 VEXTOffsets[i] = NumElts;
5121 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5123 DAG.getIntPtrConstant(NumElts));
5124 } else if (MaxElts[i] < NumElts) {
5125 // The extraction can just take the first half
5127 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5129 DAG.getIntPtrConstant(0));
5131 // An actual VEXT is needed
5132 VEXTOffsets[i] = MinElts[i];
5133 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5135 DAG.getIntPtrConstant(0));
5136 SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5138 DAG.getIntPtrConstant(NumElts));
5139 ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5140 DAG.getConstant(VEXTOffsets[i], MVT::i32));
5144 SmallVector<int, 8> Mask;
5146 for (unsigned i = 0; i < NumElts; ++i) {
5147 SDValue Entry = Op.getOperand(i);
5148 if (Entry.getOpcode() == ISD::UNDEF) {
5153 SDValue ExtractVec = Entry.getOperand(0);
5154 int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5155 .getOperand(1))->getSExtValue();
5156 if (ExtractVec == SourceVecs[0]) {
5157 Mask.push_back(ExtractElt - VEXTOffsets[0]);
5159 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5163 // Final check before we try to produce nonsense...
5164 if (isShuffleMaskLegal(Mask, VT))
5165 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5171 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5172 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5173 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5174 /// are assumed to be legal.
5176 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5178 if (VT.getVectorNumElements() == 4 &&
5179 (VT.is128BitVector() || VT.is64BitVector())) {
5180 unsigned PFIndexes[4];
5181 for (unsigned i = 0; i != 4; ++i) {
5185 PFIndexes[i] = M[i];
5188 // Compute the index in the perfect shuffle table.
5189 unsigned PFTableIndex =
5190 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5191 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5192 unsigned Cost = (PFEntry >> 30);
5199 unsigned Imm, WhichResult;
5201 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5202 return (EltSize >= 32 ||
5203 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5204 isVREVMask(M, VT, 64) ||
5205 isVREVMask(M, VT, 32) ||
5206 isVREVMask(M, VT, 16) ||
5207 isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5208 isVTBLMask(M, VT) ||
5209 isVTRNMask(M, VT, WhichResult) ||
5210 isVUZPMask(M, VT, WhichResult) ||
5211 isVZIPMask(M, VT, WhichResult) ||
5212 isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5213 isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5214 isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5215 ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5218 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5219 /// the specified operations to build the shuffle.
5220 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5221 SDValue RHS, SelectionDAG &DAG,
5223 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5224 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5225 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5228 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5237 OP_VUZPL, // VUZP, left result
5238 OP_VUZPR, // VUZP, right result
5239 OP_VZIPL, // VZIP, left result
5240 OP_VZIPR, // VZIP, right result
5241 OP_VTRNL, // VTRN, left result
5242 OP_VTRNR // VTRN, right result
5245 if (OpNum == OP_COPY) {
5246 if (LHSID == (1*9+2)*9+3) return LHS;
5247 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5251 SDValue OpLHS, OpRHS;
5252 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5253 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5254 EVT VT = OpLHS.getValueType();
5257 default: llvm_unreachable("Unknown shuffle opcode!");
5259 // VREV divides the vector in half and swaps within the half.
5260 if (VT.getVectorElementType() == MVT::i32 ||
5261 VT.getVectorElementType() == MVT::f32)
5262 return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5263 // vrev <4 x i16> -> VREV32
5264 if (VT.getVectorElementType() == MVT::i16)
5265 return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5266 // vrev <4 x i8> -> VREV16
5267 assert(VT.getVectorElementType() == MVT::i8);
5268 return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5273 return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5274 OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5278 return DAG.getNode(ARMISD::VEXT, dl, VT,
5280 DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5283 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5284 OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5287 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5288 OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5291 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5292 OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5296 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5297 ArrayRef<int> ShuffleMask,
5298 SelectionDAG &DAG) {
5299 // Check to see if we can use the VTBL instruction.
5300 SDValue V1 = Op.getOperand(0);
5301 SDValue V2 = Op.getOperand(1);
5304 SmallVector<SDValue, 8> VTBLMask;
5305 for (ArrayRef<int>::iterator
5306 I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5307 VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5309 if (V2.getNode()->getOpcode() == ISD::UNDEF)
5310 return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5311 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5314 return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5315 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5319 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5320 SelectionDAG &DAG) {
5322 SDValue OpLHS = Op.getOperand(0);
5323 EVT VT = OpLHS.getValueType();
5325 assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5326 "Expect an v8i16/v16i8 type");
5327 OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5328 // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5329 // extract the first 8 bytes into the top double word and the last 8 bytes
5330 // into the bottom double word. The v8i16 case is similar.
5331 unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5332 return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5333 DAG.getConstant(ExtractNum, MVT::i32));
5336 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5337 SDValue V1 = Op.getOperand(0);
5338 SDValue V2 = Op.getOperand(1);
5340 EVT VT = Op.getValueType();
5341 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5343 // Convert shuffles that are directly supported on NEON to target-specific
5344 // DAG nodes, instead of keeping them as shuffles and matching them again
5345 // during code selection. This is more efficient and avoids the possibility
5346 // of inconsistencies between legalization and selection.
5347 // FIXME: floating-point vectors should be canonicalized to integer vectors
5348 // of the same time so that they get CSEd properly.
5349 ArrayRef<int> ShuffleMask = SVN->getMask();
5351 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5352 if (EltSize <= 32) {
5353 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5354 int Lane = SVN->getSplatIndex();
5355 // If this is undef splat, generate it via "just" vdup, if possible.
5356 if (Lane == -1) Lane = 0;
5358 // Test if V1 is a SCALAR_TO_VECTOR.
5359 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5360 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5362 // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5363 // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5365 if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5366 !isa<ConstantSDNode>(V1.getOperand(0))) {
5367 bool IsScalarToVector = true;
5368 for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5369 if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5370 IsScalarToVector = false;
5373 if (IsScalarToVector)
5374 return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5376 return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5377 DAG.getConstant(Lane, MVT::i32));
5382 if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5385 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5386 DAG.getConstant(Imm, MVT::i32));
5389 if (isVREVMask(ShuffleMask, VT, 64))
5390 return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5391 if (isVREVMask(ShuffleMask, VT, 32))
5392 return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5393 if (isVREVMask(ShuffleMask, VT, 16))
5394 return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5396 if (V2->getOpcode() == ISD::UNDEF &&
5397 isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5398 return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5399 DAG.getConstant(Imm, MVT::i32));
5402 // Check for Neon shuffles that modify both input vectors in place.
5403 // If both results are used, i.e., if there are two shuffles with the same
5404 // source operands and with masks corresponding to both results of one of
5405 // these operations, DAG memoization will ensure that a single node is
5406 // used for both shuffles.
5407 unsigned WhichResult;
5408 if (isVTRNMask(ShuffleMask, VT, WhichResult))
5409 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5410 V1, V2).getValue(WhichResult);
5411 if (isVUZPMask(ShuffleMask, VT, WhichResult))
5412 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5413 V1, V2).getValue(WhichResult);
5414 if (isVZIPMask(ShuffleMask, VT, WhichResult))
5415 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5416 V1, V2).getValue(WhichResult);
5418 if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5419 return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5420 V1, V1).getValue(WhichResult);
5421 if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5422 return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5423 V1, V1).getValue(WhichResult);
5424 if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5425 return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5426 V1, V1).getValue(WhichResult);
5429 // If the shuffle is not directly supported and it has 4 elements, use
5430 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5431 unsigned NumElts = VT.getVectorNumElements();
5433 unsigned PFIndexes[4];
5434 for (unsigned i = 0; i != 4; ++i) {
5435 if (ShuffleMask[i] < 0)
5438 PFIndexes[i] = ShuffleMask[i];
5441 // Compute the index in the perfect shuffle table.
5442 unsigned PFTableIndex =
5443 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5444 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5445 unsigned Cost = (PFEntry >> 30);
5448 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5451 // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5452 if (EltSize >= 32) {
5453 // Do the expansion with floating-point types, since that is what the VFP
5454 // registers are defined to use, and since i64 is not legal.
5455 EVT EltVT = EVT::getFloatingPointVT(EltSize);
5456 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5457 V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5458 V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5459 SmallVector<SDValue, 8> Ops;
5460 for (unsigned i = 0; i < NumElts; ++i) {
5461 if (ShuffleMask[i] < 0)
5462 Ops.push_back(DAG.getUNDEF(EltVT));
5464 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5465 ShuffleMask[i] < (int)NumElts ? V1 : V2,
5466 DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5469 SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5470 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5473 if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5474 return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5476 if (VT == MVT::v8i8) {
5477 SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5478 if (NewOp.getNode())
5485 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5486 // INSERT_VECTOR_ELT is legal only for immediate indexes.
5487 SDValue Lane = Op.getOperand(2);
5488 if (!isa<ConstantSDNode>(Lane))
5494 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5495 // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5496 SDValue Lane = Op.getOperand(1);
5497 if (!isa<ConstantSDNode>(Lane))
5500 SDValue Vec = Op.getOperand(0);
5501 if (Op.getValueType() == MVT::i32 &&
5502 Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5504 return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5510 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5511 // The only time a CONCAT_VECTORS operation can have legal types is when
5512 // two 64-bit vectors are concatenated to a 128-bit vector.
5513 assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5514 "unexpected CONCAT_VECTORS");
5516 SDValue Val = DAG.getUNDEF(MVT::v2f64);
5517 SDValue Op0 = Op.getOperand(0);
5518 SDValue Op1 = Op.getOperand(1);
5519 if (Op0.getOpcode() != ISD::UNDEF)
5520 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5521 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5522 DAG.getIntPtrConstant(0));
5523 if (Op1.getOpcode() != ISD::UNDEF)
5524 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5525 DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5526 DAG.getIntPtrConstant(1));
5527 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5530 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5531 /// element has been zero/sign-extended, depending on the isSigned parameter,
5532 /// from an integer type half its size.
5533 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5535 // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5536 EVT VT = N->getValueType(0);
5537 if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5538 SDNode *BVN = N->getOperand(0).getNode();
5539 if (BVN->getValueType(0) != MVT::v4i32 ||
5540 BVN->getOpcode() != ISD::BUILD_VECTOR)
5542 unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5543 unsigned HiElt = 1 - LoElt;
5544 ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5545 ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5546 ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5547 ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5548 if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5551 if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5552 Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5555 if (Hi0->isNullValue() && Hi1->isNullValue())
5561 if (N->getOpcode() != ISD::BUILD_VECTOR)
5564 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5565 SDNode *Elt = N->getOperand(i).getNode();
5566 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5567 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5568 unsigned HalfSize = EltSize / 2;
5570 if (!isIntN(HalfSize, C->getSExtValue()))
5573 if (!isUIntN(HalfSize, C->getZExtValue()))
5584 /// isSignExtended - Check if a node is a vector value that is sign-extended
5585 /// or a constant BUILD_VECTOR with sign-extended elements.
5586 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5587 if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5589 if (isExtendedBUILD_VECTOR(N, DAG, true))
5594 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5595 /// or a constant BUILD_VECTOR with zero-extended elements.
5596 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5597 if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5599 if (isExtendedBUILD_VECTOR(N, DAG, false))
5604 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5605 if (OrigVT.getSizeInBits() >= 64)
5608 assert(OrigVT.isSimple() && "Expecting a simple value type");
5610 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5611 switch (OrigSimpleTy) {
5612 default: llvm_unreachable("Unexpected Vector Type");
5621 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5622 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5623 /// We insert the required extension here to get the vector to fill a D register.
5624 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5627 unsigned ExtOpcode) {
5628 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5629 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5630 // 64-bits we need to insert a new extension so that it will be 64-bits.
5631 assert(ExtTy.is128BitVector() && "Unexpected extension size");
5632 if (OrigTy.getSizeInBits() >= 64)
5635 // Must extend size to at least 64 bits to be used as an operand for VMULL.
5636 EVT NewVT = getExtensionTo64Bits(OrigTy);
5638 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5641 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5642 /// does not do any sign/zero extension. If the original vector is less
5643 /// than 64 bits, an appropriate extension will be added after the load to
5644 /// reach a total size of 64 bits. We have to add the extension separately
5645 /// because ARM does not have a sign/zero extending load for vectors.
5646 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5647 EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5649 // The load already has the right type.
5650 if (ExtendedTy == LD->getMemoryVT())
5651 return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5652 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5653 LD->isNonTemporal(), LD->isInvariant(),
5654 LD->getAlignment());
5656 // We need to create a zextload/sextload. We cannot just create a load
5657 // followed by a zext/zext node because LowerMUL is also run during normal
5658 // operation legalization where we can't create illegal types.
5659 return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5660 LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5661 LD->getMemoryVT(), LD->isVolatile(),
5662 LD->isNonTemporal(), LD->getAlignment());
5665 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5666 /// extending load, or BUILD_VECTOR with extended elements, return the
5667 /// unextended value. The unextended vector should be 64 bits so that it can
5668 /// be used as an operand to a VMULL instruction. If the original vector size
5669 /// before extension is less than 64 bits we add a an extension to resize
5670 /// the vector to 64 bits.
5671 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5672 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5673 return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5674 N->getOperand(0)->getValueType(0),
5678 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5679 return SkipLoadExtensionForVMULL(LD, DAG);
5681 // Otherwise, the value must be a BUILD_VECTOR. For v2i64, it will
5682 // have been legalized as a BITCAST from v4i32.
5683 if (N->getOpcode() == ISD::BITCAST) {
5684 SDNode *BVN = N->getOperand(0).getNode();
5685 assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5686 BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5687 unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5688 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5689 BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5691 // Construct a new BUILD_VECTOR with elements truncated to half the size.
5692 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5693 EVT VT = N->getValueType(0);
5694 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5695 unsigned NumElts = VT.getVectorNumElements();
5696 MVT TruncVT = MVT::getIntegerVT(EltSize);
5697 SmallVector<SDValue, 8> Ops;
5698 for (unsigned i = 0; i != NumElts; ++i) {
5699 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5700 const APInt &CInt = C->getAPIntValue();
5701 // Element types smaller than 32 bits are not legal, so use i32 elements.
5702 // The values are implicitly truncated so sext vs. zext doesn't matter.
5703 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5705 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5706 MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5709 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5710 unsigned Opcode = N->getOpcode();
5711 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5712 SDNode *N0 = N->getOperand(0).getNode();
5713 SDNode *N1 = N->getOperand(1).getNode();
5714 return N0->hasOneUse() && N1->hasOneUse() &&
5715 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5720 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5721 unsigned Opcode = N->getOpcode();
5722 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5723 SDNode *N0 = N->getOperand(0).getNode();
5724 SDNode *N1 = N->getOperand(1).getNode();
5725 return N0->hasOneUse() && N1->hasOneUse() &&
5726 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5731 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5732 // Multiplications are only custom-lowered for 128-bit vectors so that
5733 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
5734 EVT VT = Op.getValueType();
5735 assert(VT.is128BitVector() && VT.isInteger() &&
5736 "unexpected type for custom-lowering ISD::MUL");
5737 SDNode *N0 = Op.getOperand(0).getNode();
5738 SDNode *N1 = Op.getOperand(1).getNode();
5739 unsigned NewOpc = 0;
5741 bool isN0SExt = isSignExtended(N0, DAG);
5742 bool isN1SExt = isSignExtended(N1, DAG);
5743 if (isN0SExt && isN1SExt)
5744 NewOpc = ARMISD::VMULLs;
5746 bool isN0ZExt = isZeroExtended(N0, DAG);
5747 bool isN1ZExt = isZeroExtended(N1, DAG);
5748 if (isN0ZExt && isN1ZExt)
5749 NewOpc = ARMISD::VMULLu;
5750 else if (isN1SExt || isN1ZExt) {
5751 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5752 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5753 if (isN1SExt && isAddSubSExt(N0, DAG)) {
5754 NewOpc = ARMISD::VMULLs;
5756 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5757 NewOpc = ARMISD::VMULLu;
5759 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5761 NewOpc = ARMISD::VMULLu;
5767 if (VT == MVT::v2i64)
5768 // Fall through to expand this. It is not legal.
5771 // Other vector multiplications are legal.
5776 // Legalize to a VMULL instruction.
5779 SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5781 Op0 = SkipExtensionForVMULL(N0, DAG);
5782 assert(Op0.getValueType().is64BitVector() &&
5783 Op1.getValueType().is64BitVector() &&
5784 "unexpected types for extended operands to VMULL");
5785 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5788 // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5789 // isel lowering to take advantage of no-stall back to back vmul + vmla.
5796 SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5797 SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5798 EVT Op1VT = Op1.getValueType();
5799 return DAG.getNode(N0->getOpcode(), DL, VT,
5800 DAG.getNode(NewOpc, DL, VT,
5801 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5802 DAG.getNode(NewOpc, DL, VT,
5803 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5807 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5809 // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5810 // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5811 X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5812 Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5813 X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5814 Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5815 // Get reciprocal estimate.
5816 // float4 recip = vrecpeq_f32(yf);
5817 Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5818 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5819 // Because char has a smaller range than uchar, we can actually get away
5820 // without any newton steps. This requires that we use a weird bias
5821 // of 0xb000, however (again, this has been exhaustively tested).
5822 // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5823 X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5824 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5825 Y = DAG.getConstant(0xb000, MVT::i32);
5826 Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5827 X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5828 X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5829 // Convert back to short.
5830 X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5831 X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5836 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5838 // Convert to float.
5839 // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5840 // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5841 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5842 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5843 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5844 N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5846 // Use reciprocal estimate and one refinement step.
5847 // float4 recip = vrecpeq_f32(yf);
5848 // recip *= vrecpsq_f32(yf, recip);
5849 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5850 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5851 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5852 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5854 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5855 // Because short has a smaller range than ushort, we can actually get away
5856 // with only a single newton step. This requires that we use a weird bias
5857 // of 89, however (again, this has been exhaustively tested).
5858 // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5859 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5860 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5861 N1 = DAG.getConstant(0x89, MVT::i32);
5862 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5863 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5864 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5865 // Convert back to integer and return.
5866 // return vmovn_s32(vcvt_s32_f32(result));
5867 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5868 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5872 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5873 EVT VT = Op.getValueType();
5874 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5875 "unexpected type for custom-lowering ISD::SDIV");
5878 SDValue N0 = Op.getOperand(0);
5879 SDValue N1 = Op.getOperand(1);
5882 if (VT == MVT::v8i8) {
5883 N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5884 N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5886 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5887 DAG.getIntPtrConstant(4));
5888 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5889 DAG.getIntPtrConstant(4));
5890 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5891 DAG.getIntPtrConstant(0));
5892 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5893 DAG.getIntPtrConstant(0));
5895 N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5896 N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5898 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5899 N0 = LowerCONCAT_VECTORS(N0, DAG);
5901 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5904 return LowerSDIV_v4i16(N0, N1, dl, DAG);
5907 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5908 EVT VT = Op.getValueType();
5909 assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5910 "unexpected type for custom-lowering ISD::UDIV");
5913 SDValue N0 = Op.getOperand(0);
5914 SDValue N1 = Op.getOperand(1);
5917 if (VT == MVT::v8i8) {
5918 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5919 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5921 N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5922 DAG.getIntPtrConstant(4));
5923 N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5924 DAG.getIntPtrConstant(4));
5925 N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5926 DAG.getIntPtrConstant(0));
5927 N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5928 DAG.getIntPtrConstant(0));
5930 N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5931 N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5933 N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5934 N0 = LowerCONCAT_VECTORS(N0, DAG);
5936 N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5937 DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5942 // v4i16 sdiv ... Convert to float.
5943 // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5944 // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5945 N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5946 N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5947 N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5948 SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5950 // Use reciprocal estimate and two refinement steps.
5951 // float4 recip = vrecpeq_f32(yf);
5952 // recip *= vrecpsq_f32(yf, recip);
5953 // recip *= vrecpsq_f32(yf, recip);
5954 N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5955 DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5956 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5957 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5959 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5960 N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5961 DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5963 N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5964 // Simply multiplying by the reciprocal estimate can leave us a few ulps
5965 // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5966 // and that it will never cause us to return an answer too large).
5967 // float4 result = as_float4(as_int4(xf*recip) + 2);
5968 N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5969 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5970 N1 = DAG.getConstant(2, MVT::i32);
5971 N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5972 N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5973 N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5974 // Convert back to integer and return.
5975 // return vmovn_u32(vcvt_s32_f32(result));
5976 N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5977 N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5981 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5982 EVT VT = Op.getNode()->getValueType(0);
5983 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5986 bool ExtraOp = false;
5987 switch (Op.getOpcode()) {
5988 default: llvm_unreachable("Invalid code");
5989 case ISD::ADDC: Opc = ARMISD::ADDC; break;
5990 case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5991 case ISD::SUBC: Opc = ARMISD::SUBC; break;
5992 case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5996 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5998 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5999 Op.getOperand(1), Op.getOperand(2));
6002 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6003 // Monotonic load/store is legal for all targets
6004 if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6007 // Aquire/Release load/store is not legal for targets without a
6008 // dmb or equivalent available.
6013 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6014 SelectionDAG &DAG) {
6016 assert (Node->getValueType(0) == MVT::i64 &&
6017 "Only know how to expand i64 atomics");
6018 AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6020 SmallVector<SDValue, 6> Ops;
6021 Ops.push_back(Node->getOperand(0)); // Chain
6022 Ops.push_back(Node->getOperand(1)); // Ptr
6023 for(unsigned i=2; i<Node->getNumOperands(); i++) {
6025 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6026 Node->getOperand(i), DAG.getIntPtrConstant(0)));
6028 Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6029 Node->getOperand(i), DAG.getIntPtrConstant(1)));
6031 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6033 DAG.getAtomic(Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6034 cast<MemSDNode>(Node)->getMemOperand(), AN->getOrdering(),
6035 AN->getSynchScope());
6036 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6037 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6038 Results.push_back(Result.getValue(2));
6041 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6042 SmallVectorImpl<SDValue> &Results,
6044 const ARMSubtarget *Subtarget) {
6046 SDValue Cycles32, OutChain;
6048 if (Subtarget->hasPerfMon()) {
6049 // Under Power Management extensions, the cycle-count is:
6050 // mrc p15, #0, <Rt>, c9, c13, #0
6051 SDValue Ops[] = { N->getOperand(0), // Chain
6052 DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6053 DAG.getConstant(15, MVT::i32),
6054 DAG.getConstant(0, MVT::i32),
6055 DAG.getConstant(9, MVT::i32),
6056 DAG.getConstant(13, MVT::i32),
6057 DAG.getConstant(0, MVT::i32)
6060 Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6061 DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6062 array_lengthof(Ops));
6063 OutChain = Cycles32.getValue(1);
6065 // Intrinsic is defined to return 0 on unsupported platforms. Technically
6066 // there are older ARM CPUs that have implementation-specific ways of
6067 // obtaining this information (FIXME!).
6068 Cycles32 = DAG.getConstant(0, MVT::i32);
6069 OutChain = DAG.getEntryNode();
6073 SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6074 Cycles32, DAG.getConstant(0, MVT::i32));
6075 Results.push_back(Cycles64);
6076 Results.push_back(OutChain);
6079 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6080 switch (Op.getOpcode()) {
6081 default: llvm_unreachable("Don't know how to custom lower this!");
6082 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6083 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6084 case ISD::GlobalAddress:
6085 return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
6086 LowerGlobalAddressELF(Op, DAG);
6087 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6088 case ISD::SELECT: return LowerSELECT(Op, DAG);
6089 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6090 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
6091 case ISD::BR_JT: return LowerBR_JT(Op, DAG);
6092 case ISD::VASTART: return LowerVASTART(Op, DAG);
6093 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6094 case ISD::PREFETCH: return LowerPREFETCH(Op, DAG, Subtarget);
6095 case ISD::SINT_TO_FP:
6096 case ISD::UINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6097 case ISD::FP_TO_SINT:
6098 case ISD::FP_TO_UINT: return LowerFP_TO_INT(Op, DAG);
6099 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6100 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6101 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6102 case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6103 case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6104 case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6105 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6107 case ISD::BITCAST: return ExpandBITCAST(Op.getNode(), DAG);
6110 case ISD::SRA: return LowerShift(Op.getNode(), DAG, Subtarget);
6111 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
6112 case ISD::SRL_PARTS:
6113 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG);
6114 case ISD::CTTZ: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6115 case ISD::CTPOP: return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6116 case ISD::SETCC: return LowerVSETCC(Op, DAG);
6117 case ISD::ConstantFP: return LowerConstantFP(Op, DAG, Subtarget);
6118 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6119 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6120 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6121 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6122 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6123 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6124 case ISD::MUL: return LowerMUL(Op, DAG);
6125 case ISD::SDIV: return LowerSDIV(Op, DAG);
6126 case ISD::UDIV: return LowerUDIV(Op, DAG);
6130 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6131 case ISD::ATOMIC_LOAD:
6132 case ISD::ATOMIC_STORE: return LowerAtomicLoadStore(Op, DAG);
6134 case ISD::UDIVREM: return LowerDivRem(Op, DAG);
6138 /// ReplaceNodeResults - Replace the results of node with an illegal result
6139 /// type with new values built out of custom code.
6140 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6141 SmallVectorImpl<SDValue>&Results,
6142 SelectionDAG &DAG) const {
6144 switch (N->getOpcode()) {
6146 llvm_unreachable("Don't know how to custom expand this!");
6148 Res = ExpandBITCAST(N, DAG);
6150 case ISD::SIGN_EXTEND:
6151 case ISD::ZERO_EXTEND:
6152 Res = ExpandVectorExtension(N, DAG);
6156 Res = Expand64BitShift(N, DAG, Subtarget);
6158 case ISD::READCYCLECOUNTER:
6159 ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6161 case ISD::ATOMIC_STORE:
6162 case ISD::ATOMIC_LOAD:
6163 case ISD::ATOMIC_LOAD_ADD:
6164 case ISD::ATOMIC_LOAD_AND:
6165 case ISD::ATOMIC_LOAD_NAND:
6166 case ISD::ATOMIC_LOAD_OR:
6167 case ISD::ATOMIC_LOAD_SUB:
6168 case ISD::ATOMIC_LOAD_XOR:
6169 case ISD::ATOMIC_SWAP:
6170 case ISD::ATOMIC_CMP_SWAP:
6171 case ISD::ATOMIC_LOAD_MIN:
6172 case ISD::ATOMIC_LOAD_UMIN:
6173 case ISD::ATOMIC_LOAD_MAX:
6174 case ISD::ATOMIC_LOAD_UMAX:
6175 ReplaceATOMIC_OP_64(N, Results, DAG);
6179 Results.push_back(Res);
6182 //===----------------------------------------------------------------------===//
6183 // ARM Scheduler Hooks
6184 //===----------------------------------------------------------------------===//
6187 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6188 MachineBasicBlock *BB,
6189 unsigned Size) const {
6190 unsigned dest = MI->getOperand(0).getReg();
6191 unsigned ptr = MI->getOperand(1).getReg();
6192 unsigned oldval = MI->getOperand(2).getReg();
6193 unsigned newval = MI->getOperand(3).getReg();
6194 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6195 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6196 DebugLoc dl = MI->getDebugLoc();
6197 bool isThumb2 = Subtarget->isThumb2();
6199 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6200 unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6201 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6202 (const TargetRegisterClass*)&ARM::GPRRegClass);
6205 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6206 MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6207 MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6210 unsigned ldrOpc, strOpc;
6211 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6213 MachineFunction *MF = BB->getParent();
6214 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6215 MachineFunction::iterator It = BB;
6216 ++It; // insert the new blocks after the current block
6218 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6219 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6220 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6221 MF->insert(It, loop1MBB);
6222 MF->insert(It, loop2MBB);
6223 MF->insert(It, exitMBB);
6225 // Transfer the remainder of BB and its successor edges to exitMBB.
6226 exitMBB->splice(exitMBB->begin(), BB,
6227 llvm::next(MachineBasicBlock::iterator(MI)),
6229 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6233 // fallthrough --> loop1MBB
6234 BB->addSuccessor(loop1MBB);
6237 // ldrex dest, [ptr]
6241 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6242 if (ldrOpc == ARM::t2LDREX)
6244 AddDefaultPred(MIB);
6245 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6246 .addReg(dest).addReg(oldval));
6247 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6248 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6249 BB->addSuccessor(loop2MBB);
6250 BB->addSuccessor(exitMBB);
6253 // strex scratch, newval, [ptr]
6257 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6258 if (strOpc == ARM::t2STREX)
6260 AddDefaultPred(MIB);
6261 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6262 .addReg(scratch).addImm(0));
6263 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6264 .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6265 BB->addSuccessor(loop1MBB);
6266 BB->addSuccessor(exitMBB);
6272 MI->eraseFromParent(); // The instruction is gone now.
6278 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6279 unsigned Size, unsigned BinOpcode) const {
6280 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6281 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6283 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6284 MachineFunction *MF = BB->getParent();
6285 MachineFunction::iterator It = BB;
6288 unsigned dest = MI->getOperand(0).getReg();
6289 unsigned ptr = MI->getOperand(1).getReg();
6290 unsigned incr = MI->getOperand(2).getReg();
6291 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6292 DebugLoc dl = MI->getDebugLoc();
6293 bool isThumb2 = Subtarget->isThumb2();
6295 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6297 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6298 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6299 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6302 unsigned ldrOpc, strOpc;
6303 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6305 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6306 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6307 MF->insert(It, loopMBB);
6308 MF->insert(It, exitMBB);
6310 // Transfer the remainder of BB and its successor edges to exitMBB.
6311 exitMBB->splice(exitMBB->begin(), BB,
6312 llvm::next(MachineBasicBlock::iterator(MI)),
6314 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6316 const TargetRegisterClass *TRC = isThumb2 ?
6317 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6318 (const TargetRegisterClass*)&ARM::GPRRegClass;
6319 unsigned scratch = MRI.createVirtualRegister(TRC);
6320 unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6324 // fallthrough --> loopMBB
6325 BB->addSuccessor(loopMBB);
6329 // <binop> scratch2, dest, incr
6330 // strex scratch, scratch2, ptr
6333 // fallthrough --> exitMBB
6335 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6336 if (ldrOpc == ARM::t2LDREX)
6338 AddDefaultPred(MIB);
6340 // operand order needs to go the other way for NAND
6341 if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6342 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6343 addReg(incr).addReg(dest)).addReg(0);
6345 AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6346 addReg(dest).addReg(incr)).addReg(0);
6349 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6350 if (strOpc == ARM::t2STREX)
6352 AddDefaultPred(MIB);
6353 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6354 .addReg(scratch).addImm(0));
6355 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6356 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6358 BB->addSuccessor(loopMBB);
6359 BB->addSuccessor(exitMBB);
6365 MI->eraseFromParent(); // The instruction is gone now.
6371 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6372 MachineBasicBlock *BB,
6375 ARMCC::CondCodes Cond) const {
6376 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6378 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6379 MachineFunction *MF = BB->getParent();
6380 MachineFunction::iterator It = BB;
6383 unsigned dest = MI->getOperand(0).getReg();
6384 unsigned ptr = MI->getOperand(1).getReg();
6385 unsigned incr = MI->getOperand(2).getReg();
6386 unsigned oldval = dest;
6387 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6388 DebugLoc dl = MI->getDebugLoc();
6389 bool isThumb2 = Subtarget->isThumb2();
6391 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6393 MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6394 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6395 MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6398 unsigned ldrOpc, strOpc, extendOpc;
6399 getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6401 default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6403 extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6406 extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6413 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6414 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6415 MF->insert(It, loopMBB);
6416 MF->insert(It, exitMBB);
6418 // Transfer the remainder of BB and its successor edges to exitMBB.
6419 exitMBB->splice(exitMBB->begin(), BB,
6420 llvm::next(MachineBasicBlock::iterator(MI)),
6422 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6424 const TargetRegisterClass *TRC = isThumb2 ?
6425 (const TargetRegisterClass*)&ARM::rGPRRegClass :
6426 (const TargetRegisterClass*)&ARM::GPRRegClass;
6427 unsigned scratch = MRI.createVirtualRegister(TRC);
6428 unsigned scratch2 = MRI.createVirtualRegister(TRC);
6432 // fallthrough --> loopMBB
6433 BB->addSuccessor(loopMBB);
6437 // (sign extend dest, if required)
6439 // cmov.cond scratch2, incr, dest
6440 // strex scratch, scratch2, ptr
6443 // fallthrough --> exitMBB
6445 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6446 if (ldrOpc == ARM::t2LDREX)
6448 AddDefaultPred(MIB);
6450 // Sign extend the value, if necessary.
6451 if (signExtend && extendOpc) {
6452 oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6453 : &ARM::GPRnopcRegClass);
6455 MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6456 AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6461 // Build compare and cmov instructions.
6462 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6463 .addReg(oldval).addReg(incr));
6464 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6465 .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6467 MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6468 if (strOpc == ARM::t2STREX)
6470 AddDefaultPred(MIB);
6471 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6472 .addReg(scratch).addImm(0));
6473 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6474 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6476 BB->addSuccessor(loopMBB);
6477 BB->addSuccessor(exitMBB);
6483 MI->eraseFromParent(); // The instruction is gone now.
6489 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6490 unsigned Op1, unsigned Op2,
6491 bool NeedsCarry, bool IsCmpxchg,
6492 bool IsMinMax, ARMCC::CondCodes CC) const {
6493 // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6494 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6496 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6497 MachineFunction *MF = BB->getParent();
6498 MachineFunction::iterator It = BB;
6501 bool isStore = (MI->getOpcode() == ARM::ATOMIC_STORE_I64);
6502 unsigned offset = (isStore ? -2 : 0);
6503 unsigned destlo = MI->getOperand(0).getReg();
6504 unsigned desthi = MI->getOperand(1).getReg();
6505 unsigned ptr = MI->getOperand(offset+2).getReg();
6506 unsigned vallo = MI->getOperand(offset+3).getReg();
6507 unsigned valhi = MI->getOperand(offset+4).getReg();
6508 unsigned OrdIdx = offset + (IsCmpxchg ? 7 : 5);
6509 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(OrdIdx).getImm());
6510 DebugLoc dl = MI->getDebugLoc();
6511 bool isThumb2 = Subtarget->isThumb2();
6513 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6515 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6516 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6517 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6518 MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6519 MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6522 unsigned ldrOpc, strOpc;
6523 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6525 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6526 MachineBasicBlock *contBB = 0, *cont2BB = 0;
6527 if (IsCmpxchg || IsMinMax)
6528 contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6530 cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6531 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6533 MF->insert(It, loopMBB);
6534 if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6535 if (IsCmpxchg) MF->insert(It, cont2BB);
6536 MF->insert(It, exitMBB);
6538 // Transfer the remainder of BB and its successor edges to exitMBB.
6539 exitMBB->splice(exitMBB->begin(), BB,
6540 llvm::next(MachineBasicBlock::iterator(MI)),
6542 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6544 const TargetRegisterClass *TRC = isThumb2 ?
6545 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6546 (const TargetRegisterClass*)&ARM::GPRRegClass;
6547 unsigned storesuccess = MRI.createVirtualRegister(TRC);
6551 // fallthrough --> loopMBB
6552 BB->addSuccessor(loopMBB);
6555 // ldrexd r2, r3, ptr
6556 // <binopa> r0, r2, incr
6557 // <binopb> r1, r3, incr
6558 // strexd storesuccess, r0, r1, ptr
6559 // cmp storesuccess, #0
6561 // fallthrough --> exitMBB
6567 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6568 .addReg(destlo, RegState::Define)
6569 .addReg(desthi, RegState::Define)
6572 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6573 AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6574 .addReg(GPRPair0, RegState::Define).addReg(ptr));
6575 // Copy r2/r3 into dest. (This copy will normally be coalesced.)
6576 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6577 .addReg(GPRPair0, 0, ARM::gsub_0);
6578 BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6579 .addReg(GPRPair0, 0, ARM::gsub_1);
6583 unsigned StoreLo, StoreHi;
6586 for (unsigned i = 0; i < 2; i++) {
6587 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6589 .addReg(i == 0 ? destlo : desthi)
6590 .addReg(i == 0 ? vallo : valhi));
6591 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6592 .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6593 BB->addSuccessor(exitMBB);
6594 BB->addSuccessor(i == 0 ? contBB : cont2BB);
6595 BB = (i == 0 ? contBB : cont2BB);
6598 // Copy to physregs for strexd
6599 StoreLo = MI->getOperand(5).getReg();
6600 StoreHi = MI->getOperand(6).getReg();
6602 // Perform binary operation
6603 unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6604 AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6605 .addReg(destlo).addReg(vallo))
6606 .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6607 unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6608 AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6609 .addReg(desthi).addReg(valhi))
6610 .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6615 // Copy to physregs for strexd
6620 // Compare and branch to exit block.
6621 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6622 .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6623 BB->addSuccessor(exitMBB);
6624 BB->addSuccessor(contBB);
6632 MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6633 MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6634 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6635 .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6637 // Marshal a pair...
6638 unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6639 unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6640 unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6641 BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6642 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6645 .addImm(ARM::gsub_0);
6646 BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6649 .addImm(ARM::gsub_1);
6652 AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6653 .addReg(StorePair).addReg(ptr));
6656 AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6657 .addReg(storesuccess).addImm(0));
6658 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6659 .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6661 BB->addSuccessor(loopMBB);
6662 BB->addSuccessor(exitMBB);
6668 MI->eraseFromParent(); // The instruction is gone now.
6674 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6676 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6678 unsigned destlo = MI->getOperand(0).getReg();
6679 unsigned desthi = MI->getOperand(1).getReg();
6680 unsigned ptr = MI->getOperand(2).getReg();
6681 AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6682 DebugLoc dl = MI->getDebugLoc();
6683 bool isThumb2 = Subtarget->isThumb2();
6685 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6687 MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6688 MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6689 MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6691 unsigned ldrOpc, strOpc;
6692 getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6694 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6697 MIB.addReg(destlo, RegState::Define)
6698 .addReg(desthi, RegState::Define)
6702 unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6703 MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6705 // Copy GPRPair0 into dest. (This copy will normally be coalesced.)
6706 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6707 .addReg(GPRPair0, 0, ARM::gsub_0);
6708 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6709 .addReg(GPRPair0, 0, ARM::gsub_1);
6711 AddDefaultPred(MIB);
6713 MI->eraseFromParent(); // The instruction is gone now.
6718 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6719 /// registers the function context.
6720 void ARMTargetLowering::
6721 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6722 MachineBasicBlock *DispatchBB, int FI) const {
6723 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6724 DebugLoc dl = MI->getDebugLoc();
6725 MachineFunction *MF = MBB->getParent();
6726 MachineRegisterInfo *MRI = &MF->getRegInfo();
6727 MachineConstantPool *MCP = MF->getConstantPool();
6728 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6729 const Function *F = MF->getFunction();
6731 bool isThumb = Subtarget->isThumb();
6732 bool isThumb2 = Subtarget->isThumb2();
6734 unsigned PCLabelId = AFI->createPICLabelUId();
6735 unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6736 ARMConstantPoolValue *CPV =
6737 ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6738 unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6740 const TargetRegisterClass *TRC = isThumb ?
6741 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6742 (const TargetRegisterClass*)&ARM::GPRRegClass;
6744 // Grab constant pool and fixed stack memory operands.
6745 MachineMemOperand *CPMMO =
6746 MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6747 MachineMemOperand::MOLoad, 4, 4);
6749 MachineMemOperand *FIMMOSt =
6750 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6751 MachineMemOperand::MOStore, 4, 4);
6753 // Load the address of the dispatch MBB into the jump buffer.
6755 // Incoming value: jbuf
6756 // ldr.n r5, LCPI1_1
6759 // str r5, [$jbuf, #+4] ; &jbuf[1]
6760 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6761 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6762 .addConstantPoolIndex(CPI)
6763 .addMemOperand(CPMMO));
6764 // Set the low bit because of thumb mode.
6765 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6767 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6768 .addReg(NewVReg1, RegState::Kill)
6770 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6771 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6772 .addReg(NewVReg2, RegState::Kill)
6774 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6775 .addReg(NewVReg3, RegState::Kill)
6777 .addImm(36) // &jbuf[1] :: pc
6778 .addMemOperand(FIMMOSt));
6779 } else if (isThumb) {
6780 // Incoming value: jbuf
6781 // ldr.n r1, LCPI1_4
6785 // add r2, $jbuf, #+4 ; &jbuf[1]
6787 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6788 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6789 .addConstantPoolIndex(CPI)
6790 .addMemOperand(CPMMO));
6791 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6792 BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6793 .addReg(NewVReg1, RegState::Kill)
6795 // Set the low bit because of thumb mode.
6796 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6797 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6798 .addReg(ARM::CPSR, RegState::Define)
6800 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6801 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6802 .addReg(ARM::CPSR, RegState::Define)
6803 .addReg(NewVReg2, RegState::Kill)
6804 .addReg(NewVReg3, RegState::Kill));
6805 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6806 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6808 .addImm(36)); // &jbuf[1] :: pc
6809 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6810 .addReg(NewVReg4, RegState::Kill)
6811 .addReg(NewVReg5, RegState::Kill)
6813 .addMemOperand(FIMMOSt));
6815 // Incoming value: jbuf
6818 // str r1, [$jbuf, #+4] ; &jbuf[1]
6819 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6820 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
6821 .addConstantPoolIndex(CPI)
6823 .addMemOperand(CPMMO));
6824 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6825 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6826 .addReg(NewVReg1, RegState::Kill)
6827 .addImm(PCLabelId));
6828 AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6829 .addReg(NewVReg2, RegState::Kill)
6831 .addImm(36) // &jbuf[1] :: pc
6832 .addMemOperand(FIMMOSt));
6836 MachineBasicBlock *ARMTargetLowering::
6837 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6838 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6839 DebugLoc dl = MI->getDebugLoc();
6840 MachineFunction *MF = MBB->getParent();
6841 MachineRegisterInfo *MRI = &MF->getRegInfo();
6842 ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6843 MachineFrameInfo *MFI = MF->getFrameInfo();
6844 int FI = MFI->getFunctionContextIndex();
6846 const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6847 (const TargetRegisterClass*)&ARM::tGPRRegClass :
6848 (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6850 // Get a mapping of the call site numbers to all of the landing pads they're
6852 DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6853 unsigned MaxCSNum = 0;
6854 MachineModuleInfo &MMI = MF->getMMI();
6855 for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6857 if (!BB->isLandingPad()) continue;
6859 // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6861 for (MachineBasicBlock::iterator
6862 II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6863 if (!II->isEHLabel()) continue;
6865 MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6866 if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6868 SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6869 for (SmallVectorImpl<unsigned>::iterator
6870 CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6871 CSI != CSE; ++CSI) {
6872 CallSiteNumToLPad[*CSI].push_back(BB);
6873 MaxCSNum = std::max(MaxCSNum, *CSI);
6879 // Get an ordered list of the machine basic blocks for the jump table.
6880 std::vector<MachineBasicBlock*> LPadList;
6881 SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6882 LPadList.reserve(CallSiteNumToLPad.size());
6883 for (unsigned I = 1; I <= MaxCSNum; ++I) {
6884 SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6885 for (SmallVectorImpl<MachineBasicBlock*>::iterator
6886 II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6887 LPadList.push_back(*II);
6888 InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6892 assert(!LPadList.empty() &&
6893 "No landing pad destinations for the dispatch jump table!");
6895 // Create the jump table and associated information.
6896 MachineJumpTableInfo *JTI =
6897 MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6898 unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6899 unsigned UId = AFI->createJumpTableUId();
6900 Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6902 // Create the MBBs for the dispatch code.
6904 // Shove the dispatch's address into the return slot in the function context.
6905 MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6906 DispatchBB->setIsLandingPad();
6908 MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6909 unsigned trap_opcode;
6910 if (Subtarget->isThumb())
6911 trap_opcode = ARM::tTRAP;
6913 trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6915 BuildMI(TrapBB, dl, TII->get(trap_opcode));
6916 DispatchBB->addSuccessor(TrapBB);
6918 MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6919 DispatchBB->addSuccessor(DispContBB);
6922 MF->insert(MF->end(), DispatchBB);
6923 MF->insert(MF->end(), DispContBB);
6924 MF->insert(MF->end(), TrapBB);
6926 // Insert code into the entry block that creates and registers the function
6928 SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6930 MachineMemOperand *FIMMOLd =
6931 MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6932 MachineMemOperand::MOLoad |
6933 MachineMemOperand::MOVolatile, 4, 4);
6935 MachineInstrBuilder MIB;
6936 MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6938 const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6939 const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6941 // Add a register mask with no preserved registers. This results in all
6942 // registers being marked as clobbered.
6943 MIB.addRegMask(RI.getNoPreservedMask());
6945 unsigned NumLPads = LPadList.size();
6946 if (Subtarget->isThumb2()) {
6947 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6948 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6951 .addMemOperand(FIMMOLd));
6953 if (NumLPads < 256) {
6954 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6956 .addImm(LPadList.size()));
6958 unsigned VReg1 = MRI->createVirtualRegister(TRC);
6959 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6960 .addImm(NumLPads & 0xFFFF));
6962 unsigned VReg2 = VReg1;
6963 if ((NumLPads & 0xFFFF0000) != 0) {
6964 VReg2 = MRI->createVirtualRegister(TRC);
6965 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6967 .addImm(NumLPads >> 16));
6970 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6975 BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6980 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6981 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6982 .addJumpTableIndex(MJTI)
6985 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6988 BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6989 .addReg(NewVReg3, RegState::Kill)
6991 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6993 BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6994 .addReg(NewVReg4, RegState::Kill)
6996 .addJumpTableIndex(MJTI)
6998 } else if (Subtarget->isThumb()) {
6999 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7000 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7003 .addMemOperand(FIMMOLd));
7005 if (NumLPads < 256) {
7006 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7010 MachineConstantPool *ConstantPool = MF->getConstantPool();
7011 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7012 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7014 // MachineConstantPool wants an explicit alignment.
7015 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7017 Align = getDataLayout()->getTypeAllocSize(C->getType());
7018 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7020 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7021 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7022 .addReg(VReg1, RegState::Define)
7023 .addConstantPoolIndex(Idx));
7024 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7029 BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7034 unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7035 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7036 .addReg(ARM::CPSR, RegState::Define)
7040 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7041 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7042 .addJumpTableIndex(MJTI)
7045 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7046 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7047 .addReg(ARM::CPSR, RegState::Define)
7048 .addReg(NewVReg2, RegState::Kill)
7051 MachineMemOperand *JTMMOLd =
7052 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7053 MachineMemOperand::MOLoad, 4, 4);
7055 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7056 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7057 .addReg(NewVReg4, RegState::Kill)
7059 .addMemOperand(JTMMOLd));
7061 unsigned NewVReg6 = NewVReg5;
7062 if (RelocM == Reloc::PIC_) {
7063 NewVReg6 = MRI->createVirtualRegister(TRC);
7064 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7065 .addReg(ARM::CPSR, RegState::Define)
7066 .addReg(NewVReg5, RegState::Kill)
7070 BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7071 .addReg(NewVReg6, RegState::Kill)
7072 .addJumpTableIndex(MJTI)
7075 unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7076 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7079 .addMemOperand(FIMMOLd));
7081 if (NumLPads < 256) {
7082 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7085 } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7086 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7087 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7088 .addImm(NumLPads & 0xFFFF));
7090 unsigned VReg2 = VReg1;
7091 if ((NumLPads & 0xFFFF0000) != 0) {
7092 VReg2 = MRI->createVirtualRegister(TRC);
7093 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7095 .addImm(NumLPads >> 16));
7098 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7102 MachineConstantPool *ConstantPool = MF->getConstantPool();
7103 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7104 const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7106 // MachineConstantPool wants an explicit alignment.
7107 unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7109 Align = getDataLayout()->getTypeAllocSize(C->getType());
7110 unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7112 unsigned VReg1 = MRI->createVirtualRegister(TRC);
7113 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7114 .addReg(VReg1, RegState::Define)
7115 .addConstantPoolIndex(Idx)
7117 AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7119 .addReg(VReg1, RegState::Kill));
7122 BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7127 unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7129 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7131 .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7132 unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7133 AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7134 .addJumpTableIndex(MJTI)
7137 MachineMemOperand *JTMMOLd =
7138 MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7139 MachineMemOperand::MOLoad, 4, 4);
7140 unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7142 BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7143 .addReg(NewVReg3, RegState::Kill)
7146 .addMemOperand(JTMMOLd));
7148 if (RelocM == Reloc::PIC_) {
7149 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7150 .addReg(NewVReg5, RegState::Kill)
7152 .addJumpTableIndex(MJTI)
7155 BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7156 .addReg(NewVReg5, RegState::Kill)
7157 .addJumpTableIndex(MJTI)
7162 // Add the jump table entries as successors to the MBB.
7163 SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7164 for (std::vector<MachineBasicBlock*>::iterator
7165 I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7166 MachineBasicBlock *CurMBB = *I;
7167 if (SeenMBBs.insert(CurMBB))
7168 DispContBB->addSuccessor(CurMBB);
7171 // N.B. the order the invoke BBs are processed in doesn't matter here.
7172 const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7173 SmallVector<MachineBasicBlock*, 64> MBBLPads;
7174 for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7175 I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7176 MachineBasicBlock *BB = *I;
7178 // Remove the landing pad successor from the invoke block and replace it
7179 // with the new dispatch block.
7180 SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7182 while (!Successors.empty()) {
7183 MachineBasicBlock *SMBB = Successors.pop_back_val();
7184 if (SMBB->isLandingPad()) {
7185 BB->removeSuccessor(SMBB);
7186 MBBLPads.push_back(SMBB);
7190 BB->addSuccessor(DispatchBB);
7192 // Find the invoke call and mark all of the callee-saved registers as
7193 // 'implicit defined' so that they're spilled. This prevents code from
7194 // moving instructions to before the EH block, where they will never be
7196 for (MachineBasicBlock::reverse_iterator
7197 II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7198 if (!II->isCall()) continue;
7200 DenseMap<unsigned, bool> DefRegs;
7201 for (MachineInstr::mop_iterator
7202 OI = II->operands_begin(), OE = II->operands_end();
7204 if (!OI->isReg()) continue;
7205 DefRegs[OI->getReg()] = true;
7208 MachineInstrBuilder MIB(*MF, &*II);
7210 for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7211 unsigned Reg = SavedRegs[i];
7212 if (Subtarget->isThumb2() &&
7213 !ARM::tGPRRegClass.contains(Reg) &&
7214 !ARM::hGPRRegClass.contains(Reg))
7216 if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7218 if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7221 MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7228 // Mark all former landing pads as non-landing pads. The dispatch is the only
7230 for (SmallVectorImpl<MachineBasicBlock*>::iterator
7231 I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7232 (*I)->setIsLandingPad(false);
7234 // The instruction is gone now.
7235 MI->eraseFromParent();
7241 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7242 for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7243 E = MBB->succ_end(); I != E; ++I)
7246 llvm_unreachable("Expecting a BB with two successors!");
7250 // This class is a helper for lowering the COPY_STRUCT_BYVAL_I32 instruction.
7251 // It defines the operations needed to lower the byval copy. We use a helper
7252 // class because the opcodes and machine instructions are different for each
7253 // subtarget, but the overall algorithm for the lowering is the same. The
7254 // implementation of each operation will be defined separately for arm, thumb1,
7255 // and thumb2 targets by subclassing this base class. See
7256 // ARMTargetLowering::EmitStructByval() for how these operations are used.
7257 class TargetStructByvalEmitter {
7259 TargetStructByvalEmitter(const TargetInstrInfo *TII_,
7260 MachineRegisterInfo &MRI_,
7261 const TargetRegisterClass *TRC_)
7262 : TII(TII_), MRI(MRI_), TRC(TRC_) {}
7264 // Emit a post-increment load of "unit" size. The unit size is based on the
7265 // alignment of the struct being copied (4, 2, or 1 bytes). Alignments higher
7266 // than 4 are handled separately by using NEON instructions.
7268 // \param baseReg the register holding the address to load.
7269 // \param baseOut the register to recieve the incremented address.
7270 // \returns the register holding the loaded value.
7271 virtual unsigned emitUnitLoad(MachineBasicBlock *BB, MachineInstr *MI,
7272 DebugLoc &dl, unsigned baseReg,
7273 unsigned baseOut) = 0;
7275 // Emit a post-increment store of "unit" size. The unit size is based on the
7276 // alignment of the struct being copied (4, 2, or 1 bytes). Alignments higher
7277 // than 4 are handled separately by using NEON instructions.
7279 // \param baseReg the register holding the address to store.
7280 // \param storeReg the register holding the value to store.
7281 // \param baseOut the register to recieve the incremented address.
7282 virtual void emitUnitStore(MachineBasicBlock *BB, MachineInstr *MI,
7283 DebugLoc &dl, unsigned baseReg, unsigned storeReg,
7284 unsigned baseOut) = 0;
7286 // Emit a post-increment load of one byte.
7288 // \param baseReg the register holding the address to load.
7289 // \param baseOut the register to recieve the incremented address.
7290 // \returns the register holding the loaded value.
7291 virtual unsigned emitByteLoad(MachineBasicBlock *BB, MachineInstr *MI,
7292 DebugLoc &dl, unsigned baseReg,
7293 unsigned baseOut) = 0;
7295 // Emit a post-increment store of one byte.
7297 // \param baseReg the register holding the address to store.
7298 // \param storeReg the register holding the value to store.
7299 // \param baseOut the register to recieve the incremented address.
7300 virtual void emitByteStore(MachineBasicBlock *BB, MachineInstr *MI,
7301 DebugLoc &dl, unsigned baseReg, unsigned storeReg,
7302 unsigned baseOut) = 0;
7304 // Emit a load of a constant value.
7306 // \param Constant the register holding the address to store.
7307 // \returns the register holding the loaded value.
7308 virtual unsigned emitConstantLoad(MachineBasicBlock *BB, MachineInstr *MI,
7309 DebugLoc &dl, unsigned Constant,
7310 const DataLayout *DL) = 0;
7312 // Emit a subtract of a register minus immediate, with the immediate equal to
7313 // the "unit" size. The unit size is based on the alignment of the struct
7314 // being copied (16, 8, 4, 2, or 1 bytes).
7316 // \param InReg the register holding the initial value.
7317 // \param OutReg the register to recieve the subtracted value.
7318 virtual void emitSubImm(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7319 unsigned InReg, unsigned OutReg) = 0;
7321 // Emit a branch based on a condition code of not equal.
7323 // \param TargetBB the destination of the branch.
7324 virtual void emitBranchNE(MachineBasicBlock *BB, MachineInstr *MI,
7325 DebugLoc &dl, MachineBasicBlock *TargetBB) = 0;
7327 // Find the constant pool index for the given constant. This method is
7328 // implemented in the base class because it is the same for all subtargets.
7330 // \param LoopSize the constant value for which the index should be returned.
7331 // \returns the constant pool index for the constant.
7332 unsigned getConstantPoolIndex(MachineFunction *MF, const DataLayout *DL,
7333 unsigned LoopSize) {
7334 MachineConstantPool *ConstantPool = MF->getConstantPool();
7335 Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7336 const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7338 // MachineConstantPool wants an explicit alignment.
7339 unsigned Align = DL->getPrefTypeAlignment(Int32Ty);
7341 Align = DL->getTypeAllocSize(C->getType());
7342 return ConstantPool->getConstantPoolIndex(C, Align);
7345 // Return the register class used by the subtarget.
7347 // \returns the target register class.
7348 const TargetRegisterClass *getTRC() const { return TRC; }
7350 virtual ~TargetStructByvalEmitter() {};
7353 const TargetInstrInfo *TII;
7354 MachineRegisterInfo &MRI;
7355 const TargetRegisterClass *TRC;
7358 class ARMStructByvalEmitter : public TargetStructByvalEmitter {
7360 ARMStructByvalEmitter(const TargetInstrInfo *TII, MachineRegisterInfo &MRI,
7361 unsigned LoadStoreSize)
7362 : TargetStructByvalEmitter(
7363 TII, MRI, (const TargetRegisterClass *)&ARM::GPRRegClass),
7364 UnitSize(LoadStoreSize),
7365 UnitLdOpc(LoadStoreSize == 4
7367 : LoadStoreSize == 2
7369 : LoadStoreSize == 1 ? ARM::LDRB_POST_IMM : 0),
7370 UnitStOpc(LoadStoreSize == 4
7372 : LoadStoreSize == 2
7374 : LoadStoreSize == 1 ? ARM::STRB_POST_IMM : 0) {}
7376 unsigned emitUnitLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7377 unsigned baseReg, unsigned baseOut) {
7378 unsigned scratch = MRI.createVirtualRegister(TRC);
7379 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch).addReg(
7380 baseOut, RegState::Define).addReg(baseReg).addReg(0).addImm(UnitSize));
7384 void emitUnitStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7385 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7386 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc), baseOut).addReg(
7387 storeReg).addReg(baseReg).addReg(0).addImm(UnitSize));
7390 unsigned emitByteLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7391 unsigned baseReg, unsigned baseOut) {
7392 unsigned scratch = MRI.createVirtualRegister(TRC);
7393 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRB_POST_IMM), scratch)
7394 .addReg(baseOut, RegState::Define).addReg(baseReg)
7395 .addReg(0).addImm(1));
7399 void emitByteStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7400 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7401 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::STRB_POST_IMM), baseOut)
7402 .addReg(storeReg).addReg(baseReg).addReg(0).addImm(1));
7405 unsigned emitConstantLoad(MachineBasicBlock *BB, MachineInstr *MI,
7406 DebugLoc &dl, unsigned Constant,
7407 const DataLayout *DL) {
7408 unsigned constReg = MRI.createVirtualRegister(TRC);
7409 unsigned Idx = getConstantPoolIndex(BB->getParent(), DL, Constant);
7410 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7411 constReg, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7415 void emitSubImm(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7416 unsigned InReg, unsigned OutReg) {
7417 MachineInstrBuilder MIB =
7418 BuildMI(*BB, MI, dl, TII->get(ARM::SUBri), OutReg);
7419 AddDefaultCC(AddDefaultPred(MIB.addReg(InReg).addImm(UnitSize)));
7420 MIB->getOperand(5).setReg(ARM::CPSR);
7421 MIB->getOperand(5).setIsDef(true);
7424 void emitBranchNE(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7425 MachineBasicBlock *TargetBB) {
7426 BuildMI(*BB, MI, dl, TII->get(ARM::Bcc)).addMBB(TargetBB).addImm(ARMCC::NE)
7431 const unsigned UnitSize;
7432 const unsigned UnitLdOpc;
7433 const unsigned UnitStOpc;
7436 class Thumb2StructByvalEmitter : public TargetStructByvalEmitter {
7438 Thumb2StructByvalEmitter(const TargetInstrInfo *TII, MachineRegisterInfo &MRI,
7439 unsigned LoadStoreSize)
7440 : TargetStructByvalEmitter(
7441 TII, MRI, (const TargetRegisterClass *)&ARM::tGPRRegClass),
7442 UnitSize(LoadStoreSize),
7443 UnitLdOpc(LoadStoreSize == 4
7445 : LoadStoreSize == 2
7447 : LoadStoreSize == 1 ? ARM::t2LDRB_POST : 0),
7448 UnitStOpc(LoadStoreSize == 4
7450 : LoadStoreSize == 2
7452 : LoadStoreSize == 1 ? ARM::t2STRB_POST : 0) {}
7454 unsigned emitUnitLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7455 unsigned baseReg, unsigned baseOut) {
7456 unsigned scratch = MRI.createVirtualRegister(TRC);
7457 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch).addReg(
7458 baseOut, RegState::Define).addReg(baseReg).addImm(UnitSize));
7462 void emitUnitStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7463 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7464 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc), baseOut)
7465 .addReg(storeReg).addReg(baseReg).addImm(UnitSize));
7468 unsigned emitByteLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7469 unsigned baseReg, unsigned baseOut) {
7470 unsigned scratch = MRI.createVirtualRegister(TRC);
7471 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::t2LDRB_POST), scratch)
7472 .addReg(baseOut, RegState::Define).addReg(baseReg)
7477 void emitByteStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7478 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7479 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::t2STRB_POST), baseOut)
7480 .addReg(storeReg).addReg(baseReg).addImm(1));
7483 unsigned emitConstantLoad(MachineBasicBlock *BB, MachineInstr *MI,
7484 DebugLoc &dl, unsigned Constant,
7485 const DataLayout *DL) {
7486 unsigned VConst = MRI.createVirtualRegister(TRC);
7487 unsigned Vtmp = VConst;
7488 if ((Constant & 0xFFFF0000) != 0)
7489 Vtmp = MRI.createVirtualRegister(TRC);
7490 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7491 .addImm(Constant & 0xFFFF));
7493 if ((Constant & 0xFFFF0000) != 0)
7494 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), VConst)
7495 .addReg(Vtmp).addImm(Constant >> 16));
7499 void emitSubImm(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7500 unsigned InReg, unsigned OutReg) {
7501 MachineInstrBuilder MIB =
7502 BuildMI(*BB, MI, dl, TII->get(ARM::t2SUBri), OutReg);
7503 AddDefaultCC(AddDefaultPred(MIB.addReg(InReg).addImm(UnitSize)));
7504 MIB->getOperand(5).setReg(ARM::CPSR);
7505 MIB->getOperand(5).setIsDef(true);
7508 void emitBranchNE(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7509 MachineBasicBlock *TargetBB) {
7510 BuildMI(BB, dl, TII->get(ARM::t2Bcc)).addMBB(TargetBB).addImm(ARMCC::NE)
7515 const unsigned UnitSize;
7516 const unsigned UnitLdOpc;
7517 const unsigned UnitStOpc;
7520 class Thumb1StructByvalEmitter : public TargetStructByvalEmitter {
7522 Thumb1StructByvalEmitter(const TargetInstrInfo *TII, MachineRegisterInfo &MRI,
7523 unsigned LoadStoreSize)
7524 : TargetStructByvalEmitter(
7525 TII, MRI, (const TargetRegisterClass *)&ARM::tGPRRegClass),
7526 UnitSize(LoadStoreSize),
7527 UnitLdOpc(LoadStoreSize == 4 ? ARM::tLDRi : LoadStoreSize == 2
7529 : LoadStoreSize == 1
7532 UnitStOpc(LoadStoreSize == 4 ? ARM::tSTRi : LoadStoreSize == 2
7534 : LoadStoreSize == 1
7538 void emitAddSubi8(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7539 unsigned opcode, unsigned baseReg, unsigned Imm,
7541 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(opcode), baseOut);
7542 MIB = AddDefaultT1CC(MIB);
7543 MIB.addReg(baseReg).addImm(Imm);
7544 AddDefaultPred(MIB);
7547 unsigned emitUnitLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7548 unsigned baseReg, unsigned baseOut) {
7549 // load into scratch
7550 unsigned scratch = MRI.createVirtualRegister(TRC);
7551 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitLdOpc), scratch)
7552 .addReg(baseReg).addImm(0));
7554 // update base pointer
7555 emitAddSubi8(BB, MI, dl, ARM::tADDi8, baseReg, UnitSize, baseOut);
7559 void emitUnitStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7560 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7561 // load into scratch
7562 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(UnitStOpc)).addReg(storeReg)
7563 .addReg(baseReg).addImm(0));
7565 // update base pointer
7566 emitAddSubi8(BB, MI, dl, ARM::tADDi8, baseReg, UnitSize, baseOut);
7569 unsigned emitByteLoad(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7570 unsigned baseReg, unsigned baseOut) {
7571 // load into scratch
7572 unsigned scratch = MRI.createVirtualRegister(TRC);
7573 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRBi), scratch)
7574 .addReg(baseReg).addImm(0));
7576 // update base pointer
7577 emitAddSubi8(BB, MI, dl, ARM::tADDi8, baseReg, 1, baseOut);
7581 void emitByteStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7582 unsigned baseReg, unsigned storeReg, unsigned baseOut) {
7583 // load into scratch
7584 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tSTRBi)).addReg(storeReg)
7585 .addReg(baseReg).addImm(0));
7587 // update base pointer
7588 emitAddSubi8(BB, MI, dl, ARM::tADDi8, baseReg, 1, baseOut);
7591 unsigned emitConstantLoad(MachineBasicBlock *BB, MachineInstr *MI,
7592 DebugLoc &dl, unsigned Constant,
7593 const DataLayout *DL) {
7594 unsigned constReg = MRI.createVirtualRegister(TRC);
7595 unsigned Idx = getConstantPoolIndex(BB->getParent(), DL, Constant);
7596 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7597 constReg, RegState::Define).addConstantPoolIndex(Idx));
7601 void emitSubImm(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7602 unsigned InReg, unsigned OutReg) {
7603 emitAddSubi8(BB, MI, dl, ARM::tSUBi8, InReg, UnitSize, OutReg);
7606 void emitBranchNE(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7607 MachineBasicBlock *TargetBB) {
7608 BuildMI(*BB, MI, dl, TII->get(ARM::tBcc)).addMBB(TargetBB).addImm(ARMCC::NE)
7613 const unsigned UnitSize;
7614 const unsigned UnitLdOpc;
7615 const unsigned UnitStOpc;
7618 // This class is a thin wrapper that delegates most of the work to the correct
7619 // TargetStructByvalEmitter implementation. It also handles the lowering for
7620 // targets that support neon because the neon implementation is the same for all
7621 // targets that support it.
7622 class StructByvalEmitter {
7624 StructByvalEmitter(unsigned LoadStoreSize, const ARMSubtarget *Subtarget,
7625 const TargetInstrInfo *TII_, MachineRegisterInfo &MRI_,
7626 const DataLayout *DL_)
7627 : UnitSize(LoadStoreSize),
7629 Subtarget->isThumb1Only()
7630 ? static_cast<TargetStructByvalEmitter *>(
7631 new Thumb1StructByvalEmitter(TII_, MRI_, LoadStoreSize))
7632 : Subtarget->isThumb2()
7633 ? static_cast<TargetStructByvalEmitter *>(
7634 new Thumb2StructByvalEmitter(TII_, MRI_,
7636 : static_cast<TargetStructByvalEmitter *>(
7637 new ARMStructByvalEmitter(TII_, MRI_,
7639 TII(TII_), MRI(MRI_), DL(DL_),
7640 VecTRC(UnitSize == 16
7641 ? (const TargetRegisterClass *)&ARM::DPairRegClass
7643 ? (const TargetRegisterClass *)&ARM::DPRRegClass
7645 VecLdOpc(UnitSize == 16 ? ARM::VLD1q32wb_fixed
7646 : UnitSize == 8 ? ARM::VLD1d32wb_fixed : 0),
7647 VecStOpc(UnitSize == 16 ? ARM::VST1q32wb_fixed
7648 : UnitSize == 8 ? ARM::VST1d32wb_fixed : 0) {}
7650 // Emit a post-increment load of "unit" size. The unit size is based on the
7651 // alignment of the struct being copied (16, 8, 4, 2, or 1 bytes). Loads of 16
7652 // or 8 bytes use NEON instructions to load the value.
7654 // \param baseReg the register holding the address to load.
7655 // \param baseOut the register to recieve the incremented address. If baseOut
7656 // is 0 then a new register is created to hold the incremented address.
7657 // \returns a pair of registers holding the loaded value and the updated
7659 std::pair<unsigned, unsigned> emitUnitLoad(MachineBasicBlock *BB,
7660 MachineInstr *MI, DebugLoc &dl,
7662 unsigned baseOut = 0) {
7663 unsigned scratch = 0;
7665 baseOut = MRI.createVirtualRegister(TargetEmitter->getTRC());
7666 if (UnitSize >= 8) { // neon
7667 scratch = MRI.createVirtualRegister(VecTRC);
7668 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(VecLdOpc), scratch).addReg(
7669 baseOut, RegState::Define).addReg(baseReg).addImm(0));
7671 scratch = TargetEmitter->emitUnitLoad(BB, MI, dl, baseReg, baseOut);
7673 return std::make_pair(scratch, baseOut);
7676 // Emit a post-increment store of "unit" size. The unit size is based on the
7677 // alignment of the struct being copied (16, 8, 4, 2, or 1 bytes). Stores of
7678 // 16 or 8 bytes use NEON instructions to store the value.
7680 // \param baseReg the register holding the address to store.
7681 // \param storeReg the register holding the value to store.
7682 // \param baseOut the register to recieve the incremented address. If baseOut
7683 // is 0 then a new register is created to hold the incremented address.
7684 // \returns the register holding the updated address.
7685 unsigned emitUnitStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7686 unsigned baseReg, unsigned storeReg,
7687 unsigned baseOut = 0) {
7689 baseOut = MRI.createVirtualRegister(TargetEmitter->getTRC());
7690 if (UnitSize >= 8) { // neon
7691 AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(VecStOpc), baseOut)
7692 .addReg(baseReg).addImm(0).addReg(storeReg));
7694 TargetEmitter->emitUnitStore(BB, MI, dl, baseReg, storeReg, baseOut);
7699 // Emit a post-increment load of one byte.
7701 // \param baseReg the register holding the address to load.
7702 // \returns a pair of registers holding the loaded value and the updated
7704 std::pair<unsigned, unsigned> emitByteLoad(MachineBasicBlock *BB,
7705 MachineInstr *MI, DebugLoc &dl,
7707 unsigned baseOut = MRI.createVirtualRegister(TargetEmitter->getTRC());
7709 TargetEmitter->emitByteLoad(BB, MI, dl, baseReg, baseOut);
7710 return std::make_pair(scratch, baseOut);
7713 // Emit a post-increment store of one byte.
7715 // \param baseReg the register holding the address to store.
7716 // \param storeReg the register holding the value to store.
7717 // \returns the register holding the updated address.
7718 unsigned emitByteStore(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7719 unsigned baseReg, unsigned storeReg) {
7720 unsigned baseOut = MRI.createVirtualRegister(TargetEmitter->getTRC());
7721 TargetEmitter->emitByteStore(BB, MI, dl, baseReg, storeReg, baseOut);
7725 // Emit a load of the constant LoopSize.
7727 // \param LoopSize the constant to load.
7728 // \returns the register holding the loaded constant.
7729 unsigned emitConstantLoad(MachineBasicBlock *BB, MachineInstr *MI,
7730 DebugLoc &dl, unsigned LoopSize) {
7731 return TargetEmitter->emitConstantLoad(BB, MI, dl, LoopSize, DL);
7734 // Emit a subtract of a register minus immediate, with the immediate equal to
7735 // the "unit" size. The unit size is based on the alignment of the struct
7736 // being copied (16, 8, 4, 2, or 1 bytes).
7738 // \param InReg the register holding the initial value.
7739 // \param OutReg the register to recieve the subtracted value.
7740 void emitSubImm(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7741 unsigned InReg, unsigned OutReg) {
7742 TargetEmitter->emitSubImm(BB, MI, dl, InReg, OutReg);
7745 // Emit a branch based on a condition code of not equal.
7747 // \param TargetBB the destination of the branch.
7748 void emitBranchNE(MachineBasicBlock *BB, MachineInstr *MI, DebugLoc &dl,
7749 MachineBasicBlock *TargetBB) {
7750 TargetEmitter->emitBranchNE(BB, MI, dl, TargetBB);
7753 // Return the register class used by the subtarget.
7755 // \returns the target register class.
7756 const TargetRegisterClass *getTRC() const { return TargetEmitter->getTRC(); }
7759 const unsigned UnitSize;
7760 OwningPtr<TargetStructByvalEmitter> TargetEmitter;
7761 const TargetInstrInfo *TII;
7762 MachineRegisterInfo &MRI;
7763 const DataLayout *DL;
7765 const TargetRegisterClass *VecTRC;
7766 const unsigned VecLdOpc;
7767 const unsigned VecStOpc;
7772 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7773 MachineBasicBlock *BB) const {
7774 // This pseudo instruction has 3 operands: dst, src, size
7775 // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7776 // Otherwise, we will generate unrolled scalar copies.
7777 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7778 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7779 MachineFunction::iterator It = BB;
7782 unsigned dest = MI->getOperand(0).getReg();
7783 unsigned src = MI->getOperand(1).getReg();
7784 unsigned SizeVal = MI->getOperand(2).getImm();
7785 unsigned Align = MI->getOperand(3).getImm();
7786 DebugLoc dl = MI->getDebugLoc();
7788 MachineFunction *MF = BB->getParent();
7789 MachineRegisterInfo &MRI = MF->getRegInfo();
7790 unsigned UnitSize = 0;
7794 } else if (Align & 2) {
7797 // Check whether we can use NEON instructions.
7798 if (!MF->getFunction()->getAttributes().
7799 hasAttribute(AttributeSet::FunctionIndex,
7800 Attribute::NoImplicitFloat) &&
7801 Subtarget->hasNEON()) {
7802 if ((Align % 16 == 0) && SizeVal >= 16)
7804 else if ((Align % 8 == 0) && SizeVal >= 8)
7807 // Can't use NEON instructions.
7812 StructByvalEmitter ByvalEmitter(UnitSize, Subtarget, TII, MRI,
7814 unsigned BytesLeft = SizeVal % UnitSize;
7815 unsigned LoopSize = SizeVal - BytesLeft;
7817 if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7818 // Use LDR and STR to copy.
7819 // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7820 // [destOut] = STR_POST(scratch, destIn, UnitSize)
7821 unsigned srcIn = src;
7822 unsigned destIn = dest;
7823 for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7824 std::pair<unsigned, unsigned> res =
7825 ByvalEmitter.emitUnitLoad(BB, MI, dl, srcIn);
7826 unsigned scratch = res.first;
7828 destIn = ByvalEmitter.emitUnitStore(BB, MI, dl, destIn, scratch);
7831 // Handle the leftover bytes with LDRB and STRB.
7832 // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7833 // [destOut] = STRB_POST(scratch, destIn, 1)
7834 for (unsigned i = 0; i < BytesLeft; i++) {
7835 std::pair<unsigned, unsigned> res =
7836 ByvalEmitter.emitByteLoad(BB, MI, dl, srcIn);
7837 unsigned scratch = res.first;
7839 destIn = ByvalEmitter.emitByteStore(BB, MI, dl, destIn, scratch);
7841 MI->eraseFromParent(); // The instruction is gone now.
7845 // Expand the pseudo op to a loop.
7848 // movw varEnd, # --> with thumb2
7850 // ldrcp varEnd, idx --> without thumb2
7851 // fallthrough --> loopMBB
7853 // PHI varPhi, varEnd, varLoop
7854 // PHI srcPhi, src, srcLoop
7855 // PHI destPhi, dst, destLoop
7856 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7857 // [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7858 // subs varLoop, varPhi, #UnitSize
7860 // fallthrough --> exitMBB
7862 // epilogue to handle left-over bytes
7863 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7864 // [destOut] = STRB_POST(scratch, destLoop, 1)
7865 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7866 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7867 MF->insert(It, loopMBB);
7868 MF->insert(It, exitMBB);
7870 // Transfer the remainder of BB and its successor edges to exitMBB.
7871 exitMBB->splice(exitMBB->begin(), BB,
7872 llvm::next(MachineBasicBlock::iterator(MI)),
7874 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7876 // Load an immediate to varEnd.
7877 unsigned varEnd = ByvalEmitter.emitConstantLoad(BB, MI, dl, LoopSize);
7878 BB->addSuccessor(loopMBB);
7880 // Generate the loop body:
7881 // varPhi = PHI(varLoop, varEnd)
7882 // srcPhi = PHI(srcLoop, src)
7883 // destPhi = PHI(destLoop, dst)
7884 MachineBasicBlock *entryBB = BB;
7886 unsigned varLoop = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7887 unsigned varPhi = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7888 unsigned srcLoop = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7889 unsigned srcPhi = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7890 unsigned destLoop = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7891 unsigned destPhi = MRI.createVirtualRegister(ByvalEmitter.getTRC());
7893 BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7894 .addReg(varLoop).addMBB(loopMBB)
7895 .addReg(varEnd).addMBB(entryBB);
7896 BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7897 .addReg(srcLoop).addMBB(loopMBB)
7898 .addReg(src).addMBB(entryBB);
7899 BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7900 .addReg(destLoop).addMBB(loopMBB)
7901 .addReg(dest).addMBB(entryBB);
7903 // [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7904 // [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7906 std::pair<unsigned, unsigned> res =
7907 ByvalEmitter.emitUnitLoad(BB, BB->end(), dl, srcPhi, srcLoop);
7908 unsigned scratch = res.first;
7909 ByvalEmitter.emitUnitStore(BB, BB->end(), dl, destPhi, scratch, destLoop);
7912 // Decrement loop variable by UnitSize.
7913 ByvalEmitter.emitSubImm(BB, BB->end(), dl, varPhi, varLoop);
7914 ByvalEmitter.emitBranchNE(BB, BB->end(), dl, loopMBB);
7916 // loopMBB can loop back to loopMBB or fall through to exitMBB.
7917 BB->addSuccessor(loopMBB);
7918 BB->addSuccessor(exitMBB);
7920 // Add epilogue to handle BytesLeft.
7922 MachineInstr *StartOfExit = exitMBB->begin();
7924 // [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7925 // [destOut] = STRB_POST(scratch, destLoop, 1)
7926 unsigned srcIn = srcLoop;
7927 unsigned destIn = destLoop;
7928 for (unsigned i = 0; i < BytesLeft; i++) {
7929 std::pair<unsigned, unsigned> res =
7930 ByvalEmitter.emitByteLoad(BB, StartOfExit, dl, srcIn);
7931 unsigned scratch = res.first;
7933 destIn = ByvalEmitter.emitByteStore(BB, StartOfExit, dl, destIn, scratch);
7936 MI->eraseFromParent(); // The instruction is gone now.
7941 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7942 MachineBasicBlock *BB) const {
7943 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7944 DebugLoc dl = MI->getDebugLoc();
7945 bool isThumb2 = Subtarget->isThumb2();
7946 switch (MI->getOpcode()) {
7949 llvm_unreachable("Unexpected instr type to insert");
7951 // The Thumb2 pre-indexed stores have the same MI operands, they just
7952 // define them differently in the .td files from the isel patterns, so
7953 // they need pseudos.
7954 case ARM::t2STR_preidx:
7955 MI->setDesc(TII->get(ARM::t2STR_PRE));
7957 case ARM::t2STRB_preidx:
7958 MI->setDesc(TII->get(ARM::t2STRB_PRE));
7960 case ARM::t2STRH_preidx:
7961 MI->setDesc(TII->get(ARM::t2STRH_PRE));
7964 case ARM::STRi_preidx:
7965 case ARM::STRBi_preidx: {
7966 unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7967 ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7968 // Decode the offset.
7969 unsigned Offset = MI->getOperand(4).getImm();
7970 bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7971 Offset = ARM_AM::getAM2Offset(Offset);
7975 MachineMemOperand *MMO = *MI->memoperands_begin();
7976 BuildMI(*BB, MI, dl, TII->get(NewOpc))
7977 .addOperand(MI->getOperand(0)) // Rn_wb
7978 .addOperand(MI->getOperand(1)) // Rt
7979 .addOperand(MI->getOperand(2)) // Rn
7980 .addImm(Offset) // offset (skip GPR==zero_reg)
7981 .addOperand(MI->getOperand(5)) // pred
7982 .addOperand(MI->getOperand(6))
7983 .addMemOperand(MMO);
7984 MI->eraseFromParent();
7987 case ARM::STRr_preidx:
7988 case ARM::STRBr_preidx:
7989 case ARM::STRH_preidx: {
7991 switch (MI->getOpcode()) {
7992 default: llvm_unreachable("unexpected opcode!");
7993 case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7994 case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7995 case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7997 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7998 for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7999 MIB.addOperand(MI->getOperand(i));
8000 MI->eraseFromParent();
8003 case ARM::ATOMIC_LOAD_ADD_I8:
8004 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
8005 case ARM::ATOMIC_LOAD_ADD_I16:
8006 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
8007 case ARM::ATOMIC_LOAD_ADD_I32:
8008 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
8010 case ARM::ATOMIC_LOAD_AND_I8:
8011 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
8012 case ARM::ATOMIC_LOAD_AND_I16:
8013 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
8014 case ARM::ATOMIC_LOAD_AND_I32:
8015 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
8017 case ARM::ATOMIC_LOAD_OR_I8:
8018 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
8019 case ARM::ATOMIC_LOAD_OR_I16:
8020 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
8021 case ARM::ATOMIC_LOAD_OR_I32:
8022 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
8024 case ARM::ATOMIC_LOAD_XOR_I8:
8025 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
8026 case ARM::ATOMIC_LOAD_XOR_I16:
8027 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
8028 case ARM::ATOMIC_LOAD_XOR_I32:
8029 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
8031 case ARM::ATOMIC_LOAD_NAND_I8:
8032 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
8033 case ARM::ATOMIC_LOAD_NAND_I16:
8034 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
8035 case ARM::ATOMIC_LOAD_NAND_I32:
8036 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
8038 case ARM::ATOMIC_LOAD_SUB_I8:
8039 return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
8040 case ARM::ATOMIC_LOAD_SUB_I16:
8041 return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
8042 case ARM::ATOMIC_LOAD_SUB_I32:
8043 return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
8045 case ARM::ATOMIC_LOAD_MIN_I8:
8046 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
8047 case ARM::ATOMIC_LOAD_MIN_I16:
8048 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
8049 case ARM::ATOMIC_LOAD_MIN_I32:
8050 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
8052 case ARM::ATOMIC_LOAD_MAX_I8:
8053 return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
8054 case ARM::ATOMIC_LOAD_MAX_I16:
8055 return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
8056 case ARM::ATOMIC_LOAD_MAX_I32:
8057 return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
8059 case ARM::ATOMIC_LOAD_UMIN_I8:
8060 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
8061 case ARM::ATOMIC_LOAD_UMIN_I16:
8062 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
8063 case ARM::ATOMIC_LOAD_UMIN_I32:
8064 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
8066 case ARM::ATOMIC_LOAD_UMAX_I8:
8067 return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
8068 case ARM::ATOMIC_LOAD_UMAX_I16:
8069 return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
8070 case ARM::ATOMIC_LOAD_UMAX_I32:
8071 return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
8073 case ARM::ATOMIC_SWAP_I8: return EmitAtomicBinary(MI, BB, 1, 0);
8074 case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
8075 case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
8077 case ARM::ATOMIC_CMP_SWAP_I8: return EmitAtomicCmpSwap(MI, BB, 1);
8078 case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
8079 case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
8081 case ARM::ATOMIC_LOAD_I64:
8082 return EmitAtomicLoad64(MI, BB);
8084 case ARM::ATOMIC_LOAD_ADD_I64:
8085 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
8086 isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
8087 /*NeedsCarry*/ true);
8088 case ARM::ATOMIC_LOAD_SUB_I64:
8089 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8090 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8091 /*NeedsCarry*/ true);
8092 case ARM::ATOMIC_LOAD_OR_I64:
8093 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
8094 isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
8095 case ARM::ATOMIC_LOAD_XOR_I64:
8096 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
8097 isThumb2 ? ARM::t2EORrr : ARM::EORrr);
8098 case ARM::ATOMIC_LOAD_AND_I64:
8099 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
8100 isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
8101 case ARM::ATOMIC_STORE_I64:
8102 case ARM::ATOMIC_SWAP_I64:
8103 return EmitAtomicBinary64(MI, BB, 0, 0, false);
8104 case ARM::ATOMIC_CMP_SWAP_I64:
8105 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8106 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8107 /*NeedsCarry*/ false, /*IsCmpxchg*/true);
8108 case ARM::ATOMIC_LOAD_MIN_I64:
8109 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8110 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8111 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
8112 /*IsMinMax*/ true, ARMCC::LT);
8113 case ARM::ATOMIC_LOAD_MAX_I64:
8114 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8115 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8116 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
8117 /*IsMinMax*/ true, ARMCC::GE);
8118 case ARM::ATOMIC_LOAD_UMIN_I64:
8119 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8120 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8121 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
8122 /*IsMinMax*/ true, ARMCC::LO);
8123 case ARM::ATOMIC_LOAD_UMAX_I64:
8124 return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
8125 isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
8126 /*NeedsCarry*/ true, /*IsCmpxchg*/false,
8127 /*IsMinMax*/ true, ARMCC::HS);
8129 case ARM::tMOVCCr_pseudo: {
8130 // To "insert" a SELECT_CC instruction, we actually have to insert the
8131 // diamond control-flow pattern. The incoming instruction knows the
8132 // destination vreg to set, the condition code register to branch on, the
8133 // true/false values to select between, and a branch opcode to use.
8134 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8135 MachineFunction::iterator It = BB;
8141 // cmpTY ccX, r1, r2
8143 // fallthrough --> copy0MBB
8144 MachineBasicBlock *thisMBB = BB;
8145 MachineFunction *F = BB->getParent();
8146 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8147 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8148 F->insert(It, copy0MBB);
8149 F->insert(It, sinkMBB);
8151 // Transfer the remainder of BB and its successor edges to sinkMBB.
8152 sinkMBB->splice(sinkMBB->begin(), BB,
8153 llvm::next(MachineBasicBlock::iterator(MI)),
8155 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8157 BB->addSuccessor(copy0MBB);
8158 BB->addSuccessor(sinkMBB);
8160 BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
8161 .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
8164 // %FalseValue = ...
8165 // # fallthrough to sinkMBB
8168 // Update machine-CFG edges
8169 BB->addSuccessor(sinkMBB);
8172 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8175 BuildMI(*BB, BB->begin(), dl,
8176 TII->get(ARM::PHI), MI->getOperand(0).getReg())
8177 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8178 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8180 MI->eraseFromParent(); // The pseudo instruction is gone now.
8185 case ARM::BCCZi64: {
8186 // If there is an unconditional branch to the other successor, remove it.
8187 BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
8189 // Compare both parts that make up the double comparison separately for
8191 bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
8193 unsigned LHS1 = MI->getOperand(1).getReg();
8194 unsigned LHS2 = MI->getOperand(2).getReg();
8196 AddDefaultPred(BuildMI(BB, dl,
8197 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8198 .addReg(LHS1).addImm(0));
8199 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8200 .addReg(LHS2).addImm(0)
8201 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8203 unsigned RHS1 = MI->getOperand(3).getReg();
8204 unsigned RHS2 = MI->getOperand(4).getReg();
8205 AddDefaultPred(BuildMI(BB, dl,
8206 TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8207 .addReg(LHS1).addReg(RHS1));
8208 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8209 .addReg(LHS2).addReg(RHS2)
8210 .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8213 MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
8214 MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8215 if (MI->getOperand(0).getImm() == ARMCC::NE)
8216 std::swap(destMBB, exitMBB);
8218 BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8219 .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8221 AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8223 BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8225 MI->eraseFromParent(); // The pseudo instruction is gone now.
8229 case ARM::Int_eh_sjlj_setjmp:
8230 case ARM::Int_eh_sjlj_setjmp_nofp:
8231 case ARM::tInt_eh_sjlj_setjmp:
8232 case ARM::t2Int_eh_sjlj_setjmp:
8233 case ARM::t2Int_eh_sjlj_setjmp_nofp:
8234 EmitSjLjDispatchBlock(MI, BB);
8239 // To insert an ABS instruction, we have to insert the
8240 // diamond control-flow pattern. The incoming instruction knows the
8241 // source vreg to test against 0, the destination vreg to set,
8242 // the condition code register to branch on, the
8243 // true/false values to select between, and a branch opcode to use.
8248 // BCC (branch to SinkBB if V0 >= 0)
8249 // RSBBB: V3 = RSBri V2, 0 (compute ABS if V2 < 0)
8250 // SinkBB: V1 = PHI(V2, V3)
8251 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8252 MachineFunction::iterator BBI = BB;
8254 MachineFunction *Fn = BB->getParent();
8255 MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8256 MachineBasicBlock *SinkBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8257 Fn->insert(BBI, RSBBB);
8258 Fn->insert(BBI, SinkBB);
8260 unsigned int ABSSrcReg = MI->getOperand(1).getReg();
8261 unsigned int ABSDstReg = MI->getOperand(0).getReg();
8262 bool isThumb2 = Subtarget->isThumb2();
8263 MachineRegisterInfo &MRI = Fn->getRegInfo();
8264 // In Thumb mode S must not be specified if source register is the SP or
8265 // PC and if destination register is the SP, so restrict register class
8266 unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
8267 (const TargetRegisterClass*)&ARM::rGPRRegClass :
8268 (const TargetRegisterClass*)&ARM::GPRRegClass);
8270 // Transfer the remainder of BB and its successor edges to sinkMBB.
8271 SinkBB->splice(SinkBB->begin(), BB,
8272 llvm::next(MachineBasicBlock::iterator(MI)),
8274 SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8276 BB->addSuccessor(RSBBB);
8277 BB->addSuccessor(SinkBB);
8279 // fall through to SinkMBB
8280 RSBBB->addSuccessor(SinkBB);
8282 // insert a cmp at the end of BB
8283 AddDefaultPred(BuildMI(BB, dl,
8284 TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8285 .addReg(ABSSrcReg).addImm(0));
8287 // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8289 TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8290 .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8292 // insert rsbri in RSBBB
8293 // Note: BCC and rsbri will be converted into predicated rsbmi
8294 // by if-conversion pass
8295 BuildMI(*RSBBB, RSBBB->begin(), dl,
8296 TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8297 .addReg(ABSSrcReg, RegState::Kill)
8298 .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8300 // insert PHI in SinkBB,
8301 // reuse ABSDstReg to not change uses of ABS instruction
8302 BuildMI(*SinkBB, SinkBB->begin(), dl,
8303 TII->get(ARM::PHI), ABSDstReg)
8304 .addReg(NewRsbDstReg).addMBB(RSBBB)
8305 .addReg(ABSSrcReg).addMBB(BB);
8307 // remove ABS instruction
8308 MI->eraseFromParent();
8310 // return last added BB
8313 case ARM::COPY_STRUCT_BYVAL_I32:
8315 return EmitStructByval(MI, BB);
8319 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8320 SDNode *Node) const {
8321 if (!MI->hasPostISelHook()) {
8322 assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
8323 "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
8327 const MCInstrDesc *MCID = &MI->getDesc();
8328 // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8329 // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8330 // operand is still set to noreg. If needed, set the optional operand's
8331 // register to CPSR, and remove the redundant implicit def.
8333 // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8335 // Rename pseudo opcodes.
8336 unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8338 const ARMBaseInstrInfo *TII =
8339 static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
8340 MCID = &TII->get(NewOpc);
8342 assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8343 "converted opcode should be the same except for cc_out");
8347 // Add the optional cc_out operand
8348 MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8350 unsigned ccOutIdx = MCID->getNumOperands() - 1;
8352 // Any ARM instruction that sets the 's' bit should specify an optional
8353 // "cc_out" operand in the last operand position.
8354 if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8355 assert(!NewOpc && "Optional cc_out operand required");
8358 // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8359 // since we already have an optional CPSR def.
8360 bool definesCPSR = false;
8361 bool deadCPSR = false;
8362 for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8364 const MachineOperand &MO = MI->getOperand(i);
8365 if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8369 MI->RemoveOperand(i);
8374 assert(!NewOpc && "Optional cc_out operand required");
8377 assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8379 assert(!MI->getOperand(ccOutIdx).getReg() &&
8380 "expect uninitialized optional cc_out operand");
8384 // If this instruction was defined with an optional CPSR def and its dag node
8385 // had a live implicit CPSR def, then activate the optional CPSR def.
8386 MachineOperand &MO = MI->getOperand(ccOutIdx);
8387 MO.setReg(ARM::CPSR);
8391 //===----------------------------------------------------------------------===//
8392 // ARM Optimization Hooks
8393 //===----------------------------------------------------------------------===//
8395 // Helper function that checks if N is a null or all ones constant.
8396 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8397 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8400 return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8403 // Return true if N is conditionally 0 or all ones.
8404 // Detects these expressions where cc is an i1 value:
8406 // (select cc 0, y) [AllOnes=0]
8407 // (select cc y, 0) [AllOnes=0]
8408 // (zext cc) [AllOnes=0]
8409 // (sext cc) [AllOnes=0/1]
8410 // (select cc -1, y) [AllOnes=1]
8411 // (select cc y, -1) [AllOnes=1]
8413 // Invert is set when N is the null/all ones constant when CC is false.
8414 // OtherOp is set to the alternative value of N.
8415 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8416 SDValue &CC, bool &Invert,
8418 SelectionDAG &DAG) {
8419 switch (N->getOpcode()) {
8420 default: return false;
8422 CC = N->getOperand(0);
8423 SDValue N1 = N->getOperand(1);
8424 SDValue N2 = N->getOperand(2);
8425 if (isZeroOrAllOnes(N1, AllOnes)) {
8430 if (isZeroOrAllOnes(N2, AllOnes)) {
8437 case ISD::ZERO_EXTEND:
8438 // (zext cc) can never be the all ones value.
8442 case ISD::SIGN_EXTEND: {
8443 EVT VT = N->getValueType(0);
8444 CC = N->getOperand(0);
8445 if (CC.getValueType() != MVT::i1)
8449 // When looking for an AllOnes constant, N is an sext, and the 'other'
8451 OtherOp = DAG.getConstant(0, VT);
8452 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8453 // When looking for a 0 constant, N can be zext or sext.
8454 OtherOp = DAG.getConstant(1, VT);
8456 OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8462 // Combine a constant select operand into its use:
8464 // (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8465 // (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8466 // (and (select cc, -1, c), x) -> (select cc, x, (and, x, c)) [AllOnes=1]
8467 // (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8468 // (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8470 // The transform is rejected if the select doesn't have a constant operand that
8471 // is null, or all ones when AllOnes is set.
8473 // Also recognize sext/zext from i1:
8475 // (add (zext cc), x) -> (select cc (add x, 1), x)
8476 // (add (sext cc), x) -> (select cc (add x, -1), x)
8478 // These transformations eventually create predicated instructions.
8480 // @param N The node to transform.
8481 // @param Slct The N operand that is a select.
8482 // @param OtherOp The other N operand (x above).
8483 // @param DCI Context.
8484 // @param AllOnes Require the select constant to be all ones instead of null.
8485 // @returns The new node, or SDValue() on failure.
8487 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8488 TargetLowering::DAGCombinerInfo &DCI,
8489 bool AllOnes = false) {
8490 SelectionDAG &DAG = DCI.DAG;
8491 EVT VT = N->getValueType(0);
8492 SDValue NonConstantVal;
8495 if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8496 NonConstantVal, DAG))
8499 // Slct is now know to be the desired identity constant when CC is true.
8500 SDValue TrueVal = OtherOp;
8501 SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8502 OtherOp, NonConstantVal);
8503 // Unless SwapSelectOps says CC should be false.
8505 std::swap(TrueVal, FalseVal);
8507 return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8508 CCOp, TrueVal, FalseVal);
8511 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8513 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8514 TargetLowering::DAGCombinerInfo &DCI) {
8515 SDValue N0 = N->getOperand(0);
8516 SDValue N1 = N->getOperand(1);
8517 if (N0.getNode()->hasOneUse()) {
8518 SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8519 if (Result.getNode())
8522 if (N1.getNode()->hasOneUse()) {
8523 SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8524 if (Result.getNode())
8530 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8531 // (only after legalization).
8532 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8533 TargetLowering::DAGCombinerInfo &DCI,
8534 const ARMSubtarget *Subtarget) {
8536 // Only perform optimization if after legalize, and if NEON is available. We
8537 // also expected both operands to be BUILD_VECTORs.
8538 if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8539 || N0.getOpcode() != ISD::BUILD_VECTOR
8540 || N1.getOpcode() != ISD::BUILD_VECTOR)
8543 // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8544 EVT VT = N->getValueType(0);
8545 if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8548 // Check that the vector operands are of the right form.
8549 // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8550 // operands, where N is the size of the formed vector.
8551 // Each EXTRACT_VECTOR should have the same input vector and odd or even
8552 // index such that we have a pair wise add pattern.
8554 // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8555 if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8557 SDValue Vec = N0->getOperand(0)->getOperand(0);
8558 SDNode *V = Vec.getNode();
8559 unsigned nextIndex = 0;
8561 // For each operands to the ADD which are BUILD_VECTORs,
8562 // check to see if each of their operands are an EXTRACT_VECTOR with
8563 // the same vector and appropriate index.
8564 for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8565 if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8566 && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8568 SDValue ExtVec0 = N0->getOperand(i);
8569 SDValue ExtVec1 = N1->getOperand(i);
8571 // First operand is the vector, verify its the same.
8572 if (V != ExtVec0->getOperand(0).getNode() ||
8573 V != ExtVec1->getOperand(0).getNode())
8576 // Second is the constant, verify its correct.
8577 ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8578 ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8580 // For the constant, we want to see all the even or all the odd.
8581 if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8582 || C1->getZExtValue() != nextIndex+1)
8591 // Create VPADDL node.
8592 SelectionDAG &DAG = DCI.DAG;
8593 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8595 // Build operand list.
8596 SmallVector<SDValue, 8> Ops;
8597 Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8598 TLI.getPointerTy()));
8600 // Input is the vector.
8603 // Get widened type and narrowed type.
8605 unsigned numElem = VT.getVectorNumElements();
8606 switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8607 case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8608 case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8609 case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8611 llvm_unreachable("Invalid vector element type for padd optimization.");
8614 SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8615 widenType, &Ops[0], Ops.size());
8616 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8619 static SDValue findMUL_LOHI(SDValue V) {
8620 if (V->getOpcode() == ISD::UMUL_LOHI ||
8621 V->getOpcode() == ISD::SMUL_LOHI)
8626 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8627 TargetLowering::DAGCombinerInfo &DCI,
8628 const ARMSubtarget *Subtarget) {
8630 if (Subtarget->isThumb1Only()) return SDValue();
8632 // Only perform the checks after legalize when the pattern is available.
8633 if (DCI.isBeforeLegalize()) return SDValue();
8635 // Look for multiply add opportunities.
8636 // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8637 // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8638 // a glue link from the first add to the second add.
8639 // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8640 // a S/UMLAL instruction.
8643 // \ / \ [no multiline comment]
8649 assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8650 SDValue AddcOp0 = AddcNode->getOperand(0);
8651 SDValue AddcOp1 = AddcNode->getOperand(1);
8653 // Check if the two operands are from the same mul_lohi node.
8654 if (AddcOp0.getNode() == AddcOp1.getNode())
8657 assert(AddcNode->getNumValues() == 2 &&
8658 AddcNode->getValueType(0) == MVT::i32 &&
8659 "Expect ADDC with two result values. First: i32");
8661 // Check that we have a glued ADDC node.
8662 if (AddcNode->getValueType(1) != MVT::Glue)
8665 // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8666 if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8667 AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8668 AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8669 AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8672 // Look for the glued ADDE.
8673 SDNode* AddeNode = AddcNode->getGluedUser();
8674 if (AddeNode == NULL)
8677 // Make sure it is really an ADDE.
8678 if (AddeNode->getOpcode() != ISD::ADDE)
8681 assert(AddeNode->getNumOperands() == 3 &&
8682 AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8683 "ADDE node has the wrong inputs");
8685 // Check for the triangle shape.
8686 SDValue AddeOp0 = AddeNode->getOperand(0);
8687 SDValue AddeOp1 = AddeNode->getOperand(1);
8689 // Make sure that the ADDE operands are not coming from the same node.
8690 if (AddeOp0.getNode() == AddeOp1.getNode())
8693 // Find the MUL_LOHI node walking up ADDE's operands.
8694 bool IsLeftOperandMUL = false;
8695 SDValue MULOp = findMUL_LOHI(AddeOp0);
8696 if (MULOp == SDValue())
8697 MULOp = findMUL_LOHI(AddeOp1);
8699 IsLeftOperandMUL = true;
8700 if (MULOp == SDValue())
8703 // Figure out the right opcode.
8704 unsigned Opc = MULOp->getOpcode();
8705 unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8707 // Figure out the high and low input values to the MLAL node.
8708 SDValue* HiMul = &MULOp;
8709 SDValue* HiAdd = NULL;
8710 SDValue* LoMul = NULL;
8711 SDValue* LowAdd = NULL;
8713 if (IsLeftOperandMUL)
8719 if (AddcOp0->getOpcode() == Opc) {
8723 if (AddcOp1->getOpcode() == Opc) {
8731 if (LoMul->getNode() != HiMul->getNode())
8734 // Create the merged node.
8735 SelectionDAG &DAG = DCI.DAG;
8737 // Build operand list.
8738 SmallVector<SDValue, 8> Ops;
8739 Ops.push_back(LoMul->getOperand(0));
8740 Ops.push_back(LoMul->getOperand(1));
8741 Ops.push_back(*LowAdd);
8742 Ops.push_back(*HiAdd);
8744 SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcNode),
8745 DAG.getVTList(MVT::i32, MVT::i32),
8746 &Ops[0], Ops.size());
8748 // Replace the ADDs' nodes uses by the MLA node's values.
8749 SDValue HiMLALResult(MLALNode.getNode(), 1);
8750 DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8752 SDValue LoMLALResult(MLALNode.getNode(), 0);
8753 DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8755 // Return original node to notify the driver to stop replacing.
8756 SDValue resNode(AddcNode, 0);
8760 /// PerformADDCCombine - Target-specific dag combine transform from
8761 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8762 static SDValue PerformADDCCombine(SDNode *N,
8763 TargetLowering::DAGCombinerInfo &DCI,
8764 const ARMSubtarget *Subtarget) {
8766 return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8770 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8771 /// operands N0 and N1. This is a helper for PerformADDCombine that is
8772 /// called with the default operands, and if that fails, with commuted
8774 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8775 TargetLowering::DAGCombinerInfo &DCI,
8776 const ARMSubtarget *Subtarget){
8778 // Attempt to create vpaddl for this add.
8779 SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8780 if (Result.getNode())
8783 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8784 if (N0.getNode()->hasOneUse()) {
8785 SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8786 if (Result.getNode()) return Result;
8791 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8793 static SDValue PerformADDCombine(SDNode *N,
8794 TargetLowering::DAGCombinerInfo &DCI,
8795 const ARMSubtarget *Subtarget) {
8796 SDValue N0 = N->getOperand(0);
8797 SDValue N1 = N->getOperand(1);
8799 // First try with the default operand order.
8800 SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8801 if (Result.getNode())
8804 // If that didn't work, try again with the operands commuted.
8805 return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8808 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8810 static SDValue PerformSUBCombine(SDNode *N,
8811 TargetLowering::DAGCombinerInfo &DCI) {
8812 SDValue N0 = N->getOperand(0);
8813 SDValue N1 = N->getOperand(1);
8815 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8816 if (N1.getNode()->hasOneUse()) {
8817 SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8818 if (Result.getNode()) return Result;
8824 /// PerformVMULCombine
8825 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8826 /// special multiplier accumulator forwarding.
8832 // However, for (A + B) * (A + B),
8839 static SDValue PerformVMULCombine(SDNode *N,
8840 TargetLowering::DAGCombinerInfo &DCI,
8841 const ARMSubtarget *Subtarget) {
8842 if (!Subtarget->hasVMLxForwarding())
8845 SelectionDAG &DAG = DCI.DAG;
8846 SDValue N0 = N->getOperand(0);
8847 SDValue N1 = N->getOperand(1);
8848 unsigned Opcode = N0.getOpcode();
8849 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8850 Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8851 Opcode = N1.getOpcode();
8852 if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8853 Opcode != ISD::FADD && Opcode != ISD::FSUB)
8861 EVT VT = N->getValueType(0);
8863 SDValue N00 = N0->getOperand(0);
8864 SDValue N01 = N0->getOperand(1);
8865 return DAG.getNode(Opcode, DL, VT,
8866 DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8867 DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8870 static SDValue PerformMULCombine(SDNode *N,
8871 TargetLowering::DAGCombinerInfo &DCI,
8872 const ARMSubtarget *Subtarget) {
8873 SelectionDAG &DAG = DCI.DAG;
8875 if (Subtarget->isThumb1Only())
8878 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8881 EVT VT = N->getValueType(0);
8882 if (VT.is64BitVector() || VT.is128BitVector())
8883 return PerformVMULCombine(N, DCI, Subtarget);
8887 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8891 int64_t MulAmt = C->getSExtValue();
8892 unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8894 ShiftAmt = ShiftAmt & (32 - 1);
8895 SDValue V = N->getOperand(0);
8899 MulAmt >>= ShiftAmt;
8902 if (isPowerOf2_32(MulAmt - 1)) {
8903 // (mul x, 2^N + 1) => (add (shl x, N), x)
8904 Res = DAG.getNode(ISD::ADD, DL, VT,
8906 DAG.getNode(ISD::SHL, DL, VT,
8908 DAG.getConstant(Log2_32(MulAmt - 1),
8910 } else if (isPowerOf2_32(MulAmt + 1)) {
8911 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8912 Res = DAG.getNode(ISD::SUB, DL, VT,
8913 DAG.getNode(ISD::SHL, DL, VT,
8915 DAG.getConstant(Log2_32(MulAmt + 1),
8921 uint64_t MulAmtAbs = -MulAmt;
8922 if (isPowerOf2_32(MulAmtAbs + 1)) {
8923 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8924 Res = DAG.getNode(ISD::SUB, DL, VT,
8926 DAG.getNode(ISD::SHL, DL, VT,
8928 DAG.getConstant(Log2_32(MulAmtAbs + 1),
8930 } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8931 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8932 Res = DAG.getNode(ISD::ADD, DL, VT,
8934 DAG.getNode(ISD::SHL, DL, VT,
8936 DAG.getConstant(Log2_32(MulAmtAbs-1),
8938 Res = DAG.getNode(ISD::SUB, DL, VT,
8939 DAG.getConstant(0, MVT::i32),Res);
8946 Res = DAG.getNode(ISD::SHL, DL, VT,
8947 Res, DAG.getConstant(ShiftAmt, MVT::i32));
8949 // Do not add new nodes to DAG combiner worklist.
8950 DCI.CombineTo(N, Res, false);
8954 static SDValue PerformANDCombine(SDNode *N,
8955 TargetLowering::DAGCombinerInfo &DCI,
8956 const ARMSubtarget *Subtarget) {
8958 // Attempt to use immediate-form VBIC
8959 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8961 EVT VT = N->getValueType(0);
8962 SelectionDAG &DAG = DCI.DAG;
8964 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8967 APInt SplatBits, SplatUndef;
8968 unsigned SplatBitSize;
8971 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8972 if (SplatBitSize <= 64) {
8974 SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8975 SplatUndef.getZExtValue(), SplatBitSize,
8976 DAG, VbicVT, VT.is128BitVector(),
8978 if (Val.getNode()) {
8980 DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8981 SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8982 return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8987 if (!Subtarget->isThumb1Only()) {
8988 // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8989 SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8990 if (Result.getNode())
8997 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8998 static SDValue PerformORCombine(SDNode *N,
8999 TargetLowering::DAGCombinerInfo &DCI,
9000 const ARMSubtarget *Subtarget) {
9001 // Attempt to use immediate-form VORR
9002 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9004 EVT VT = N->getValueType(0);
9005 SelectionDAG &DAG = DCI.DAG;
9007 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9010 APInt SplatBits, SplatUndef;
9011 unsigned SplatBitSize;
9013 if (BVN && Subtarget->hasNEON() &&
9014 BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9015 if (SplatBitSize <= 64) {
9017 SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9018 SplatUndef.getZExtValue(), SplatBitSize,
9019 DAG, VorrVT, VT.is128BitVector(),
9021 if (Val.getNode()) {
9023 DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9024 SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9025 return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9030 if (!Subtarget->isThumb1Only()) {
9031 // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9032 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9033 if (Result.getNode())
9037 // The code below optimizes (or (and X, Y), Z).
9038 // The AND operand needs to have a single user to make these optimizations
9040 SDValue N0 = N->getOperand(0);
9041 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9043 SDValue N1 = N->getOperand(1);
9045 // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9046 if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9047 DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9049 unsigned SplatBitSize;
9052 APInt SplatBits0, SplatBits1;
9053 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9054 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9055 // Ensure that the second operand of both ands are constants
9056 if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9057 HasAnyUndefs) && !HasAnyUndefs) {
9058 if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9059 HasAnyUndefs) && !HasAnyUndefs) {
9060 // Ensure that the bit width of the constants are the same and that
9061 // the splat arguments are logical inverses as per the pattern we
9062 // are trying to simplify.
9063 if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9064 SplatBits0 == ~SplatBits1) {
9065 // Canonicalize the vector type to make instruction selection
9067 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9068 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9072 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9078 // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9081 // BFI is only available on V6T2+
9082 if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9086 // 1) or (and A, mask), val => ARMbfi A, val, mask
9087 // iff (val & mask) == val
9089 // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9090 // 2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9091 // && mask == ~mask2
9092 // 2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9093 // && ~mask == mask2
9094 // (i.e., copy a bitfield value into another bitfield of the same width)
9099 SDValue N00 = N0.getOperand(0);
9101 // The value and the mask need to be constants so we can verify this is
9102 // actually a bitfield set. If the mask is 0xffff, we can do better
9103 // via a movt instruction, so don't use BFI in that case.
9104 SDValue MaskOp = N0.getOperand(1);
9105 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9108 unsigned Mask = MaskC->getZExtValue();
9112 // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9113 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9115 unsigned Val = N1C->getZExtValue();
9116 if ((Val & ~Mask) != Val)
9119 if (ARM::isBitFieldInvertedMask(Mask)) {
9120 Val >>= countTrailingZeros(~Mask);
9122 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9123 DAG.getConstant(Val, MVT::i32),
9124 DAG.getConstant(Mask, MVT::i32));
9126 // Do not add new nodes to DAG combiner worklist.
9127 DCI.CombineTo(N, Res, false);
9130 } else if (N1.getOpcode() == ISD::AND) {
9131 // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9132 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9135 unsigned Mask2 = N11C->getZExtValue();
9137 // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9139 if (ARM::isBitFieldInvertedMask(Mask) &&
9141 // The pack halfword instruction works better for masks that fit it,
9142 // so use that when it's available.
9143 if (Subtarget->hasT2ExtractPack() &&
9144 (Mask == 0xffff || Mask == 0xffff0000))
9147 unsigned amt = countTrailingZeros(Mask2);
9148 Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9149 DAG.getConstant(amt, MVT::i32));
9150 Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9151 DAG.getConstant(Mask, MVT::i32));
9152 // Do not add new nodes to DAG combiner worklist.
9153 DCI.CombineTo(N, Res, false);
9155 } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9157 // The pack halfword instruction works better for masks that fit it,
9158 // so use that when it's available.
9159 if (Subtarget->hasT2ExtractPack() &&
9160 (Mask2 == 0xffff || Mask2 == 0xffff0000))
9163 unsigned lsb = countTrailingZeros(Mask);
9164 Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9165 DAG.getConstant(lsb, MVT::i32));
9166 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9167 DAG.getConstant(Mask2, MVT::i32));
9168 // Do not add new nodes to DAG combiner worklist.
9169 DCI.CombineTo(N, Res, false);
9174 if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9175 N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9176 ARM::isBitFieldInvertedMask(~Mask)) {
9177 // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9178 // where lsb(mask) == #shamt and masked bits of B are known zero.
9179 SDValue ShAmt = N00.getOperand(1);
9180 unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9181 unsigned LSB = countTrailingZeros(Mask);
9185 Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9186 DAG.getConstant(~Mask, MVT::i32));
9188 // Do not add new nodes to DAG combiner worklist.
9189 DCI.CombineTo(N, Res, false);
9195 static SDValue PerformXORCombine(SDNode *N,
9196 TargetLowering::DAGCombinerInfo &DCI,
9197 const ARMSubtarget *Subtarget) {
9198 EVT VT = N->getValueType(0);
9199 SelectionDAG &DAG = DCI.DAG;
9201 if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9204 if (!Subtarget->isThumb1Only()) {
9205 // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9206 SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
9207 if (Result.getNode())
9214 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9215 /// the bits being cleared by the AND are not demanded by the BFI.
9216 static SDValue PerformBFICombine(SDNode *N,
9217 TargetLowering::DAGCombinerInfo &DCI) {
9218 SDValue N1 = N->getOperand(1);
9219 if (N1.getOpcode() == ISD::AND) {
9220 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9223 unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9224 unsigned LSB = countTrailingZeros(~InvMask);
9225 unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9226 unsigned Mask = (1 << Width)-1;
9227 unsigned Mask2 = N11C->getZExtValue();
9228 if ((Mask & (~Mask2)) == 0)
9229 return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9230 N->getOperand(0), N1.getOperand(0),
9236 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
9237 /// ARMISD::VMOVRRD.
9238 static SDValue PerformVMOVRRDCombine(SDNode *N,
9239 TargetLowering::DAGCombinerInfo &DCI) {
9240 // vmovrrd(vmovdrr x, y) -> x,y
9241 SDValue InDouble = N->getOperand(0);
9242 if (InDouble.getOpcode() == ARMISD::VMOVDRR)
9243 return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
9245 // vmovrrd(load f64) -> (load i32), (load i32)
9246 SDNode *InNode = InDouble.getNode();
9247 if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
9248 InNode->getValueType(0) == MVT::f64 &&
9249 InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
9250 !cast<LoadSDNode>(InNode)->isVolatile()) {
9251 // TODO: Should this be done for non-FrameIndex operands?
9252 LoadSDNode *LD = cast<LoadSDNode>(InNode);
9254 SelectionDAG &DAG = DCI.DAG;
9256 SDValue BasePtr = LD->getBasePtr();
9257 SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
9258 LD->getPointerInfo(), LD->isVolatile(),
9259 LD->isNonTemporal(), LD->isInvariant(),
9260 LD->getAlignment());
9262 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9263 DAG.getConstant(4, MVT::i32));
9264 SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
9265 LD->getPointerInfo(), LD->isVolatile(),
9266 LD->isNonTemporal(), LD->isInvariant(),
9267 std::min(4U, LD->getAlignment() / 2));
9269 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
9270 SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
9271 DCI.RemoveFromWorklist(LD);
9279 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
9280 /// ARMISD::VMOVDRR. This is also used for BUILD_VECTORs with 2 operands.
9281 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
9282 // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
9283 SDValue Op0 = N->getOperand(0);
9284 SDValue Op1 = N->getOperand(1);
9285 if (Op0.getOpcode() == ISD::BITCAST)
9286 Op0 = Op0.getOperand(0);
9287 if (Op1.getOpcode() == ISD::BITCAST)
9288 Op1 = Op1.getOperand(0);
9289 if (Op0.getOpcode() == ARMISD::VMOVRRD &&
9290 Op0.getNode() == Op1.getNode() &&
9291 Op0.getResNo() == 0 && Op1.getResNo() == 1)
9292 return DAG.getNode(ISD::BITCAST, SDLoc(N),
9293 N->getValueType(0), Op0.getOperand(0));
9297 /// PerformSTORECombine - Target-specific dag combine xforms for
9299 static SDValue PerformSTORECombine(SDNode *N,
9300 TargetLowering::DAGCombinerInfo &DCI) {
9301 StoreSDNode *St = cast<StoreSDNode>(N);
9302 if (St->isVolatile())
9305 // Optimize trunc store (of multiple scalars) to shuffle and store. First,
9306 // pack all of the elements in one place. Next, store to memory in fewer
9308 SDValue StVal = St->getValue();
9309 EVT VT = StVal.getValueType();
9310 if (St->isTruncatingStore() && VT.isVector()) {
9311 SelectionDAG &DAG = DCI.DAG;
9312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9313 EVT StVT = St->getMemoryVT();
9314 unsigned NumElems = VT.getVectorNumElements();
9315 assert(StVT != VT && "Cannot truncate to the same type");
9316 unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9317 unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9319 // From, To sizes and ElemCount must be pow of two
9320 if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9322 // We are going to use the original vector elt for storing.
9323 // Accumulated smaller vector elements must be a multiple of the store size.
9324 if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9326 unsigned SizeRatio = FromEltSz / ToEltSz;
9327 assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9329 // Create a type on which we perform the shuffle.
9330 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9331 NumElems*SizeRatio);
9332 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9335 SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9336 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9337 for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
9339 // Can't shuffle using an illegal type.
9340 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9342 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9343 DAG.getUNDEF(WideVec.getValueType()),
9345 // At this point all of the data is stored at the bottom of the
9346 // register. We now need to save it to mem.
9348 // Find the largest store unit
9349 MVT StoreType = MVT::i8;
9350 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9351 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9352 MVT Tp = (MVT::SimpleValueType)tp;
9353 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9356 // Didn't find a legal store type.
9357 if (!TLI.isTypeLegal(StoreType))
9360 // Bitcast the original vector into a vector of store-size units
9361 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9362 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9363 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9364 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9365 SmallVector<SDValue, 8> Chains;
9366 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9367 TLI.getPointerTy());
9368 SDValue BasePtr = St->getBasePtr();
9370 // Perform one or more big stores into memory.
9371 unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9372 for (unsigned I = 0; I < E; I++) {
9373 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9374 StoreType, ShuffWide,
9375 DAG.getIntPtrConstant(I));
9376 SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9377 St->getPointerInfo(), St->isVolatile(),
9378 St->isNonTemporal(), St->getAlignment());
9379 BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9381 Chains.push_back(Ch);
9383 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9387 if (!ISD::isNormalStore(St))
9390 // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9391 // ARM stores of arguments in the same cache line.
9392 if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9393 StVal.getNode()->hasOneUse()) {
9394 SelectionDAG &DAG = DCI.DAG;
9396 SDValue BasePtr = St->getBasePtr();
9397 SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9398 StVal.getNode()->getOperand(0), BasePtr,
9399 St->getPointerInfo(), St->isVolatile(),
9400 St->isNonTemporal(), St->getAlignment());
9402 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9403 DAG.getConstant(4, MVT::i32));
9404 return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9405 OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9406 St->isNonTemporal(),
9407 std::min(4U, St->getAlignment() / 2));
9410 if (StVal.getValueType() != MVT::i64 ||
9411 StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9414 // Bitcast an i64 store extracted from a vector to f64.
9415 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9416 SelectionDAG &DAG = DCI.DAG;
9418 SDValue IntVec = StVal.getOperand(0);
9419 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9420 IntVec.getValueType().getVectorNumElements());
9421 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9422 SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9423 Vec, StVal.getOperand(1));
9425 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9426 // Make the DAGCombiner fold the bitcasts.
9427 DCI.AddToWorklist(Vec.getNode());
9428 DCI.AddToWorklist(ExtElt.getNode());
9429 DCI.AddToWorklist(V.getNode());
9430 return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9431 St->getPointerInfo(), St->isVolatile(),
9432 St->isNonTemporal(), St->getAlignment(),
9436 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9437 /// are normal, non-volatile loads. If so, it is profitable to bitcast an
9438 /// i64 vector to have f64 elements, since the value can then be loaded
9439 /// directly into a VFP register.
9440 static bool hasNormalLoadOperand(SDNode *N) {
9441 unsigned NumElts = N->getValueType(0).getVectorNumElements();
9442 for (unsigned i = 0; i < NumElts; ++i) {
9443 SDNode *Elt = N->getOperand(i).getNode();
9444 if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9450 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9451 /// ISD::BUILD_VECTOR.
9452 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9453 TargetLowering::DAGCombinerInfo &DCI){
9454 // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9455 // VMOVRRD is introduced when legalizing i64 types. It forces the i64 value
9456 // into a pair of GPRs, which is fine when the value is used as a scalar,
9457 // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9458 SelectionDAG &DAG = DCI.DAG;
9459 if (N->getNumOperands() == 2) {
9460 SDValue RV = PerformVMOVDRRCombine(N, DAG);
9465 // Load i64 elements as f64 values so that type legalization does not split
9466 // them up into i32 values.
9467 EVT VT = N->getValueType(0);
9468 if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9471 SmallVector<SDValue, 8> Ops;
9472 unsigned NumElts = VT.getVectorNumElements();
9473 for (unsigned i = 0; i < NumElts; ++i) {
9474 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9476 // Make the DAGCombiner fold the bitcast.
9477 DCI.AddToWorklist(V.getNode());
9479 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9480 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9481 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9484 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9486 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9487 // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9488 // At that time, we may have inserted bitcasts from integer to float.
9489 // If these bitcasts have survived DAGCombine, change the lowering of this
9490 // BUILD_VECTOR in something more vector friendly, i.e., that does not
9491 // force to use floating point types.
9493 // Make sure we can change the type of the vector.
9494 // This is possible iff:
9495 // 1. The vector is only used in a bitcast to a integer type. I.e.,
9496 // 1.1. Vector is used only once.
9497 // 1.2. Use is a bit convert to an integer type.
9498 // 2. The size of its operands are 32-bits (64-bits are not legal).
9499 EVT VT = N->getValueType(0);
9500 EVT EltVT = VT.getVectorElementType();
9502 // Check 1.1. and 2.
9503 if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9506 // By construction, the input type must be float.
9507 assert(EltVT == MVT::f32 && "Unexpected type!");
9510 SDNode *Use = *N->use_begin();
9511 if (Use->getOpcode() != ISD::BITCAST ||
9512 Use->getValueType(0).isFloatingPoint())
9515 // Check profitability.
9516 // Model is, if more than half of the relevant operands are bitcast from
9517 // i32, turn the build_vector into a sequence of insert_vector_elt.
9518 // Relevant operands are everything that is not statically
9519 // (i.e., at compile time) bitcasted.
9520 unsigned NumOfBitCastedElts = 0;
9521 unsigned NumElts = VT.getVectorNumElements();
9522 unsigned NumOfRelevantElts = NumElts;
9523 for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9524 SDValue Elt = N->getOperand(Idx);
9525 if (Elt->getOpcode() == ISD::BITCAST) {
9526 // Assume only bit cast to i32 will go away.
9527 if (Elt->getOperand(0).getValueType() == MVT::i32)
9528 ++NumOfBitCastedElts;
9529 } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9530 // Constants are statically casted, thus do not count them as
9531 // relevant operands.
9532 --NumOfRelevantElts;
9535 // Check if more than half of the elements require a non-free bitcast.
9536 if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9539 SelectionDAG &DAG = DCI.DAG;
9540 // Create the new vector type.
9541 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9542 // Check if the type is legal.
9543 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9544 if (!TLI.isTypeLegal(VecVT))
9548 // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9549 // => BITCAST INSERT_VECTOR_ELT
9550 // (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9552 SDValue Vec = DAG.getUNDEF(VecVT);
9554 for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9555 SDValue V = N->getOperand(Idx);
9556 if (V.getOpcode() == ISD::UNDEF)
9558 if (V.getOpcode() == ISD::BITCAST &&
9559 V->getOperand(0).getValueType() == MVT::i32)
9560 // Fold obvious case.
9561 V = V.getOperand(0);
9563 V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9564 // Make the DAGCombiner fold the bitcasts.
9565 DCI.AddToWorklist(V.getNode());
9567 SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9568 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9570 Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9571 // Make the DAGCombiner fold the bitcasts.
9572 DCI.AddToWorklist(Vec.getNode());
9576 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9577 /// ISD::INSERT_VECTOR_ELT.
9578 static SDValue PerformInsertEltCombine(SDNode *N,
9579 TargetLowering::DAGCombinerInfo &DCI) {
9580 // Bitcast an i64 load inserted into a vector to f64.
9581 // Otherwise, the i64 value will be legalized to a pair of i32 values.
9582 EVT VT = N->getValueType(0);
9583 SDNode *Elt = N->getOperand(1).getNode();
9584 if (VT.getVectorElementType() != MVT::i64 ||
9585 !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9588 SelectionDAG &DAG = DCI.DAG;
9590 EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9591 VT.getVectorNumElements());
9592 SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9593 SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9594 // Make the DAGCombiner fold the bitcasts.
9595 DCI.AddToWorklist(Vec.getNode());
9596 DCI.AddToWorklist(V.getNode());
9597 SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9598 Vec, V, N->getOperand(2));
9599 return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9602 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9603 /// ISD::VECTOR_SHUFFLE.
9604 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9605 // The LLVM shufflevector instruction does not require the shuffle mask
9606 // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9607 // have that requirement. When translating to ISD::VECTOR_SHUFFLE, if the
9608 // operands do not match the mask length, they are extended by concatenating
9609 // them with undef vectors. That is probably the right thing for other
9610 // targets, but for NEON it is better to concatenate two double-register
9611 // size vector operands into a single quad-register size vector. Do that
9612 // transformation here:
9613 // shuffle(concat(v1, undef), concat(v2, undef)) ->
9614 // shuffle(concat(v1, v2), undef)
9615 SDValue Op0 = N->getOperand(0);
9616 SDValue Op1 = N->getOperand(1);
9617 if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9618 Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9619 Op0.getNumOperands() != 2 ||
9620 Op1.getNumOperands() != 2)
9622 SDValue Concat0Op1 = Op0.getOperand(1);
9623 SDValue Concat1Op1 = Op1.getOperand(1);
9624 if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9625 Concat1Op1.getOpcode() != ISD::UNDEF)
9627 // Skip the transformation if any of the types are illegal.
9628 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9629 EVT VT = N->getValueType(0);
9630 if (!TLI.isTypeLegal(VT) ||
9631 !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9632 !TLI.isTypeLegal(Concat1Op1.getValueType()))
9635 SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9636 Op0.getOperand(0), Op1.getOperand(0));
9637 // Translate the shuffle mask.
9638 SmallVector<int, 16> NewMask;
9639 unsigned NumElts = VT.getVectorNumElements();
9640 unsigned HalfElts = NumElts/2;
9641 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9642 for (unsigned n = 0; n < NumElts; ++n) {
9643 int MaskElt = SVN->getMaskElt(n);
9645 if (MaskElt < (int)HalfElts)
9647 else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9648 NewElt = HalfElts + MaskElt - NumElts;
9649 NewMask.push_back(NewElt);
9651 return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9652 DAG.getUNDEF(VT), NewMask.data());
9655 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9656 /// NEON load/store intrinsics to merge base address updates.
9657 static SDValue CombineBaseUpdate(SDNode *N,
9658 TargetLowering::DAGCombinerInfo &DCI) {
9659 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9662 SelectionDAG &DAG = DCI.DAG;
9663 bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9664 N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9665 unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9666 SDValue Addr = N->getOperand(AddrOpIdx);
9668 // Search for a use of the address operand that is an increment.
9669 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9670 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9672 if (User->getOpcode() != ISD::ADD ||
9673 UI.getUse().getResNo() != Addr.getResNo())
9676 // Check that the add is independent of the load/store. Otherwise, folding
9677 // it would create a cycle.
9678 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9681 // Find the new opcode for the updating load/store.
9683 bool isLaneOp = false;
9684 unsigned NewOpc = 0;
9685 unsigned NumVecs = 0;
9687 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9689 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9690 case Intrinsic::arm_neon_vld1: NewOpc = ARMISD::VLD1_UPD;
9692 case Intrinsic::arm_neon_vld2: NewOpc = ARMISD::VLD2_UPD;
9694 case Intrinsic::arm_neon_vld3: NewOpc = ARMISD::VLD3_UPD;
9696 case Intrinsic::arm_neon_vld4: NewOpc = ARMISD::VLD4_UPD;
9698 case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9699 NumVecs = 2; isLaneOp = true; break;
9700 case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9701 NumVecs = 3; isLaneOp = true; break;
9702 case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9703 NumVecs = 4; isLaneOp = true; break;
9704 case Intrinsic::arm_neon_vst1: NewOpc = ARMISD::VST1_UPD;
9705 NumVecs = 1; isLoad = false; break;
9706 case Intrinsic::arm_neon_vst2: NewOpc = ARMISD::VST2_UPD;
9707 NumVecs = 2; isLoad = false; break;
9708 case Intrinsic::arm_neon_vst3: NewOpc = ARMISD::VST3_UPD;
9709 NumVecs = 3; isLoad = false; break;
9710 case Intrinsic::arm_neon_vst4: NewOpc = ARMISD::VST4_UPD;
9711 NumVecs = 4; isLoad = false; break;
9712 case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9713 NumVecs = 2; isLoad = false; isLaneOp = true; break;
9714 case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9715 NumVecs = 3; isLoad = false; isLaneOp = true; break;
9716 case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9717 NumVecs = 4; isLoad = false; isLaneOp = true; break;
9721 switch (N->getOpcode()) {
9722 default: llvm_unreachable("unexpected opcode for Neon base update");
9723 case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9724 case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9725 case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9729 // Find the size of memory referenced by the load/store.
9732 VecTy = N->getValueType(0);
9734 VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9735 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9737 NumBytes /= VecTy.getVectorNumElements();
9739 // If the increment is a constant, it must match the memory ref size.
9740 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9741 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9742 uint64_t IncVal = CInc->getZExtValue();
9743 if (IncVal != NumBytes)
9745 } else if (NumBytes >= 3 * 16) {
9746 // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9747 // separate instructions that make it harder to use a non-constant update.
9751 // Create the new updating load/store node.
9753 unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9755 for (n = 0; n < NumResultVecs; ++n)
9757 Tys[n++] = MVT::i32;
9758 Tys[n] = MVT::Other;
9759 SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9760 SmallVector<SDValue, 8> Ops;
9761 Ops.push_back(N->getOperand(0)); // incoming chain
9762 Ops.push_back(N->getOperand(AddrOpIdx));
9764 for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9765 Ops.push_back(N->getOperand(i));
9767 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9768 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9769 Ops.data(), Ops.size(),
9770 MemInt->getMemoryVT(),
9771 MemInt->getMemOperand());
9774 std::vector<SDValue> NewResults;
9775 for (unsigned i = 0; i < NumResultVecs; ++i) {
9776 NewResults.push_back(SDValue(UpdN.getNode(), i));
9778 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9779 DCI.CombineTo(N, NewResults);
9780 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9787 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9788 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9789 /// are also VDUPLANEs. If so, combine them to a vldN-dup operation and
9791 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9792 SelectionDAG &DAG = DCI.DAG;
9793 EVT VT = N->getValueType(0);
9794 // vldN-dup instructions only support 64-bit vectors for N > 1.
9795 if (!VT.is64BitVector())
9798 // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9799 SDNode *VLD = N->getOperand(0).getNode();
9800 if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9802 unsigned NumVecs = 0;
9803 unsigned NewOpc = 0;
9804 unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9805 if (IntNo == Intrinsic::arm_neon_vld2lane) {
9807 NewOpc = ARMISD::VLD2DUP;
9808 } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9810 NewOpc = ARMISD::VLD3DUP;
9811 } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9813 NewOpc = ARMISD::VLD4DUP;
9818 // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9819 // numbers match the load.
9820 unsigned VLDLaneNo =
9821 cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9822 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9824 // Ignore uses of the chain result.
9825 if (UI.getUse().getResNo() == NumVecs)
9828 if (User->getOpcode() != ARMISD::VDUPLANE ||
9829 VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9833 // Create the vldN-dup node.
9836 for (n = 0; n < NumVecs; ++n)
9838 Tys[n] = MVT::Other;
9839 SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9840 SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9841 MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9842 SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9843 Ops, 2, VLDMemInt->getMemoryVT(),
9844 VLDMemInt->getMemOperand());
9847 for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9849 unsigned ResNo = UI.getUse().getResNo();
9850 // Ignore uses of the chain result.
9851 if (ResNo == NumVecs)
9854 DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9857 // Now the vldN-lane intrinsic is dead except for its chain result.
9858 // Update uses of the chain.
9859 std::vector<SDValue> VLDDupResults;
9860 for (unsigned n = 0; n < NumVecs; ++n)
9861 VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9862 VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9863 DCI.CombineTo(VLD, VLDDupResults);
9868 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9869 /// ARMISD::VDUPLANE.
9870 static SDValue PerformVDUPLANECombine(SDNode *N,
9871 TargetLowering::DAGCombinerInfo &DCI) {
9872 SDValue Op = N->getOperand(0);
9874 // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9875 // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9876 if (CombineVLDDUP(N, DCI))
9877 return SDValue(N, 0);
9879 // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9880 // redundant. Ignore bit_converts for now; element sizes are checked below.
9881 while (Op.getOpcode() == ISD::BITCAST)
9882 Op = Op.getOperand(0);
9883 if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9886 // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9887 unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9888 // The canonical VMOV for a zero vector uses a 32-bit element size.
9889 unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9891 if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9893 EVT VT = N->getValueType(0);
9894 if (EltSize > VT.getVectorElementType().getSizeInBits())
9897 return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9900 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9901 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9902 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9906 for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9908 ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9913 APFloat APF = C->getValueAPF();
9914 if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9915 != APFloat::opOK || !isExact)
9918 c0 = (I == 0) ? cN : c0;
9919 if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9926 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9927 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9928 /// when the VMUL has a constant operand that is a power of 2.
9930 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9931 /// vmul.f32 d16, d17, d16
9932 /// vcvt.s32.f32 d16, d16
9934 /// vcvt.s32.f32 d16, d16, #3
9935 static SDValue PerformVCVTCombine(SDNode *N,
9936 TargetLowering::DAGCombinerInfo &DCI,
9937 const ARMSubtarget *Subtarget) {
9938 SelectionDAG &DAG = DCI.DAG;
9939 SDValue Op = N->getOperand(0);
9941 if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9942 Op.getOpcode() != ISD::FMUL)
9946 SDValue N0 = Op->getOperand(0);
9947 SDValue ConstVec = Op->getOperand(1);
9948 bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9950 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9951 !isConstVecPow2(ConstVec, isSigned, C))
9954 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9955 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9956 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9957 // These instructions only exist converting from f32 to i32. We can handle
9958 // smaller integers by generating an extra truncate, but larger ones would
9963 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9964 Intrinsic::arm_neon_vcvtfp2fxu;
9965 unsigned NumLanes = Op.getValueType().getVectorNumElements();
9966 SDValue FixConv = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9967 NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9968 DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9969 DAG.getConstant(Log2_64(C), MVT::i32));
9971 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9972 FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9977 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9978 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9979 /// when the VDIV has a constant operand that is a power of 2.
9981 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9982 /// vcvt.f32.s32 d16, d16
9983 /// vdiv.f32 d16, d17, d16
9985 /// vcvt.f32.s32 d16, d16, #3
9986 static SDValue PerformVDIVCombine(SDNode *N,
9987 TargetLowering::DAGCombinerInfo &DCI,
9988 const ARMSubtarget *Subtarget) {
9989 SelectionDAG &DAG = DCI.DAG;
9990 SDValue Op = N->getOperand(0);
9991 unsigned OpOpcode = Op.getNode()->getOpcode();
9993 if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9994 (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9998 SDValue ConstVec = N->getOperand(1);
9999 bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10001 if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
10002 !isConstVecPow2(ConstVec, isSigned, C))
10005 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10006 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10007 if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
10008 // These instructions only exist converting from i32 to f32. We can handle
10009 // smaller integers by generating an extra extend, but larger ones would
10014 SDValue ConvInput = Op.getOperand(0);
10015 unsigned NumLanes = Op.getValueType().getVectorNumElements();
10016 if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
10017 ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10018 SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10021 unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10022 Intrinsic::arm_neon_vcvtfxu2fp;
10023 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
10025 DAG.getConstant(IntrinsicOpcode, MVT::i32),
10026 ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
10029 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10030 /// operand of a vector shift operation, where all the elements of the
10031 /// build_vector must have the same constant integer value.
10032 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10033 // Ignore bit_converts.
10034 while (Op.getOpcode() == ISD::BITCAST)
10035 Op = Op.getOperand(0);
10036 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10037 APInt SplatBits, SplatUndef;
10038 unsigned SplatBitSize;
10040 if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10041 HasAnyUndefs, ElementBits) ||
10042 SplatBitSize > ElementBits)
10044 Cnt = SplatBits.getSExtValue();
10048 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10049 /// operand of a vector shift left operation. That value must be in the range:
10050 /// 0 <= Value < ElementBits for a left shift; or
10051 /// 0 <= Value <= ElementBits for a long left shift.
10052 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10053 assert(VT.isVector() && "vector shift count is not a vector type");
10054 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
10055 if (! getVShiftImm(Op, ElementBits, Cnt))
10057 return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10060 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10061 /// operand of a vector shift right operation. For a shift opcode, the value
10062 /// is positive, but for an intrinsic the value count must be negative. The
10063 /// absolute value must be in the range:
10064 /// 1 <= |Value| <= ElementBits for a right shift; or
10065 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
10066 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10068 assert(VT.isVector() && "vector shift count is not a vector type");
10069 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
10070 if (! getVShiftImm(Op, ElementBits, Cnt))
10074 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10077 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10078 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10079 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10082 // Don't do anything for most intrinsics.
10085 // Vector shifts: check for immediate versions and lower them.
10086 // Note: This is done during DAG combining instead of DAG legalizing because
10087 // the build_vectors for 64-bit vector element shift counts are generally
10088 // not legal, and it is hard to see their values after they get legalized to
10089 // loads from a constant pool.
10090 case Intrinsic::arm_neon_vshifts:
10091 case Intrinsic::arm_neon_vshiftu:
10092 case Intrinsic::arm_neon_vshiftls:
10093 case Intrinsic::arm_neon_vshiftlu:
10094 case Intrinsic::arm_neon_vshiftn:
10095 case Intrinsic::arm_neon_vrshifts:
10096 case Intrinsic::arm_neon_vrshiftu:
10097 case Intrinsic::arm_neon_vrshiftn:
10098 case Intrinsic::arm_neon_vqshifts:
10099 case Intrinsic::arm_neon_vqshiftu:
10100 case Intrinsic::arm_neon_vqshiftsu:
10101 case Intrinsic::arm_neon_vqshiftns:
10102 case Intrinsic::arm_neon_vqshiftnu:
10103 case Intrinsic::arm_neon_vqshiftnsu:
10104 case Intrinsic::arm_neon_vqrshiftns:
10105 case Intrinsic::arm_neon_vqrshiftnu:
10106 case Intrinsic::arm_neon_vqrshiftnsu: {
10107 EVT VT = N->getOperand(1).getValueType();
10109 unsigned VShiftOpc = 0;
10112 case Intrinsic::arm_neon_vshifts:
10113 case Intrinsic::arm_neon_vshiftu:
10114 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10115 VShiftOpc = ARMISD::VSHL;
10118 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10119 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10120 ARMISD::VSHRs : ARMISD::VSHRu);
10125 case Intrinsic::arm_neon_vshiftls:
10126 case Intrinsic::arm_neon_vshiftlu:
10127 if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
10129 llvm_unreachable("invalid shift count for vshll intrinsic");
10131 case Intrinsic::arm_neon_vrshifts:
10132 case Intrinsic::arm_neon_vrshiftu:
10133 if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10137 case Intrinsic::arm_neon_vqshifts:
10138 case Intrinsic::arm_neon_vqshiftu:
10139 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10143 case Intrinsic::arm_neon_vqshiftsu:
10144 if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
10146 llvm_unreachable("invalid shift count for vqshlu intrinsic");
10148 case Intrinsic::arm_neon_vshiftn:
10149 case Intrinsic::arm_neon_vrshiftn:
10150 case Intrinsic::arm_neon_vqshiftns:
10151 case Intrinsic::arm_neon_vqshiftnu:
10152 case Intrinsic::arm_neon_vqshiftnsu:
10153 case Intrinsic::arm_neon_vqrshiftns:
10154 case Intrinsic::arm_neon_vqrshiftnu:
10155 case Intrinsic::arm_neon_vqrshiftnsu:
10156 // Narrowing shifts require an immediate right shift.
10157 if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
10159 llvm_unreachable("invalid shift count for narrowing vector shift "
10163 llvm_unreachable("unhandled vector shift");
10167 case Intrinsic::arm_neon_vshifts:
10168 case Intrinsic::arm_neon_vshiftu:
10169 // Opcode already set above.
10171 case Intrinsic::arm_neon_vshiftls:
10172 case Intrinsic::arm_neon_vshiftlu:
10173 if (Cnt == VT.getVectorElementType().getSizeInBits())
10174 VShiftOpc = ARMISD::VSHLLi;
10176 VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
10177 ARMISD::VSHLLs : ARMISD::VSHLLu);
10179 case Intrinsic::arm_neon_vshiftn:
10180 VShiftOpc = ARMISD::VSHRN; break;
10181 case Intrinsic::arm_neon_vrshifts:
10182 VShiftOpc = ARMISD::VRSHRs; break;
10183 case Intrinsic::arm_neon_vrshiftu:
10184 VShiftOpc = ARMISD::VRSHRu; break;
10185 case Intrinsic::arm_neon_vrshiftn:
10186 VShiftOpc = ARMISD::VRSHRN; break;
10187 case Intrinsic::arm_neon_vqshifts:
10188 VShiftOpc = ARMISD::VQSHLs; break;
10189 case Intrinsic::arm_neon_vqshiftu:
10190 VShiftOpc = ARMISD::VQSHLu; break;
10191 case Intrinsic::arm_neon_vqshiftsu:
10192 VShiftOpc = ARMISD::VQSHLsu; break;
10193 case Intrinsic::arm_neon_vqshiftns:
10194 VShiftOpc = ARMISD::VQSHRNs; break;
10195 case Intrinsic::arm_neon_vqshiftnu:
10196 VShiftOpc = ARMISD::VQSHRNu; break;
10197 case Intrinsic::arm_neon_vqshiftnsu:
10198 VShiftOpc = ARMISD::VQSHRNsu; break;
10199 case Intrinsic::arm_neon_vqrshiftns:
10200 VShiftOpc = ARMISD::VQRSHRNs; break;
10201 case Intrinsic::arm_neon_vqrshiftnu:
10202 VShiftOpc = ARMISD::VQRSHRNu; break;
10203 case Intrinsic::arm_neon_vqrshiftnsu:
10204 VShiftOpc = ARMISD::VQRSHRNsu; break;
10207 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
10208 N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
10211 case Intrinsic::arm_neon_vshiftins: {
10212 EVT VT = N->getOperand(1).getValueType();
10214 unsigned VShiftOpc = 0;
10216 if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10217 VShiftOpc = ARMISD::VSLI;
10218 else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10219 VShiftOpc = ARMISD::VSRI;
10221 llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10224 return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
10225 N->getOperand(1), N->getOperand(2),
10226 DAG.getConstant(Cnt, MVT::i32));
10229 case Intrinsic::arm_neon_vqrshifts:
10230 case Intrinsic::arm_neon_vqrshiftu:
10231 // No immediate versions of these to check for.
10238 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10239 /// lowers them. As with the vector shift intrinsics, this is done during DAG
10240 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10241 /// vector element shift counts are generally not legal, and it is hard to see
10242 /// their values after they get legalized to loads from a constant pool.
10243 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10244 const ARMSubtarget *ST) {
10245 EVT VT = N->getValueType(0);
10246 if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10247 // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10248 // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10249 SDValue N1 = N->getOperand(1);
10250 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10251 SDValue N0 = N->getOperand(0);
10252 if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10253 DAG.MaskedValueIsZero(N0.getOperand(0),
10254 APInt::getHighBitsSet(32, 16)))
10255 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10259 // Nothing to be done for scalar shifts.
10260 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10261 if (!VT.isVector() || !TLI.isTypeLegal(VT))
10264 assert(ST->hasNEON() && "unexpected vector shift");
10267 switch (N->getOpcode()) {
10268 default: llvm_unreachable("unexpected shift opcode");
10271 if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
10272 return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
10273 DAG.getConstant(Cnt, MVT::i32));
10278 if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10279 unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10280 ARMISD::VSHRs : ARMISD::VSHRu);
10281 return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
10282 DAG.getConstant(Cnt, MVT::i32));
10288 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10289 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10290 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10291 const ARMSubtarget *ST) {
10292 SDValue N0 = N->getOperand(0);
10294 // Check for sign- and zero-extensions of vector extract operations of 8-
10295 // and 16-bit vector elements. NEON supports these directly. They are
10296 // handled during DAG combining because type legalization will promote them
10297 // to 32-bit types and it is messy to recognize the operations after that.
10298 if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10299 SDValue Vec = N0.getOperand(0);
10300 SDValue Lane = N0.getOperand(1);
10301 EVT VT = N->getValueType(0);
10302 EVT EltVT = N0.getValueType();
10303 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10305 if (VT == MVT::i32 &&
10306 (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10307 TLI.isTypeLegal(Vec.getValueType()) &&
10308 isa<ConstantSDNode>(Lane)) {
10311 switch (N->getOpcode()) {
10312 default: llvm_unreachable("unexpected opcode");
10313 case ISD::SIGN_EXTEND:
10314 Opc = ARMISD::VGETLANEs;
10316 case ISD::ZERO_EXTEND:
10317 case ISD::ANY_EXTEND:
10318 Opc = ARMISD::VGETLANEu;
10321 return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10328 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10329 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10330 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10331 const ARMSubtarget *ST) {
10332 // If the target supports NEON, try to use vmax/vmin instructions for f32
10333 // selects like "x < y ? x : y". Unless the NoNaNsFPMath option is set,
10334 // be careful about NaNs: NEON's vmax/vmin return NaN if either operand is
10335 // a NaN; only do the transformation when it matches that behavior.
10337 // For now only do this when using NEON for FP operations; if using VFP, it
10338 // is not obvious that the benefit outweighs the cost of switching to the
10340 if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10341 N->getValueType(0) != MVT::f32)
10344 SDValue CondLHS = N->getOperand(0);
10345 SDValue CondRHS = N->getOperand(1);
10346 SDValue LHS = N->getOperand(2);
10347 SDValue RHS = N->getOperand(3);
10348 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10350 unsigned Opcode = 0;
10352 if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10353 IsReversed = false; // x CC y ? x : y
10354 } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10355 IsReversed = true ; // x CC y ? y : x
10369 // If LHS is NaN, an ordered comparison will be false and the result will
10370 // be the RHS, but vmin(NaN, RHS) = NaN. Avoid this by checking that LHS
10371 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10372 IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10373 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10375 // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10376 // will return -0, so vmin can only be used for unsafe math or if one of
10377 // the operands is known to be nonzero.
10378 if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10379 !DAG.getTarget().Options.UnsafeFPMath &&
10380 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10382 Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10391 // If LHS is NaN, an ordered comparison will be false and the result will
10392 // be the RHS, but vmax(NaN, RHS) = NaN. Avoid this by checking that LHS
10393 // != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
10394 IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10395 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10397 // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10398 // will return +0, so vmax can only be used for unsafe math or if one of
10399 // the operands is known to be nonzero.
10400 if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10401 !DAG.getTarget().Options.UnsafeFPMath &&
10402 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10404 Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10410 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10413 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10415 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10416 SDValue Cmp = N->getOperand(4);
10417 if (Cmp.getOpcode() != ARMISD::CMPZ)
10418 // Only looking at EQ and NE cases.
10421 EVT VT = N->getValueType(0);
10423 SDValue LHS = Cmp.getOperand(0);
10424 SDValue RHS = Cmp.getOperand(1);
10425 SDValue FalseVal = N->getOperand(0);
10426 SDValue TrueVal = N->getOperand(1);
10427 SDValue ARMcc = N->getOperand(2);
10428 ARMCC::CondCodes CC =
10429 (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10447 /// FIXME: Turn this into a target neutral optimization?
10449 if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10450 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10451 N->getOperand(3), Cmp);
10452 } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10454 SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10455 Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10456 N->getOperand(3), NewCmp);
10459 if (Res.getNode()) {
10460 APInt KnownZero, KnownOne;
10461 DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10462 // Capture demanded bits information that would be otherwise lost.
10463 if (KnownZero == 0xfffffffe)
10464 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10465 DAG.getValueType(MVT::i1));
10466 else if (KnownZero == 0xffffff00)
10467 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10468 DAG.getValueType(MVT::i8));
10469 else if (KnownZero == 0xffff0000)
10470 Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10471 DAG.getValueType(MVT::i16));
10477 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10478 DAGCombinerInfo &DCI) const {
10479 switch (N->getOpcode()) {
10481 case ISD::ADDC: return PerformADDCCombine(N, DCI, Subtarget);
10482 case ISD::ADD: return PerformADDCombine(N, DCI, Subtarget);
10483 case ISD::SUB: return PerformSUBCombine(N, DCI);
10484 case ISD::MUL: return PerformMULCombine(N, DCI, Subtarget);
10485 case ISD::OR: return PerformORCombine(N, DCI, Subtarget);
10486 case ISD::XOR: return PerformXORCombine(N, DCI, Subtarget);
10487 case ISD::AND: return PerformANDCombine(N, DCI, Subtarget);
10488 case ARMISD::BFI: return PerformBFICombine(N, DCI);
10489 case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10490 case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10491 case ISD::STORE: return PerformSTORECombine(N, DCI);
10492 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10493 case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10494 case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10495 case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10496 case ISD::FP_TO_SINT:
10497 case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10498 case ISD::FDIV: return PerformVDIVCombine(N, DCI, Subtarget);
10499 case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10502 case ISD::SRL: return PerformShiftCombine(N, DCI.DAG, Subtarget);
10503 case ISD::SIGN_EXTEND:
10504 case ISD::ZERO_EXTEND:
10505 case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10506 case ISD::SELECT_CC: return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10507 case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10508 case ARMISD::VLD2DUP:
10509 case ARMISD::VLD3DUP:
10510 case ARMISD::VLD4DUP:
10511 return CombineBaseUpdate(N, DCI);
10512 case ARMISD::BUILD_VECTOR:
10513 return PerformARMBUILD_VECTORCombine(N, DCI);
10514 case ISD::INTRINSIC_VOID:
10515 case ISD::INTRINSIC_W_CHAIN:
10516 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10517 case Intrinsic::arm_neon_vld1:
10518 case Intrinsic::arm_neon_vld2:
10519 case Intrinsic::arm_neon_vld3:
10520 case Intrinsic::arm_neon_vld4:
10521 case Intrinsic::arm_neon_vld2lane:
10522 case Intrinsic::arm_neon_vld3lane:
10523 case Intrinsic::arm_neon_vld4lane:
10524 case Intrinsic::arm_neon_vst1:
10525 case Intrinsic::arm_neon_vst2:
10526 case Intrinsic::arm_neon_vst3:
10527 case Intrinsic::arm_neon_vst4:
10528 case Intrinsic::arm_neon_vst2lane:
10529 case Intrinsic::arm_neon_vst3lane:
10530 case Intrinsic::arm_neon_vst4lane:
10531 return CombineBaseUpdate(N, DCI);
10539 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10541 return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10544 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
10545 // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10546 bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10548 switch (VT.getSimpleVT().SimpleTy) {
10554 // Unaligned access can use (for example) LRDB, LRDH, LDR
10555 if (AllowsUnaligned) {
10557 *Fast = Subtarget->hasV7Ops();
10564 // For any little-endian targets with neon, we can support unaligned ld/st
10565 // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10566 // A big-endian target may also explictly support unaligned accesses
10567 if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10577 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10578 unsigned AlignCheck) {
10579 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10580 (DstAlign == 0 || DstAlign % AlignCheck == 0));
10583 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10584 unsigned DstAlign, unsigned SrcAlign,
10585 bool IsMemset, bool ZeroMemset,
10587 MachineFunction &MF) const {
10588 const Function *F = MF.getFunction();
10590 // See if we can use NEON instructions for this...
10591 if ((!IsMemset || ZeroMemset) &&
10592 Subtarget->hasNEON() &&
10593 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10594 Attribute::NoImplicitFloat)) {
10597 (memOpAlign(SrcAlign, DstAlign, 16) ||
10598 (allowsUnalignedMemoryAccesses(MVT::v2f64, &Fast) && Fast))) {
10600 } else if (Size >= 8 &&
10601 (memOpAlign(SrcAlign, DstAlign, 8) ||
10602 (allowsUnalignedMemoryAccesses(MVT::f64, &Fast) && Fast))) {
10607 // Lowering to i32/i16 if the size permits.
10610 else if (Size >= 2)
10613 // Let the target-independent logic figure it out.
10617 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10618 if (Val.getOpcode() != ISD::LOAD)
10621 EVT VT1 = Val.getValueType();
10622 if (!VT1.isSimple() || !VT1.isInteger() ||
10623 !VT2.isSimple() || !VT2.isInteger())
10626 switch (VT1.getSimpleVT().SimpleTy) {
10631 // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10638 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10639 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10642 if (!isTypeLegal(EVT::getEVT(Ty1)))
10645 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10647 // Assuming the caller doesn't have a zeroext or signext return parameter,
10648 // truncation all the way down to i1 is valid.
10653 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10657 unsigned Scale = 1;
10658 switch (VT.getSimpleVT().SimpleTy) {
10659 default: return false;
10674 if ((V & (Scale - 1)) != 0)
10677 return V == (V & ((1LL << 5) - 1));
10680 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10681 const ARMSubtarget *Subtarget) {
10682 bool isNeg = false;
10688 switch (VT.getSimpleVT().SimpleTy) {
10689 default: return false;
10694 // + imm12 or - imm8
10696 return V == (V & ((1LL << 8) - 1));
10697 return V == (V & ((1LL << 12) - 1));
10700 // Same as ARM mode. FIXME: NEON?
10701 if (!Subtarget->hasVFP2())
10706 return V == (V & ((1LL << 8) - 1));
10710 /// isLegalAddressImmediate - Return true if the integer value can be used
10711 /// as the offset of the target addressing mode for load / store of the
10713 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10714 const ARMSubtarget *Subtarget) {
10718 if (!VT.isSimple())
10721 if (Subtarget->isThumb1Only())
10722 return isLegalT1AddressImmediate(V, VT);
10723 else if (Subtarget->isThumb2())
10724 return isLegalT2AddressImmediate(V, VT, Subtarget);
10729 switch (VT.getSimpleVT().SimpleTy) {
10730 default: return false;
10735 return V == (V & ((1LL << 12) - 1));
10738 return V == (V & ((1LL << 8) - 1));
10741 if (!Subtarget->hasVFP2()) // FIXME: NEON?
10746 return V == (V & ((1LL << 8) - 1));
10750 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10752 int Scale = AM.Scale;
10756 switch (VT.getSimpleVT().SimpleTy) {
10757 default: return false;
10765 Scale = Scale & ~1;
10766 return Scale == 2 || Scale == 4 || Scale == 8;
10769 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10773 // Note, we allow "void" uses (basically, uses that aren't loads or
10774 // stores), because arm allows folding a scale into many arithmetic
10775 // operations. This should be made more precise and revisited later.
10777 // Allow r << imm, but the imm has to be a multiple of two.
10778 if (Scale & 1) return false;
10779 return isPowerOf2_32(Scale);
10783 /// isLegalAddressingMode - Return true if the addressing mode represented
10784 /// by AM is legal for this target, for a load/store of the specified type.
10785 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10787 EVT VT = getValueType(Ty, true);
10788 if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10791 // Can never fold addr of global into load/store.
10795 switch (AM.Scale) {
10796 case 0: // no scale reg, must be "r+i" or "r", or "i".
10799 if (Subtarget->isThumb1Only())
10803 // ARM doesn't support any R+R*scale+imm addr modes.
10807 if (!VT.isSimple())
10810 if (Subtarget->isThumb2())
10811 return isLegalT2ScaledAddressingMode(AM, VT);
10813 int Scale = AM.Scale;
10814 switch (VT.getSimpleVT().SimpleTy) {
10815 default: return false;
10819 if (Scale < 0) Scale = -Scale;
10823 return isPowerOf2_32(Scale & ~1);
10827 if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10832 // Note, we allow "void" uses (basically, uses that aren't loads or
10833 // stores), because arm allows folding a scale into many arithmetic
10834 // operations. This should be made more precise and revisited later.
10836 // Allow r << imm, but the imm has to be a multiple of two.
10837 if (Scale & 1) return false;
10838 return isPowerOf2_32(Scale);
10844 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10845 /// icmp immediate, that is the target has icmp instructions which can compare
10846 /// a register against the immediate without having to materialize the
10847 /// immediate into a register.
10848 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10849 // Thumb2 and ARM modes can use cmn for negative immediates.
10850 if (!Subtarget->isThumb())
10851 return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10852 if (Subtarget->isThumb2())
10853 return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10854 // Thumb1 doesn't have cmn, and only 8-bit immediates.
10855 return Imm >= 0 && Imm <= 255;
10858 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10859 /// *or sub* immediate, that is the target has add or sub instructions which can
10860 /// add a register with the immediate without having to materialize the
10861 /// immediate into a register.
10862 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10863 // Same encoding for add/sub, just flip the sign.
10864 int64_t AbsImm = llvm::abs64(Imm);
10865 if (!Subtarget->isThumb())
10866 return ARM_AM::getSOImmVal(AbsImm) != -1;
10867 if (Subtarget->isThumb2())
10868 return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10869 // Thumb1 only has 8-bit unsigned immediate.
10870 return AbsImm >= 0 && AbsImm <= 255;
10873 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10874 bool isSEXTLoad, SDValue &Base,
10875 SDValue &Offset, bool &isInc,
10876 SelectionDAG &DAG) {
10877 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10880 if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10881 // AddressingMode 3
10882 Base = Ptr->getOperand(0);
10883 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10884 int RHSC = (int)RHS->getZExtValue();
10885 if (RHSC < 0 && RHSC > -256) {
10886 assert(Ptr->getOpcode() == ISD::ADD);
10888 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10892 isInc = (Ptr->getOpcode() == ISD::ADD);
10893 Offset = Ptr->getOperand(1);
10895 } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10896 // AddressingMode 2
10897 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10898 int RHSC = (int)RHS->getZExtValue();
10899 if (RHSC < 0 && RHSC > -0x1000) {
10900 assert(Ptr->getOpcode() == ISD::ADD);
10902 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10903 Base = Ptr->getOperand(0);
10908 if (Ptr->getOpcode() == ISD::ADD) {
10910 ARM_AM::ShiftOpc ShOpcVal=
10911 ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10912 if (ShOpcVal != ARM_AM::no_shift) {
10913 Base = Ptr->getOperand(1);
10914 Offset = Ptr->getOperand(0);
10916 Base = Ptr->getOperand(0);
10917 Offset = Ptr->getOperand(1);
10922 isInc = (Ptr->getOpcode() == ISD::ADD);
10923 Base = Ptr->getOperand(0);
10924 Offset = Ptr->getOperand(1);
10928 // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10932 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10933 bool isSEXTLoad, SDValue &Base,
10934 SDValue &Offset, bool &isInc,
10935 SelectionDAG &DAG) {
10936 if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10939 Base = Ptr->getOperand(0);
10940 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10941 int RHSC = (int)RHS->getZExtValue();
10942 if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10943 assert(Ptr->getOpcode() == ISD::ADD);
10945 Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10947 } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10948 isInc = Ptr->getOpcode() == ISD::ADD;
10949 Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10957 /// getPreIndexedAddressParts - returns true by value, base pointer and
10958 /// offset pointer and addressing mode by reference if the node's address
10959 /// can be legally represented as pre-indexed load / store address.
10961 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10963 ISD::MemIndexedMode &AM,
10964 SelectionDAG &DAG) const {
10965 if (Subtarget->isThumb1Only())
10970 bool isSEXTLoad = false;
10971 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10972 Ptr = LD->getBasePtr();
10973 VT = LD->getMemoryVT();
10974 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10975 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10976 Ptr = ST->getBasePtr();
10977 VT = ST->getMemoryVT();
10982 bool isLegal = false;
10983 if (Subtarget->isThumb2())
10984 isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10985 Offset, isInc, DAG);
10987 isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10988 Offset, isInc, DAG);
10992 AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10996 /// getPostIndexedAddressParts - returns true by value, base pointer and
10997 /// offset pointer and addressing mode by reference if this node can be
10998 /// combined with a load / store to form a post-indexed load / store.
10999 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11002 ISD::MemIndexedMode &AM,
11003 SelectionDAG &DAG) const {
11004 if (Subtarget->isThumb1Only())
11009 bool isSEXTLoad = false;
11010 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11011 VT = LD->getMemoryVT();
11012 Ptr = LD->getBasePtr();
11013 isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11014 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11015 VT = ST->getMemoryVT();
11016 Ptr = ST->getBasePtr();
11021 bool isLegal = false;
11022 if (Subtarget->isThumb2())
11023 isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11026 isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
11032 // Swap base ptr and offset to catch more post-index load / store when
11033 // it's legal. In Thumb2 mode, offset must be an immediate.
11034 if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
11035 !Subtarget->isThumb2())
11036 std::swap(Base, Offset);
11038 // Post-indexed load / store update the base pointer.
11043 AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
11047 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
11050 const SelectionDAG &DAG,
11051 unsigned Depth) const {
11052 unsigned BitWidth = KnownOne.getBitWidth();
11053 KnownZero = KnownOne = APInt(BitWidth, 0);
11054 switch (Op.getOpcode()) {
11060 // These nodes' second result is a boolean
11061 if (Op.getResNo() == 0)
11063 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
11065 case ARMISD::CMOV: {
11066 // Bits are known zero/one if known on the LHS and RHS.
11067 DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
11068 if (KnownZero == 0 && KnownOne == 0) return;
11070 APInt KnownZeroRHS, KnownOneRHS;
11071 DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
11072 KnownZero &= KnownZeroRHS;
11073 KnownOne &= KnownOneRHS;
11079 //===----------------------------------------------------------------------===//
11080 // ARM Inline Assembly Support
11081 //===----------------------------------------------------------------------===//
11083 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
11084 // Looking for "rev" which is V6+.
11085 if (!Subtarget->hasV6Ops())
11088 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11089 std::string AsmStr = IA->getAsmString();
11090 SmallVector<StringRef, 4> AsmPieces;
11091 SplitString(AsmStr, AsmPieces, ";\n");
11093 switch (AsmPieces.size()) {
11094 default: return false;
11096 AsmStr = AsmPieces[0];
11098 SplitString(AsmStr, AsmPieces, " \t,");
11101 if (AsmPieces.size() == 3 &&
11102 AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
11103 IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
11104 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11105 if (Ty && Ty->getBitWidth() == 32)
11106 return IntrinsicLowering::LowerToByteSwap(CI);
11114 /// getConstraintType - Given a constraint letter, return the type of
11115 /// constraint it is for this target.
11116 ARMTargetLowering::ConstraintType
11117 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
11118 if (Constraint.size() == 1) {
11119 switch (Constraint[0]) {
11121 case 'l': return C_RegisterClass;
11122 case 'w': return C_RegisterClass;
11123 case 'h': return C_RegisterClass;
11124 case 'x': return C_RegisterClass;
11125 case 't': return C_RegisterClass;
11126 case 'j': return C_Other; // Constant for movw.
11127 // An address with a single base register. Due to the way we
11128 // currently handle addresses it is the same as an 'r' memory constraint.
11129 case 'Q': return C_Memory;
11131 } else if (Constraint.size() == 2) {
11132 switch (Constraint[0]) {
11134 // All 'U+' constraints are addresses.
11135 case 'U': return C_Memory;
11138 return TargetLowering::getConstraintType(Constraint);
11141 /// Examine constraint type and operand type and determine a weight value.
11142 /// This object must already have been set up with the operand type
11143 /// and the current alternative constraint selected.
11144 TargetLowering::ConstraintWeight
11145 ARMTargetLowering::getSingleConstraintMatchWeight(
11146 AsmOperandInfo &info, const char *constraint) const {
11147 ConstraintWeight weight = CW_Invalid;
11148 Value *CallOperandVal = info.CallOperandVal;
11149 // If we don't have a value, we can't do a match,
11150 // but allow it at the lowest weight.
11151 if (CallOperandVal == NULL)
11153 Type *type = CallOperandVal->getType();
11154 // Look at the constraint type.
11155 switch (*constraint) {
11157 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11160 if (type->isIntegerTy()) {
11161 if (Subtarget->isThumb())
11162 weight = CW_SpecificReg;
11164 weight = CW_Register;
11168 if (type->isFloatingPointTy())
11169 weight = CW_Register;
11175 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11177 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11179 if (Constraint.size() == 1) {
11180 // GCC ARM Constraint Letters
11181 switch (Constraint[0]) {
11182 case 'l': // Low regs or general regs.
11183 if (Subtarget->isThumb())
11184 return RCPair(0U, &ARM::tGPRRegClass);
11185 return RCPair(0U, &ARM::GPRRegClass);
11186 case 'h': // High regs or no regs.
11187 if (Subtarget->isThumb())
11188 return RCPair(0U, &ARM::hGPRRegClass);
11191 return RCPair(0U, &ARM::GPRRegClass);
11193 if (VT == MVT::f32)
11194 return RCPair(0U, &ARM::SPRRegClass);
11195 if (VT.getSizeInBits() == 64)
11196 return RCPair(0U, &ARM::DPRRegClass);
11197 if (VT.getSizeInBits() == 128)
11198 return RCPair(0U, &ARM::QPRRegClass);
11201 if (VT == MVT::f32)
11202 return RCPair(0U, &ARM::SPR_8RegClass);
11203 if (VT.getSizeInBits() == 64)
11204 return RCPair(0U, &ARM::DPR_8RegClass);
11205 if (VT.getSizeInBits() == 128)
11206 return RCPair(0U, &ARM::QPR_8RegClass);
11209 if (VT == MVT::f32)
11210 return RCPair(0U, &ARM::SPRRegClass);
11214 if (StringRef("{cc}").equals_lower(Constraint))
11215 return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11217 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11220 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11221 /// vector. If it is invalid, don't add anything to Ops.
11222 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11223 std::string &Constraint,
11224 std::vector<SDValue>&Ops,
11225 SelectionDAG &DAG) const {
11226 SDValue Result(0, 0);
11228 // Currently only support length 1 constraints.
11229 if (Constraint.length() != 1) return;
11231 char ConstraintLetter = Constraint[0];
11232 switch (ConstraintLetter) {
11235 case 'I': case 'J': case 'K': case 'L':
11236 case 'M': case 'N': case 'O':
11237 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11241 int64_t CVal64 = C->getSExtValue();
11242 int CVal = (int) CVal64;
11243 // None of these constraints allow values larger than 32 bits. Check
11244 // that the value fits in an int.
11245 if (CVal != CVal64)
11248 switch (ConstraintLetter) {
11250 // Constant suitable for movw, must be between 0 and
11252 if (Subtarget->hasV6T2Ops())
11253 if (CVal >= 0 && CVal <= 65535)
11257 if (Subtarget->isThumb1Only()) {
11258 // This must be a constant between 0 and 255, for ADD
11260 if (CVal >= 0 && CVal <= 255)
11262 } else if (Subtarget->isThumb2()) {
11263 // A constant that can be used as an immediate value in a
11264 // data-processing instruction.
11265 if (ARM_AM::getT2SOImmVal(CVal) != -1)
11268 // A constant that can be used as an immediate value in a
11269 // data-processing instruction.
11270 if (ARM_AM::getSOImmVal(CVal) != -1)
11276 if (Subtarget->isThumb()) { // FIXME thumb2
11277 // This must be a constant between -255 and -1, for negated ADD
11278 // immediates. This can be used in GCC with an "n" modifier that
11279 // prints the negated value, for use with SUB instructions. It is
11280 // not useful otherwise but is implemented for compatibility.
11281 if (CVal >= -255 && CVal <= -1)
11284 // This must be a constant between -4095 and 4095. It is not clear
11285 // what this constraint is intended for. Implemented for
11286 // compatibility with GCC.
11287 if (CVal >= -4095 && CVal <= 4095)
11293 if (Subtarget->isThumb1Only()) {
11294 // A 32-bit value where only one byte has a nonzero value. Exclude
11295 // zero to match GCC. This constraint is used by GCC internally for
11296 // constants that can be loaded with a move/shift combination.
11297 // It is not useful otherwise but is implemented for compatibility.
11298 if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11300 } else if (Subtarget->isThumb2()) {
11301 // A constant whose bitwise inverse can be used as an immediate
11302 // value in a data-processing instruction. This can be used in GCC
11303 // with a "B" modifier that prints the inverted value, for use with
11304 // BIC and MVN instructions. It is not useful otherwise but is
11305 // implemented for compatibility.
11306 if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11309 // A constant whose bitwise inverse can be used as an immediate
11310 // value in a data-processing instruction. This can be used in GCC
11311 // with a "B" modifier that prints the inverted value, for use with
11312 // BIC and MVN instructions. It is not useful otherwise but is
11313 // implemented for compatibility.
11314 if (ARM_AM::getSOImmVal(~CVal) != -1)
11320 if (Subtarget->isThumb1Only()) {
11321 // This must be a constant between -7 and 7,
11322 // for 3-operand ADD/SUB immediate instructions.
11323 if (CVal >= -7 && CVal < 7)
11325 } else if (Subtarget->isThumb2()) {
11326 // A constant whose negation can be used as an immediate value in a
11327 // data-processing instruction. This can be used in GCC with an "n"
11328 // modifier that prints the negated value, for use with SUB
11329 // instructions. It is not useful otherwise but is implemented for
11331 if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11334 // A constant whose negation can be used as an immediate value in a
11335 // data-processing instruction. This can be used in GCC with an "n"
11336 // modifier that prints the negated value, for use with SUB
11337 // instructions. It is not useful otherwise but is implemented for
11339 if (ARM_AM::getSOImmVal(-CVal) != -1)
11345 if (Subtarget->isThumb()) { // FIXME thumb2
11346 // This must be a multiple of 4 between 0 and 1020, for
11347 // ADD sp + immediate.
11348 if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11351 // A power of two or a constant between 0 and 32. This is used in
11352 // GCC for the shift amount on shifted register operands, but it is
11353 // useful in general for any shift amounts.
11354 if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11360 if (Subtarget->isThumb()) { // FIXME thumb2
11361 // This must be a constant between 0 and 31, for shift amounts.
11362 if (CVal >= 0 && CVal <= 31)
11368 if (Subtarget->isThumb()) { // FIXME thumb2
11369 // This must be a multiple of 4 between -508 and 508, for
11370 // ADD/SUB sp = sp + immediate.
11371 if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11376 Result = DAG.getTargetConstant(CVal, Op.getValueType());
11380 if (Result.getNode()) {
11381 Ops.push_back(Result);
11384 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11387 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11388 assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11389 unsigned Opcode = Op->getOpcode();
11390 assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11391 "Invalid opcode for Div/Rem lowering");
11392 bool isSigned = (Opcode == ISD::SDIVREM);
11393 EVT VT = Op->getValueType(0);
11394 Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11397 switch (VT.getSimpleVT().SimpleTy) {
11398 default: llvm_unreachable("Unexpected request for libcall!");
11399 case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
11400 case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11401 case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11402 case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11405 SDValue InChain = DAG.getEntryNode();
11407 TargetLowering::ArgListTy Args;
11408 TargetLowering::ArgListEntry Entry;
11409 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11410 EVT ArgVT = Op->getOperand(i).getValueType();
11411 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11412 Entry.Node = Op->getOperand(i);
11414 Entry.isSExt = isSigned;
11415 Entry.isZExt = !isSigned;
11416 Args.push_back(Entry);
11419 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11422 Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11426 CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11427 0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11428 /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11429 Callee, Args, DAG, dl);
11430 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11432 return CallInfo.first;
11436 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11437 // The ARM target isn't yet aware of offsets.
11441 bool ARM::isBitFieldInvertedMask(unsigned v) {
11442 if (v == 0xffffffff)
11445 // there can be 1's on either or both "outsides", all the "inside"
11446 // bits must be 0's
11447 unsigned TO = CountTrailingOnes_32(v);
11448 unsigned LO = CountLeadingOnes_32(v);
11449 v = (v >> TO) << TO;
11450 v = (v << LO) >> LO;
11454 /// isFPImmLegal - Returns true if the target can instruction select the
11455 /// specified FP immediate natively. If false, the legalizer will
11456 /// materialize the FP immediate as a load from a constant pool.
11457 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11458 if (!Subtarget->hasVFP3())
11460 if (VT == MVT::f32)
11461 return ARM_AM::getFP32Imm(Imm) != -1;
11462 if (VT == MVT::f64)
11463 return ARM_AM::getFP64Imm(Imm) != -1;
11467 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11468 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
11469 /// specified in the intrinsic calls.
11470 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11472 unsigned Intrinsic) const {
11473 switch (Intrinsic) {
11474 case Intrinsic::arm_neon_vld1:
11475 case Intrinsic::arm_neon_vld2:
11476 case Intrinsic::arm_neon_vld3:
11477 case Intrinsic::arm_neon_vld4:
11478 case Intrinsic::arm_neon_vld2lane:
11479 case Intrinsic::arm_neon_vld3lane:
11480 case Intrinsic::arm_neon_vld4lane: {
11481 Info.opc = ISD::INTRINSIC_W_CHAIN;
11482 // Conservatively set memVT to the entire set of vectors loaded.
11483 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11484 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11485 Info.ptrVal = I.getArgOperand(0);
11487 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11488 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11489 Info.vol = false; // volatile loads with NEON intrinsics not supported
11490 Info.readMem = true;
11491 Info.writeMem = false;
11494 case Intrinsic::arm_neon_vst1:
11495 case Intrinsic::arm_neon_vst2:
11496 case Intrinsic::arm_neon_vst3:
11497 case Intrinsic::arm_neon_vst4:
11498 case Intrinsic::arm_neon_vst2lane:
11499 case Intrinsic::arm_neon_vst3lane:
11500 case Intrinsic::arm_neon_vst4lane: {
11501 Info.opc = ISD::INTRINSIC_VOID;
11502 // Conservatively set memVT to the entire set of vectors stored.
11503 unsigned NumElts = 0;
11504 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11505 Type *ArgTy = I.getArgOperand(ArgI)->getType();
11506 if (!ArgTy->isVectorTy())
11508 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11510 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11511 Info.ptrVal = I.getArgOperand(0);
11513 Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11514 Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11515 Info.vol = false; // volatile stores with NEON intrinsics not supported
11516 Info.readMem = false;
11517 Info.writeMem = true;
11520 case Intrinsic::arm_ldrex: {
11521 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11522 Info.opc = ISD::INTRINSIC_W_CHAIN;
11523 Info.memVT = MVT::getVT(PtrTy->getElementType());
11524 Info.ptrVal = I.getArgOperand(0);
11526 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11528 Info.readMem = true;
11529 Info.writeMem = false;
11532 case Intrinsic::arm_strex: {
11533 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11534 Info.opc = ISD::INTRINSIC_W_CHAIN;
11535 Info.memVT = MVT::getVT(PtrTy->getElementType());
11536 Info.ptrVal = I.getArgOperand(1);
11538 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11540 Info.readMem = false;
11541 Info.writeMem = true;
11544 case Intrinsic::arm_strexd: {
11545 Info.opc = ISD::INTRINSIC_W_CHAIN;
11546 Info.memVT = MVT::i64;
11547 Info.ptrVal = I.getArgOperand(2);
11551 Info.readMem = false;
11552 Info.writeMem = true;
11555 case Intrinsic::arm_ldrexd: {
11556 Info.opc = ISD::INTRINSIC_W_CHAIN;
11557 Info.memVT = MVT::i64;
11558 Info.ptrVal = I.getArgOperand(0);
11562 Info.readMem = true;
11563 Info.writeMem = false;